Add ruff (lint + format) and ty (type checking) to the project
Adds [tool.ruff] and [tool.ty] config to pyproject.toml with a curated ruff rule set (E, F, W, I, UP, B, C4, SIM, RUF, ASYNC, LOG, G, PIE, RET, PERF, N), pins ruff/ty in requirements-dev.txt, reformats the whole tree with `ruff format`, and fixes the pre-existing lint and type-check debt those tools surfaced so both run clean. Production-code type fixes include: HA's ConfigFlowResult vs. the generic FlowResult in config_flow.py, narrowing BoundEntity.desc to its platform-specific subclass (SelectDesc/NumberDesc/SensorDesc/etc.) via cast() instead of an unchecked annotation, converting HA device_class strings to their proper enum types, a resolve_registry callback typed as `object` instead of `DeviceRegistry | None`, and a couple of other narrow correctness fixes (CA key type validation, an index-out-of-bounds false positive from an empty-tuple fallback, a bool/dict argument swap). Test-file fixes are mechanical: narrowing SamsungEntityDescription to the correct subclass via isinstance()/cast() before accessing subclass-only fields, and asserting Optional write_fn/unit_fn fields are set before calling them.
This commit is contained in:
147 files changed
+9977
-7584
No files matched your search
+23
-19
@@ -3,16 +3,17 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
|
||||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||
|
||||
|
||||
def _resources_from_dump(dump: dict) -> dict[str, dict]:
|
||||
from custom_components.localthings.registry.batch import parse_device0_batch
|
||||
return parse_device0_batch(dump['device0'])
|
||||
|
||||
return parse_device0_batch(dump["device0"])
|
||||
|
||||
|
||||
def _load_device(name: str) -> dict[str, dict]:
|
||||
data = json.loads((FIXTURES / f'{name}_device.json').read_text())
|
||||
data = json.loads((FIXTURES / f"{name}_device.json").read_text())
|
||||
return _resources_from_dump(data)
|
||||
|
||||
|
||||
@@ -33,10 +34,10 @@ def _load_device_full(name: str):
|
||||
ARTIK051_DONGLE_FAC_18K fixture) is folded into `seeds` here, since
|
||||
FakeCoapSession answers both shapes off the same href key.
|
||||
"""
|
||||
data = json.loads((FIXTURES / f'{name}_device.json').read_text())
|
||||
data = json.loads((FIXTURES / f"{name}_device.json").read_text())
|
||||
resources = _resources_from_dump(data)
|
||||
seeds = {**data.get('seeds', {}), **data.get('probes', {})}
|
||||
return resources, data.get('oic_res', []), seeds
|
||||
seeds = {**data.get("seeds", {}), **data.get("probes", {})}
|
||||
return resources, data.get("oic_res", []), seeds
|
||||
|
||||
|
||||
class FakeCoapSession:
|
||||
@@ -57,11 +58,12 @@ class FakeCoapSession:
|
||||
self.seeds = seeds or {}
|
||||
|
||||
def get(self, path, timeout=None):
|
||||
href = '/' + '/'.join(path)
|
||||
href = "/" + "/".join(path)
|
||||
body = self.seeds.get(href)
|
||||
if body is None:
|
||||
return 0x84, b'' # 4.04 not found -- tolerated absence
|
||||
return 0x84, b"" # 4.04 not found -- tolerated absence
|
||||
import cbor2
|
||||
|
||||
return 0x45, cbor2.dumps(body)
|
||||
|
||||
def pace(self):
|
||||
@@ -87,14 +89,18 @@ def _discover_full(resources: dict[str, dict], oic_res, seeds: dict[str, list]):
|
||||
from custom_components.localthings.registry.by_type import resolve
|
||||
from custom_components.localthings.registry.registry import CAPABILITIES
|
||||
from custom_components.localthings.registry.subdevices import (
|
||||
discover_partitioned, enumerate_subdevices,
|
||||
discover_partitioned,
|
||||
enumerate_subdevices,
|
||||
)
|
||||
|
||||
sess = FakeCoapSession(seeds)
|
||||
candidates, extra = enumerate_subdevices(sess, resources, oic_res)
|
||||
full_resources = {**resources, **extra}
|
||||
bound, device_type_name, materialized, skipped = discover_partitioned(
|
||||
full_resources, candidates, resolve, CAPABILITIES,
|
||||
full_resources,
|
||||
candidates,
|
||||
resolve,
|
||||
CAPABILITIES,
|
||||
)
|
||||
return bound, materialized, skipped, full_resources, device_type_name
|
||||
|
||||
@@ -102,8 +108,8 @@ def _discover_full(resources: dict[str, dict], oic_res, seeds: dict[str, list]):
|
||||
def _load_resources(ip: str) -> dict[str, dict]:
|
||||
"""Legacy IP-based loader — maps known IPs to named fixtures."""
|
||||
_ip_to_name = {
|
||||
'10.0.0.129': 'dishwasher',
|
||||
'10.0.0.254': 'refrigerator',
|
||||
"10.0.0.129": "dishwasher",
|
||||
"10.0.0.254": "refrigerator",
|
||||
}
|
||||
name = _ip_to_name.get(ip)
|
||||
if name is None:
|
||||
@@ -113,17 +119,17 @@ def _load_resources(ip: str) -> dict[str, dict]:
|
||||
|
||||
@pytest.fixture
|
||||
def dishwasher_resources() -> dict[str, dict]:
|
||||
return _load_device('dishwasher')
|
||||
return _load_device("dishwasher")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fridge_resources() -> dict[str, dict]:
|
||||
return _load_device('refrigerator')
|
||||
return _load_device("refrigerator")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def washer_resources() -> dict[str, dict]:
|
||||
return _load_device('washer')
|
||||
return _load_device("washer")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -134,8 +140,6 @@ def all_device_fixtures() -> dict[str, dict[str, dict]]:
|
||||
device -- so a newly added dump exercises them automatically.
|
||||
"""
|
||||
return {
|
||||
path.name[:-len('_device.json')]: _resources_from_dump(
|
||||
json.loads(path.read_text())
|
||||
)
|
||||
for path in sorted(FIXTURES.glob('*_device.json'))
|
||||
path.name[: -len("_device.json")]: _resources_from_dump(json.loads(path.read_text()))
|
||||
for path in sorted(FIXTURES.glob("*_device.json"))
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Shared fixtures for localthings component tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -10,6 +11,17 @@ import cbor2
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.localthings.const import (
|
||||
CONF_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM,
|
||||
CONF_HOST,
|
||||
CONF_LEAF_CERT_PEM,
|
||||
CONF_LEAF_KEY_PEM,
|
||||
CONF_PORT,
|
||||
DOMAIN,
|
||||
)
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
|
||||
# Point HA's config dir at the repo root so the loader mounts custom_components/
|
||||
# from the project into sys.path — otherwise IntegrationNotFound is raised.
|
||||
PROJECT_ROOT = str(Path(__file__).resolve().parents[2])
|
||||
@@ -33,13 +45,6 @@ def auto_enable_custom_integrations(enable_custom_integrations):
|
||||
return enable_custom_integrations
|
||||
|
||||
|
||||
from custom_components.localthings.const import (
|
||||
CONF_CA_CERT_PEM, CONF_CA_KEY_PEM,
|
||||
CONF_HOST, CONF_LEAF_CERT_PEM, CONF_LEAF_KEY_PEM, CONF_PORT, DOMAIN,
|
||||
)
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fast_coordinator_timers():
|
||||
"""Shrink the coordinator's real-time delays for every localthings test.
|
||||
@@ -58,36 +63,38 @@ def _fast_coordinator_timers():
|
||||
still pass `grace_period_s=` explicitly and are unaffected.
|
||||
"""
|
||||
with (
|
||||
patch.object(LocalThingsCoordinator, '_SUBPOLL_STEP_S', 0.001),
|
||||
patch.object(LocalThingsCoordinator, '_OBSERVE_GRACE_PERIOD_S', 0.02),
|
||||
patch.object(LocalThingsCoordinator, '_RECONNECT_PAUSE_S', 0.01),
|
||||
patch.object(LocalThingsCoordinator, "_SUBPOLL_STEP_S", 0.001),
|
||||
patch.object(LocalThingsCoordinator, "_OBSERVE_GRACE_PERIOD_S", 0.02),
|
||||
patch.object(LocalThingsCoordinator, "_RECONNECT_PAUSE_S", 0.01),
|
||||
):
|
||||
yield
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parent.parent / 'fixtures'
|
||||
|
||||
MOCK_HOST = '10.0.0.254'
|
||||
FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"
|
||||
|
||||
MOCK_HOST = "10.0.0.254"
|
||||
MOCK_PORT = 49154
|
||||
MOCK_SERIAL = 'TEST-SERIAL-001'
|
||||
MOCK_CA_CERT_PEM = '-----BEGIN CERTIFICATE-----\nTEST-CA\n-----END CERTIFICATE-----'
|
||||
MOCK_CA_KEY_PEM = '-----BEGIN PRIVATE KEY-----\nTEST-CA-KEY\n-----END PRIVATE KEY-----'
|
||||
MOCK_LEAF_CERT_PEM = '-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----'
|
||||
MOCK_LEAF_KEY_PEM = '-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----'
|
||||
MOCK_SERIAL = "TEST-SERIAL-001"
|
||||
MOCK_CA_CERT_PEM = "-----BEGIN CERTIFICATE-----\nTEST-CA\n-----END CERTIFICATE-----"
|
||||
MOCK_CA_KEY_PEM = "-----BEGIN PRIVATE KEY-----\nTEST-CA-KEY\n-----END PRIVATE KEY-----"
|
||||
MOCK_LEAF_CERT_PEM = "-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----"
|
||||
MOCK_LEAF_KEY_PEM = "-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----"
|
||||
|
||||
ENTRY_DATA = {
|
||||
CONF_HOST: MOCK_HOST,
|
||||
CONF_PORT: MOCK_PORT,
|
||||
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
|
||||
CONF_HOST: MOCK_HOST,
|
||||
CONF_PORT: MOCK_PORT,
|
||||
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
|
||||
CONF_LEAF_CERT_PEM: MOCK_LEAF_CERT_PEM,
|
||||
CONF_LEAF_KEY_PEM: MOCK_LEAF_KEY_PEM,
|
||||
CONF_LEAF_KEY_PEM: MOCK_LEAF_KEY_PEM,
|
||||
}
|
||||
|
||||
|
||||
def _load_fridge_resources() -> dict:
|
||||
from custom_components.localthings.registry.batch import parse_device0_batch
|
||||
data = json.loads((FIXTURES / 'refrigerator_device.json').read_text())
|
||||
return parse_device0_batch(data['device0'])
|
||||
|
||||
data = json.loads((FIXTURES / "refrigerator_device.json").read_text())
|
||||
return parse_device0_batch(data["device0"])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -99,13 +106,13 @@ def fridge_resources():
|
||||
def mock_probe():
|
||||
"""Patch _probe_and_validate to succeed (recognized type) without a real DTLS connection."""
|
||||
with patch(
|
||||
'custom_components.localthings.config_flow._probe_and_validate',
|
||||
"custom_components.localthings.config_flow._probe_and_validate",
|
||||
return_value={
|
||||
'port': MOCK_PORT,
|
||||
'serial': MOCK_SERIAL,
|
||||
'leaf_cert_pem': MOCK_LEAF_CERT_PEM,
|
||||
'leaf_key_pem': MOCK_LEAF_KEY_PEM,
|
||||
'device_type_recognized': True,
|
||||
"port": MOCK_PORT,
|
||||
"serial": MOCK_SERIAL,
|
||||
"leaf_cert_pem": MOCK_LEAF_CERT_PEM,
|
||||
"leaf_key_pem": MOCK_LEAF_KEY_PEM,
|
||||
"device_type_recognized": True,
|
||||
},
|
||||
) as m:
|
||||
yield m
|
||||
@@ -115,13 +122,13 @@ def mock_probe():
|
||||
def mock_probe_unknown_type():
|
||||
"""Patch _probe_and_validate to succeed, but with an unrecognized device type."""
|
||||
with patch(
|
||||
'custom_components.localthings.config_flow._probe_and_validate',
|
||||
"custom_components.localthings.config_flow._probe_and_validate",
|
||||
return_value={
|
||||
'port': MOCK_PORT,
|
||||
'serial': MOCK_SERIAL,
|
||||
'leaf_cert_pem': MOCK_LEAF_CERT_PEM,
|
||||
'leaf_key_pem': MOCK_LEAF_KEY_PEM,
|
||||
'device_type_recognized': False,
|
||||
"port": MOCK_PORT,
|
||||
"serial": MOCK_SERIAL,
|
||||
"leaf_cert_pem": MOCK_LEAF_CERT_PEM,
|
||||
"leaf_key_pem": MOCK_LEAF_KEY_PEM,
|
||||
"device_type_recognized": False,
|
||||
},
|
||||
) as m:
|
||||
yield m
|
||||
@@ -131,12 +138,12 @@ def mock_probe_unknown_type():
|
||||
def mock_coordinator_session(fridge_resources):
|
||||
"""Patch coordinator's blocking session methods so no real DTLS is needed."""
|
||||
with (
|
||||
patch('custom_components.localthings.coordinator.LocalThingsCoordinator._connect_session'),
|
||||
patch("custom_components.localthings.coordinator.LocalThingsCoordinator._connect_session"),
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once",
|
||||
return_value=fridge_resources,
|
||||
),
|
||||
patch('custom_components.localthings.coordinator.LocalThingsCoordinator._close_session'),
|
||||
patch("custom_components.localthings.coordinator.LocalThingsCoordinator._close_session"),
|
||||
):
|
||||
yield
|
||||
|
||||
@@ -164,13 +171,13 @@ class FakeObserveSession:
|
||||
self.notify_on_subscribe: dict[str, Any] | None = None
|
||||
|
||||
def subscribe(self, path_segs):
|
||||
href = '/' + '/'.join(path_segs)
|
||||
href = "/" + "/".join(path_segs)
|
||||
if href in self.fail_hrefs:
|
||||
raise ConnectionError("subscribe failed")
|
||||
self.subscribed.append(href)
|
||||
if self.notify_on_subscribe is not None and self.on_notification is not None:
|
||||
self.on_notification(href, cbor2.dumps(self.notify_on_subscribe))
|
||||
return b'\x01'
|
||||
return b"\x01"
|
||||
|
||||
def refresh_observes(self, paths):
|
||||
return None
|
||||
@@ -192,14 +199,14 @@ def mock_coordinator_observe_session(fridge_resources):
|
||||
|
||||
with (
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._connect_session',
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator._connect_session",
|
||||
_connect,
|
||||
),
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once",
|
||||
return_value=fridge_resources,
|
||||
),
|
||||
patch('custom_components.localthings.coordinator.LocalThingsCoordinator._close_session'),
|
||||
patch("custom_components.localthings.coordinator.LocalThingsCoordinator._close_session"),
|
||||
):
|
||||
yield fake
|
||||
|
||||
@@ -210,7 +217,7 @@ def mock_entry(hass):
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_DATA,
|
||||
unique_id=f'localthings_{MOCK_SERIAL}',
|
||||
unique_id=f"localthings_{MOCK_SERIAL}",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
return entry
|
||||
@@ -1,32 +1,39 @@
|
||||
"""Tests for the localthings config flow."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.localthings.const import (
|
||||
CONF_BYPASS_REMOTE_CONTROL, CONF_CA_CERT_PEM, CONF_CA_KEY_PEM,
|
||||
CONF_HOST, CONF_PORT, DOMAIN,
|
||||
CONF_BYPASS_REMOTE_CONTROL,
|
||||
CONF_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM,
|
||||
CONF_HOST,
|
||||
CONF_PORT,
|
||||
DOMAIN,
|
||||
)
|
||||
|
||||
from .conftest import (
|
||||
ENTRY_DATA, MOCK_CA_CERT_PEM, MOCK_CA_KEY_PEM, MOCK_HOST, MOCK_PORT, MOCK_SERIAL,
|
||||
ENTRY_DATA,
|
||||
MOCK_CA_CERT_PEM,
|
||||
MOCK_CA_KEY_PEM,
|
||||
MOCK_HOST,
|
||||
MOCK_PORT,
|
||||
MOCK_SERIAL,
|
||||
)
|
||||
|
||||
|
||||
async def test_form_first_device(hass: HomeAssistant) -> None:
|
||||
"""First device: form asks for host, CA cert, and CA key."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'user'}
|
||||
)
|
||||
assert result['type'] == FlowResultType.FORM
|
||||
assert result['step_id'] == 'user'
|
||||
assert CONF_CA_CERT_PEM in result['data_schema'].schema
|
||||
assert CONF_CA_KEY_PEM in result['data_schema'].schema
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert CONF_CA_CERT_PEM in result["data_schema"].schema
|
||||
assert CONF_CA_KEY_PEM in result["data_schema"].schema
|
||||
|
||||
|
||||
async def test_form_second_device_reuses_creds(hass: HomeAssistant) -> None:
|
||||
@@ -34,28 +41,28 @@ async def test_form_second_device_reuses_creds(hass: HomeAssistant) -> None:
|
||||
existing = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA)
|
||||
existing.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'user'}
|
||||
)
|
||||
assert result['type'] == FlowResultType.FORM
|
||||
assert result['step_id'] == 'user_reuse'
|
||||
assert CONF_CA_CERT_PEM not in result['data_schema'].schema
|
||||
assert CONF_CA_KEY_PEM not in result['data_schema'].schema
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "user_reuse"
|
||||
assert CONF_CA_CERT_PEM not in result["data_schema"].schema
|
||||
assert CONF_CA_KEY_PEM not in result["data_schema"].schema
|
||||
|
||||
|
||||
async def test_successful_setup(hass: HomeAssistant, mock_probe) -> None:
|
||||
"""Happy path: valid IP connects, entry created with discovered port."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'user'}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result['flow_id'],
|
||||
{CONF_HOST: MOCK_HOST, CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM, CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM},
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: MOCK_HOST,
|
||||
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
|
||||
},
|
||||
)
|
||||
assert result['type'] == FlowResultType.CREATE_ENTRY
|
||||
assert result['data'][CONF_HOST] == MOCK_HOST
|
||||
assert result['data'][CONF_PORT] == MOCK_PORT
|
||||
assert result['data'][CONF_CA_CERT_PEM] == MOCK_CA_CERT_PEM
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_HOST] == MOCK_HOST
|
||||
assert result["data"][CONF_PORT] == MOCK_PORT
|
||||
assert result["data"][CONF_CA_CERT_PEM] == MOCK_CA_CERT_PEM
|
||||
|
||||
|
||||
def test_order_candidates_prefers_known_ports() -> None:
|
||||
@@ -64,7 +71,10 @@ def test_order_candidates_prefers_known_ports() -> None:
|
||||
from custom_components.localthings.config_flow import _order_candidates
|
||||
|
||||
assert _order_candidates([49160, 49153, 49155, 49154]) == [
|
||||
49154, 49155, 49153, 49160,
|
||||
49154,
|
||||
49155,
|
||||
49153,
|
||||
49160,
|
||||
]
|
||||
assert _order_candidates([49153]) == [49153]
|
||||
|
||||
@@ -88,7 +98,7 @@ def test_find_live_ports_detects_silent_port(socket_enabled) -> None:
|
||||
|
||||
reserve = [socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for _ in range(3)]
|
||||
for s in reserve:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
s.bind(("127.0.0.1", 0))
|
||||
ports = [s.getsockname()[1] for s in reserve]
|
||||
live_sock, live_port = reserve[0], ports[0]
|
||||
reserve[1].close()
|
||||
@@ -97,7 +107,9 @@ def test_find_live_ports_detects_silent_port(socket_enabled) -> None:
|
||||
|
||||
try:
|
||||
result = _find_live_ports(
|
||||
'127.0.0.1', [closed_ports[0], live_port, closed_ports[1]], 0.8,
|
||||
"127.0.0.1",
|
||||
[closed_ports[0], live_port, closed_ports[1]],
|
||||
0.8,
|
||||
)
|
||||
finally:
|
||||
live_sock.close()
|
||||
@@ -106,7 +118,8 @@ def test_find_live_ports_detects_silent_port(socket_enabled) -> None:
|
||||
|
||||
|
||||
def test_find_live_ports_rescues_preferred_ports_the_sweep_missed(
|
||||
socket_enabled, monkeypatch,
|
||||
socket_enabled,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""Issue #192: a segregated VLAN made the ICMP-based sweep call three
|
||||
closed ports live while missing the one port (a historically confirmed
|
||||
@@ -129,17 +142,17 @@ def test_find_live_ports_rescues_preferred_ports_the_sweep_missed(
|
||||
# once closed, loopback refuses datagrams to it, standing in for the
|
||||
# sweep wrongly ruling out a port we have strong prior evidence for.
|
||||
reserved = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
reserved.bind(('127.0.0.1', 0))
|
||||
reserved.bind(("127.0.0.1", 0))
|
||||
preferred_port = reserved.getsockname()[1]
|
||||
reserved.close()
|
||||
monkeypatch.setattr(config_flow, 'PREFERRED_PROBE_PORTS', [preferred_port])
|
||||
monkeypatch.setattr(config_flow, "PREFERRED_PROBE_PORTS", [preferred_port])
|
||||
|
||||
live_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
live_sock.bind(('127.0.0.1', 0))
|
||||
live_sock.bind(("127.0.0.1", 0))
|
||||
live_port = live_sock.getsockname()[1]
|
||||
|
||||
try:
|
||||
result = _find_live_ports('127.0.0.1', [preferred_port, live_port], 0.8)
|
||||
result = _find_live_ports("127.0.0.1", [preferred_port, live_port], 0.8)
|
||||
finally:
|
||||
live_sock.close()
|
||||
|
||||
@@ -155,15 +168,16 @@ async def test_probe_uses_discovered_low_port(hass: HomeAssistant, monkeypatch)
|
||||
from custom_components.localthings import config_flow
|
||||
|
||||
device0 = [
|
||||
{'rt': ['x.com.samsung.devcol']},
|
||||
{'href': '/information/vs/0', 'rep': {
|
||||
'x.com.samsung.da.modelNum':
|
||||
'DA_WM_TP1_21_COMMON|20375141|20010002001811424AA30217008A0000',
|
||||
'x.com.samsung.da.description':
|
||||
'DA_WM_TP1_21_COMMON_WW5000C/DC92-03495A_B048',
|
||||
'x.com.samsung.da.serialNum': 'DISHWASHER-49153',
|
||||
}},
|
||||
{'href': '/otninformation/vs/0', 'rep': {'otnStatus': 'None'}},
|
||||
{"rt": ["x.com.samsung.devcol"]},
|
||||
{
|
||||
"href": "/information/vs/0",
|
||||
"rep": {
|
||||
"x.com.samsung.da.modelNum": "DA_WM_TP1_21_COMMON|20375141|20010002001811424AA30217008A0000", # noqa: E501
|
||||
"x.com.samsung.da.description": "DA_WM_TP1_21_COMMON_WW5000C/DC92-03495A_B048",
|
||||
"x.com.samsung.da.serialNum": "DISHWASHER-49153",
|
||||
},
|
||||
},
|
||||
{"href": "/otninformation/vs/0", "rep": {"otnStatus": "None"}},
|
||||
]
|
||||
|
||||
class _FakeSession:
|
||||
@@ -182,28 +196,33 @@ async def test_probe_uses_discovered_low_port(hass: HomeAssistant, monkeypatch)
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(config_flow, '_fetch_samsung_uuid', lambda: 'test-uuid')
|
||||
monkeypatch.setattr(config_flow, "_fetch_samsung_uuid", lambda: "test-uuid")
|
||||
monkeypatch.setattr(
|
||||
config_flow, '_mint_leaf_cert',
|
||||
lambda ca_cert, ca_key, uuid: ('FULLCHAIN', 'LEAFKEY'),
|
||||
config_flow,
|
||||
"_mint_leaf_cert",
|
||||
lambda ca_cert, ca_key, uuid: ("FULLCHAIN", "LEAFKEY"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
config_flow, '_find_live_ports',
|
||||
config_flow,
|
||||
"_find_live_ports",
|
||||
lambda host, ports, timeout: [49153],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'smartthings_local.protocol.dtls_session.DtlsCoapSession', _FakeSession,
|
||||
"smartthings_local.protocol.dtls_session.DtlsCoapSession",
|
||||
_FakeSession,
|
||||
)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'user'}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result['flow_id'],
|
||||
{CONF_HOST: MOCK_HOST, CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM, CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM},
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: MOCK_HOST,
|
||||
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
|
||||
},
|
||||
)
|
||||
assert result['type'] == FlowResultType.CREATE_ENTRY
|
||||
assert result['data'][CONF_PORT] == 49153
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_PORT] == 49153
|
||||
|
||||
|
||||
async def test_cannot_connect(hass: HomeAssistant) -> None:
|
||||
@@ -211,53 +230,58 @@ async def test_cannot_connect(hass: HomeAssistant) -> None:
|
||||
from custom_components.localthings.config_flow import CannotConnect
|
||||
|
||||
with patch(
|
||||
'custom_components.localthings.config_flow._probe_and_validate',
|
||||
side_effect=CannotConnect('no port'),
|
||||
"custom_components.localthings.config_flow._probe_and_validate",
|
||||
side_effect=CannotConnect("no port"),
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'user'}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result['flow_id'],
|
||||
{CONF_HOST: MOCK_HOST, CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM, CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM},
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: MOCK_HOST,
|
||||
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
|
||||
},
|
||||
)
|
||||
assert result['type'] == FlowResultType.FORM
|
||||
assert result['errors']['base'] == 'cannot_connect'
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["errors"]["base"] == "cannot_connect"
|
||||
|
||||
|
||||
async def test_recognized_type_skips_confirmation_step(
|
||||
hass: HomeAssistant, mock_probe
|
||||
) -> None:
|
||||
async def test_recognized_type_skips_confirmation_step(hass: HomeAssistant, mock_probe) -> None:
|
||||
"""A recognized device type creates the entry with no extra step."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'user'}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result['flow_id'],
|
||||
{CONF_HOST: MOCK_HOST, CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM, CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM},
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: MOCK_HOST,
|
||||
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
|
||||
},
|
||||
)
|
||||
assert result['type'] == FlowResultType.CREATE_ENTRY
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
|
||||
|
||||
async def test_unknown_type_shows_confirmation_step(
|
||||
hass: HomeAssistant, mock_probe_unknown_type
|
||||
) -> None:
|
||||
"""An unrecognized device type shows a confirmation step before creating the entry."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'user'}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result['flow_id'],
|
||||
{CONF_HOST: MOCK_HOST, CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM, CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM},
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: MOCK_HOST,
|
||||
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
|
||||
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
|
||||
},
|
||||
)
|
||||
assert result['type'] == FlowResultType.FORM
|
||||
assert result['step_id'] == 'confirm_unknown_type'
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "confirm_unknown_type"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result['flow_id'], {},
|
||||
result["flow_id"],
|
||||
{},
|
||||
)
|
||||
assert result['type'] == FlowResultType.CREATE_ENTRY
|
||||
assert result['data'][CONF_HOST] == MOCK_HOST
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_HOST] == MOCK_HOST
|
||||
|
||||
|
||||
async def test_unknown_type_step_description_makes_no_version_claim(
|
||||
@@ -270,14 +294,19 @@ async def test_unknown_type_step_description_makes_no_version_claim(
|
||||
from pathlib import Path
|
||||
|
||||
steps = json.loads(
|
||||
(Path(__file__).parents[2] / 'custom_components' / 'localthings'
|
||||
/ 'translations' / 'en.json').read_text()
|
||||
)['config']['step']
|
||||
(
|
||||
Path(__file__).parents[2]
|
||||
/ "custom_components"
|
||||
/ "localthings"
|
||||
/ "translations"
|
||||
/ "en.json"
|
||||
).read_text()
|
||||
)["config"]["step"]
|
||||
|
||||
assert 'confirm_unknown_type_no_version' not in steps
|
||||
description = steps['confirm_unknown_type']['description']
|
||||
assert 'oneUiVersion' not in description
|
||||
assert '{' not in description # no unfilled placeholder
|
||||
assert "confirm_unknown_type_no_version" not in steps
|
||||
description = steps["confirm_unknown_type"]["description"]
|
||||
assert "oneUiVersion" not in description
|
||||
assert "{" not in description # no unfilled placeholder
|
||||
|
||||
|
||||
async def test_duplicate_device_aborted(hass: HomeAssistant, mock_probe) -> None:
|
||||
@@ -289,42 +318,42 @@ async def test_duplicate_device_aborted(hass: HomeAssistant, mock_probe) -> None
|
||||
existing = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_DATA,
|
||||
unique_id=f'localthings_{MOCK_SERIAL}',
|
||||
unique_id=f"localthings_{MOCK_SERIAL}",
|
||||
)
|
||||
existing.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'user'}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
|
||||
# Second-device form only has CONF_HOST; CA creds are reused from existing.
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result['flow_id'],
|
||||
result["flow_id"],
|
||||
{CONF_HOST: MOCK_HOST},
|
||||
)
|
||||
assert result['type'] == FlowResultType.ABORT
|
||||
assert result['reason'] == 'already_configured'
|
||||
assert result["type"] == FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
def test_probe_marks_washer_as_recognized(monkeypatch):
|
||||
"""A washer reports no oneUiVersion at all -- its consumer-model code
|
||||
must still resolve so setup doesn't warn about an unrecognized type."""
|
||||
from custom_components.localthings import config_flow
|
||||
|
||||
device0 = [
|
||||
{'rt': ['x.com.samsung.devcol']},
|
||||
{'href': '/information/vs/0', 'rep': {
|
||||
'x.com.samsung.da.modelNum':
|
||||
'DA_WM_TP1_21_COMMON|20375141|20010002001811424AA30217008A0000',
|
||||
'x.com.samsung.da.description':
|
||||
'DA_WM_TP1_21_COMMON_WW5000C/DC92-03495A_B048',
|
||||
'x.com.samsung.da.serialNum': 'TEST-SERIAL',
|
||||
}},
|
||||
{'href': '/otninformation/vs/0', 'rep': {'otnStatus': 'None'}},
|
||||
{"rt": ["x.com.samsung.devcol"]},
|
||||
{
|
||||
"href": "/information/vs/0",
|
||||
"rep": {
|
||||
"x.com.samsung.da.modelNum": "DA_WM_TP1_21_COMMON|20375141|20010002001811424AA30217008A0000", # noqa: E501
|
||||
"x.com.samsung.da.description": "DA_WM_TP1_21_COMMON_WW5000C/DC92-03495A_B048",
|
||||
"x.com.samsung.da.serialNum": "TEST-SERIAL",
|
||||
},
|
||||
},
|
||||
{"href": "/otninformation/vs/0", "rep": {"otnStatus": "None"}},
|
||||
]
|
||||
from custom_components.localthings.registry.batch import parse_device0_batch
|
||||
|
||||
resources = parse_device0_batch(device0)
|
||||
|
||||
from custom_components.localthings.registry.by_type import resolve
|
||||
|
||||
assert resolve(resources) is not None
|
||||
|
||||
|
||||
@@ -332,47 +361,47 @@ async def test_options_flow_init_shows_menu(hass: HomeAssistant) -> None:
|
||||
"""The options flow's entry point is now a menu (issue #54's debug
|
||||
panel lives alongside the remote-control settings), not the settings
|
||||
form directly."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}')
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
assert result['type'] == FlowResultType.MENU
|
||||
assert result['step_id'] == 'init'
|
||||
assert set(result['menu_options']) == {'settings', 'debug_write'}
|
||||
assert result["type"] == FlowResultType.MENU
|
||||
assert result["step_id"] == "init"
|
||||
assert set(result["menu_options"]) == {"settings", "debug_write"}
|
||||
|
||||
|
||||
async def test_options_flow_default_is_off(hass: HomeAssistant) -> None:
|
||||
"""The bypass defaults to False, so devices that never touch this
|
||||
option see no change in the remote-control write block."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}')
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'settings'}
|
||||
result["flow_id"], user_input={"next_step_id": "settings"}
|
||||
)
|
||||
|
||||
assert result['type'] == FlowResultType.FORM
|
||||
assert result['step_id'] == 'settings'
|
||||
assert result['data_schema']({})[CONF_BYPASS_REMOTE_CONTROL] is False
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "settings"
|
||||
assert result["data_schema"]({})[CONF_BYPASS_REMOTE_CONTROL] is False
|
||||
|
||||
|
||||
async def test_options_flow_can_enable_bypass(hass: HomeAssistant) -> None:
|
||||
"""Submitting the form with the toggle on stores it in entry.options,
|
||||
where coordinator.async_send_command reads it (issue #54)."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}')
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'settings'}
|
||||
result["flow_id"], user_input={"next_step_id": "settings"}
|
||||
)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={CONF_BYPASS_REMOTE_CONTROL: True}
|
||||
result["flow_id"], user_input={CONF_BYPASS_REMOTE_CONTROL: True}
|
||||
)
|
||||
|
||||
assert result['type'] == FlowResultType.CREATE_ENTRY
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert entry.options[CONF_BYPASS_REMOTE_CONTROL] is True
|
||||
|
||||
|
||||
@@ -380,36 +409,39 @@ async def test_options_flow_reflects_previously_saved_value(hass: HomeAssistant)
|
||||
"""Reopening the form shows the currently-saved choice as the default,
|
||||
not always False."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}',
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_DATA,
|
||||
unique_id=f"localthings_{MOCK_SERIAL}",
|
||||
options={CONF_BYPASS_REMOTE_CONTROL: True},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'settings'}
|
||||
result["flow_id"], user_input={"next_step_id": "settings"}
|
||||
)
|
||||
|
||||
assert result['data_schema']({})[CONF_BYPASS_REMOTE_CONTROL] is True
|
||||
assert result["data_schema"]({})[CONF_BYPASS_REMOTE_CONTROL] is True
|
||||
|
||||
|
||||
async def test_options_flow_debug_write_shows_hrefs_from_coordinator(
|
||||
hass: HomeAssistant, mock_coordinator_session,
|
||||
hass: HomeAssistant,
|
||||
mock_coordinator_session,
|
||||
) -> None:
|
||||
"""The debug panel's href dropdown is populated from the live
|
||||
coordinator's cached resources, not a static list."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}')
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'debug_write'}
|
||||
result["flow_id"], user_input={"next_step_id": "debug_write"}
|
||||
)
|
||||
|
||||
assert result['type'] == FlowResultType.FORM
|
||||
assert result['step_id'] == 'debug_write'
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "debug_write"
|
||||
|
||||
|
||||
async def test_options_flow_debug_write_aborts_when_device_not_loaded(
|
||||
@@ -417,83 +449,92 @@ async def test_options_flow_debug_write_aborts_when_device_not_loaded(
|
||||
) -> None:
|
||||
"""No coordinator in hass.data (device never finished loading) means
|
||||
the debug panel has nothing to write to or read from."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}')
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'debug_write'}
|
||||
result["flow_id"], user_input={"next_step_id": "debug_write"}
|
||||
)
|
||||
|
||||
assert result['type'] == FlowResultType.ABORT
|
||||
assert result['reason'] == 'not_loaded'
|
||||
assert result["type"] == FlowResultType.ABORT
|
||||
assert result["reason"] == "not_loaded"
|
||||
|
||||
|
||||
async def test_options_flow_debug_edit_writes_and_shows_result(
|
||||
hass: HomeAssistant, mock_coordinator_session,
|
||||
hass: HomeAssistant,
|
||||
mock_coordinator_session,
|
||||
) -> None:
|
||||
"""Picking an href, then submitting a payload, drives
|
||||
coordinator.async_raw_write and lands on the result menu with the
|
||||
device's response."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}')
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'debug_write'}
|
||||
result["flow_id"], user_input={"next_step_id": "debug_write"}
|
||||
)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'href': '/washer/vs/0'},
|
||||
result["flow_id"],
|
||||
user_input={"href": "/washer/vs/0"},
|
||||
)
|
||||
assert result['type'] == FlowResultType.FORM
|
||||
assert result['step_id'] == 'debug_edit'
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "debug_edit"
|
||||
|
||||
with patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator.async_raw_write',
|
||||
return_value=(0x44, {'a': 1}),
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator.async_raw_write",
|
||||
return_value=(0x44, {"a": 1}),
|
||||
):
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'payload': {'a': 1}},
|
||||
result["flow_id"],
|
||||
user_input={"payload": {"a": 1}},
|
||||
)
|
||||
|
||||
assert result['type'] == FlowResultType.MENU
|
||||
assert result['step_id'] == 'debug_result'
|
||||
assert result['description_placeholders']['code'] == '2.04 (0x44)'
|
||||
assert result["type"] == FlowResultType.MENU
|
||||
assert result["step_id"] == "debug_result"
|
||||
assert result["description_placeholders"]["code"] == "2.04 (0x44)"
|
||||
|
||||
|
||||
async def test_options_flow_debug_edit_rejects_empty_payload(
|
||||
hass: HomeAssistant, mock_coordinator_session,
|
||||
hass: HomeAssistant,
|
||||
mock_coordinator_session,
|
||||
) -> None:
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}')
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'debug_write'}
|
||||
result["flow_id"], user_input={"next_step_id": "debug_write"}
|
||||
)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'href': '/washer/vs/0'},
|
||||
result["flow_id"],
|
||||
user_input={"href": "/washer/vs/0"},
|
||||
)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'payload': {}},
|
||||
result["flow_id"],
|
||||
user_input={"payload": {}},
|
||||
)
|
||||
|
||||
assert result['type'] == FlowResultType.FORM
|
||||
assert result['step_id'] == 'debug_edit'
|
||||
assert result['errors'] == {'payload': 'empty_payload'}
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "debug_edit"
|
||||
assert result["errors"] == {"payload": "empty_payload"}
|
||||
|
||||
|
||||
async def test_options_flow_finish_preserves_existing_options(
|
||||
hass: HomeAssistant, mock_coordinator_session,
|
||||
hass: HomeAssistant,
|
||||
mock_coordinator_session,
|
||||
) -> None:
|
||||
"""Finishing from the debug-result menu must not clobber a previously
|
||||
saved remote-control bypass setting."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data=ENTRY_DATA, unique_id=f'localthings_{MOCK_SERIAL}',
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_DATA,
|
||||
unique_id=f"localthings_{MOCK_SERIAL}",
|
||||
options={CONF_BYPASS_REMOTE_CONTROL: True},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
@@ -502,26 +543,28 @@ async def test_options_flow_finish_preserves_existing_options(
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'debug_write'}
|
||||
result["flow_id"], user_input={"next_step_id": "debug_write"}
|
||||
)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'href': '/washer/vs/0'},
|
||||
result["flow_id"],
|
||||
user_input={"href": "/washer/vs/0"},
|
||||
)
|
||||
with patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator.async_raw_write',
|
||||
return_value=(0x44, {'a': 1}),
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator.async_raw_write",
|
||||
return_value=(0x44, {"a": 1}),
|
||||
):
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'payload': {'a': 1}},
|
||||
result["flow_id"],
|
||||
user_input={"payload": {"a": 1}},
|
||||
)
|
||||
assert result['type'] == FlowResultType.MENU
|
||||
assert result['step_id'] == 'debug_result'
|
||||
assert result["type"] == FlowResultType.MENU
|
||||
assert result["step_id"] == "debug_result"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result['flow_id'], user_input={'next_step_id': 'finish'}
|
||||
result["flow_id"], user_input={"next_step_id": "finish"}
|
||||
)
|
||||
|
||||
assert result['type'] == FlowResultType.CREATE_ENTRY
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert entry.options[CONF_BYPASS_REMOTE_CONTROL] is True
|
||||
|
||||
|
||||
@@ -530,15 +573,17 @@ def test_is_placeholder_serial_catches_nothing_svc():
|
||||
literal string 'Nothing(SVC)' as serialNum on every unit -- non-empty,
|
||||
so it must be caught by name, not by the plain `if not serial` check."""
|
||||
from custom_components.localthings.config_flow import _is_placeholder_serial
|
||||
assert _is_placeholder_serial('Nothing(SVC)') is True
|
||||
assert _is_placeholder_serial('nothing(svc)') is True
|
||||
assert _is_placeholder_serial(' Nothing(SVC) ') is True
|
||||
|
||||
assert _is_placeholder_serial("Nothing(SVC)") is True
|
||||
assert _is_placeholder_serial("nothing(svc)") is True
|
||||
assert _is_placeholder_serial(" Nothing(SVC) ") is True
|
||||
|
||||
|
||||
def test_is_placeholder_serial_accepts_real_serials():
|
||||
from custom_components.localthings.config_flow import _is_placeholder_serial
|
||||
assert _is_placeholder_serial('0A1B2C3D4E5F') is False
|
||||
assert _is_placeholder_serial('') is False
|
||||
|
||||
assert _is_placeholder_serial("0A1B2C3D4E5F") is False
|
||||
assert _is_placeholder_serial("") is False
|
||||
|
||||
|
||||
def test_is_placeholder_serial_catches_all_same_hex_digit():
|
||||
@@ -548,9 +593,10 @@ def test_is_placeholder_serial_catches_all_same_hex_digit():
|
||||
different physical units, both reported the literal serialNum
|
||||
'FFFFFFFFFFFFFFF', colliding on the config-entry unique_id."""
|
||||
from custom_components.localthings.config_flow import _is_placeholder_serial
|
||||
assert _is_placeholder_serial('FFFFFFFFFFFFFFF') is True
|
||||
assert _is_placeholder_serial('ffffffffffffffff') is True
|
||||
assert _is_placeholder_serial('00000000') is True
|
||||
|
||||
assert _is_placeholder_serial("FFFFFFFFFFFFFFF") is True
|
||||
assert _is_placeholder_serial("ffffffffffffffff") is True
|
||||
assert _is_placeholder_serial("00000000") is True
|
||||
# Too short to be the flash-unset sentinel -- a real serial could
|
||||
# plausibly repeat one hex digit seven times by chance.
|
||||
assert _is_placeholder_serial('FFFFFFF') is False
|
||||
assert _is_placeholder_serial("FFFFFFF") is False
|
||||
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,7 @@ refrigerator whose diagnostics now report no subdevices at all) sticks
|
||||
around forever. Defining this callback is what puts a working "Delete
|
||||
device" button on it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -20,7 +21,8 @@ from custom_components.localthings.registry.subdevices import Subdevice
|
||||
|
||||
def _device(hass, entry, identifiers) -> dr.DeviceEntry:
|
||||
return dr.async_get(hass).async_get_or_create(
|
||||
config_entry_id=entry.entry_id, identifiers=identifiers,
|
||||
config_entry_id=entry.entry_id,
|
||||
identifiers=identifiers,
|
||||
)
|
||||
|
||||
|
||||
@@ -33,9 +35,11 @@ async def test_stale_device_can_be_removed(
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
assert coordinator.subdevices == [] # this fixture is not a composite device
|
||||
assert coordinator.subdevices == [] # this fixture is not a composite device
|
||||
stale = _device(
|
||||
hass, mock_entry, {(DOMAIN, f'{coordinator.device_serial}_1')},
|
||||
hass,
|
||||
mock_entry,
|
||||
{(DOMAIN, f"{coordinator.device_serial}_1")},
|
||||
)
|
||||
|
||||
assert await async_remove_config_entry_device(hass, mock_entry, stale) is True
|
||||
@@ -50,7 +54,7 @@ async def test_master_device_cannot_be_removed(
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
master = _device(hass, mock_entry, set(coordinator.device_info['identifiers']))
|
||||
master = _device(hass, mock_entry, set(coordinator.device_info["identifiers"]))
|
||||
|
||||
assert await async_remove_config_entry_device(hass, mock_entry, master) is False
|
||||
|
||||
@@ -65,22 +69,24 @@ async def test_live_subdevice_device_cannot_be_removed(
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
subdevice = Subdevice(kind='indexed', key='1', seed_path=('device', '1'))
|
||||
subdevice = Subdevice(kind="indexed", key="1", seed_path=("device", "1"))
|
||||
coordinator.subdevices = [subdevice]
|
||||
live = _device(
|
||||
hass, mock_entry,
|
||||
set(coordinator.device_info_for(subdevice)['identifiers']),
|
||||
hass,
|
||||
mock_entry,
|
||||
set(coordinator.device_info_for(subdevice)["identifiers"]),
|
||||
)
|
||||
|
||||
assert await async_remove_config_entry_device(hass, mock_entry, live) is False
|
||||
|
||||
|
||||
async def test_removal_allowed_when_entry_is_not_loaded(
|
||||
hass: HomeAssistant, mock_entry,
|
||||
hass: HomeAssistant,
|
||||
mock_entry,
|
||||
) -> None:
|
||||
"""No coordinator means nothing is claiming the device -- don't strand
|
||||
it behind a callback that can't answer."""
|
||||
mock_entry.add_to_hass(hass)
|
||||
orphan = _device(hass, mock_entry, {(DOMAIN, 'whatever')})
|
||||
orphan = _device(hass, mock_entry, {(DOMAIN, "whatever")})
|
||||
|
||||
assert await async_remove_config_entry_device(hass, mock_entry, orphan) is True
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Tests for the diagnostics platform."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -13,8 +14,8 @@ from custom_components.localthings.diagnostics import async_get_config_entry_dia
|
||||
from custom_components.localthings.registry.redact import REDACTED
|
||||
|
||||
_MANIFEST_VERSION = json.loads(
|
||||
(Path(__file__).parents[2] / 'custom_components' / 'localthings' / 'manifest.json').read_text()
|
||||
)['version']
|
||||
(Path(__file__).parents[2] / "custom_components" / "localthings" / "manifest.json").read_text()
|
||||
)["version"]
|
||||
|
||||
|
||||
async def test_diagnostics_shape_and_redaction(
|
||||
@@ -25,17 +26,17 @@ async def test_diagnostics_shape_and_redaction(
|
||||
|
||||
diagnostics = await async_get_config_entry_diagnostics(hass, mock_entry)
|
||||
|
||||
assert diagnostics["device_type"] == 'refrigerator'
|
||||
assert diagnostics["one_ui_version"] == '7.0 Refrigerator'
|
||||
assert diagnostics["device_type"] == "refrigerator"
|
||||
assert diagnostics["one_ui_version"] == "7.0 Refrigerator"
|
||||
assert diagnostics["unbound_hrefs"] == []
|
||||
assert diagnostics["integration_version"] == _MANIFEST_VERSION
|
||||
assert diagnostics["smartthings_local_version"]
|
||||
|
||||
resources = diagnostics["resources"]
|
||||
assert resources['/information/vs/0']['x.com.samsung.da.serialNum'] == REDACTED
|
||||
assert resources['/wirelessinfo/vs/0']['macaddressWiFi'] == REDACTED
|
||||
assert resources["/information/vs/0"]["x.com.samsung.da.serialNum"] == REDACTED
|
||||
assert resources["/wirelessinfo/vs/0"]["macaddressWiFi"] == REDACTED
|
||||
# Ordinary state survives.
|
||||
assert resources['/status/lock/vs/0']['x.com.samsung.da.ado.devicecontrol'] == 'On'
|
||||
assert resources["/status/lock/vs/0"]["x.com.samsung.da.ado.devicecontrol"] == "On"
|
||||
|
||||
|
||||
async def test_diagnostics_include_ocf_identity(
|
||||
@@ -51,33 +52,36 @@ async def test_diagnostics_include_ocf_identity(
|
||||
|
||||
coordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
coordinator._identity = DeviceIdentity(
|
||||
manufacturer='Samsung Electronics',
|
||||
model='RF9000B',
|
||||
name='Family Hub',
|
||||
manufacturer="Samsung Electronics",
|
||||
model="RF9000B",
|
||||
name="Family Hub",
|
||||
serial=None,
|
||||
device_types=('oic.wk.d', 'oic.d.refrigerator'),
|
||||
device_types=("oic.wk.d", "oic.d.refrigerator"),
|
||||
raw={
|
||||
'/oic/p': {'mnmn': 'Samsung Electronics', 'pi': '12-34-56'},
|
||||
'/oic/d': {'n': 'Family Hub', 'di': 'ab-cd-ef',
|
||||
'rt': ['oic.wk.d', 'oic.d.refrigerator']},
|
||||
"/oic/p": {"mnmn": "Samsung Electronics", "pi": "12-34-56"},
|
||||
"/oic/d": {
|
||||
"n": "Family Hub",
|
||||
"di": "ab-cd-ef",
|
||||
"rt": ["oic.wk.d", "oic.d.refrigerator"],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, mock_entry)
|
||||
|
||||
identity = diag['identity']
|
||||
assert identity['model'] == 'RF9000B'
|
||||
assert identity['device_types'] == ['oic.wk.d', 'oic.d.refrigerator']
|
||||
identity = diag["identity"]
|
||||
assert identity["model"] == "RF9000B"
|
||||
assert identity["device_types"] == ["oic.wk.d", "oic.d.refrigerator"]
|
||||
# The raw payloads ride along whole -- we don't yet know which of their
|
||||
# fields identify a device type, so nothing is dropped up front beyond
|
||||
# what redaction takes out.
|
||||
assert identity['resources']['/oic/p']['mnmn'] == 'Samsung Electronics'
|
||||
assert identity['resources']['/oic/d']['di'] == REDACTED
|
||||
assert identity['resources']['/oic/p']['pi'] == REDACTED
|
||||
assert identity["resources"]["/oic/p"]["mnmn"] == "Samsung Electronics"
|
||||
assert identity["resources"]["/oic/d"]["di"] == REDACTED
|
||||
assert identity["resources"]["/oic/p"]["pi"] == REDACTED
|
||||
# The owner-settable device name is redacted; `rt` -- the reason this
|
||||
# block exists -- is not.
|
||||
assert identity['resources']['/oic/d']['n'] == REDACTED
|
||||
assert identity['resources']['/oic/d']['rt'] == ['oic.wk.d', 'oic.d.refrigerator']
|
||||
assert identity["resources"]["/oic/d"]["n"] == REDACTED
|
||||
assert identity["resources"]["/oic/d"]["rt"] == ["oic.wk.d", "oic.d.refrigerator"]
|
||||
|
||||
|
||||
async def test_diagnostics_include_oic_res_links(
|
||||
@@ -94,32 +98,38 @@ async def test_diagnostics_include_oic_res_links(
|
||||
|
||||
coordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
coordinator._identity = DeviceIdentity(
|
||||
manufacturer='Samsung Electronics',
|
||||
model='RF9000B',
|
||||
name='Family Hub',
|
||||
manufacturer="Samsung Electronics",
|
||||
model="RF9000B",
|
||||
name="Family Hub",
|
||||
serial=None,
|
||||
device_types=('oic.wk.d', 'oic.d.refrigerator'),
|
||||
device_types=("oic.wk.d", "oic.d.refrigerator"),
|
||||
raw={
|
||||
'/oic/p': {'mnmn': 'Samsung Electronics'},
|
||||
'/oic/d': {'rt': ['oic.wk.d', 'oic.d.refrigerator']},
|
||||
'/oic/res': [
|
||||
{'di': 'aaaa-1111', 'href': '/device/0',
|
||||
'rt': ['x.com.samsung.devcol', 'oic.wk.col']},
|
||||
{'di': 'bbbb-2222', 'href': '/device/1',
|
||||
'rt': ['x.com.samsung.devcol', 'oic.wk.col']},
|
||||
"/oic/p": {"mnmn": "Samsung Electronics"},
|
||||
"/oic/d": {"rt": ["oic.wk.d", "oic.d.refrigerator"]},
|
||||
"/oic/res": [
|
||||
{
|
||||
"di": "aaaa-1111",
|
||||
"href": "/device/0",
|
||||
"rt": ["x.com.samsung.devcol", "oic.wk.col"],
|
||||
},
|
||||
{
|
||||
"di": "bbbb-2222",
|
||||
"href": "/device/1",
|
||||
"rt": ["x.com.samsung.devcol", "oic.wk.col"],
|
||||
},
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, mock_entry)
|
||||
|
||||
links = diag['identity']['resources']['/oic/res']
|
||||
links = diag["identity"]["resources"]["/oic/res"]
|
||||
assert len(links) == 2
|
||||
assert links[0]['di'] == REDACTED
|
||||
assert links[0]['href'] == '/device/0'
|
||||
assert links[1]['di'] == REDACTED
|
||||
assert links[1]['href'] == '/device/1'
|
||||
assert links[1]['rt'] == ['x.com.samsung.devcol', 'oic.wk.col']
|
||||
assert links[0]["di"] == REDACTED
|
||||
assert links[0]["href"] == "/device/0"
|
||||
assert links[1]["di"] == REDACTED
|
||||
assert links[1]["href"] == "/device/1"
|
||||
assert links[1]["rt"] == ["x.com.samsung.devcol", "oic.wk.col"]
|
||||
|
||||
|
||||
async def test_diagnostics_include_speculative_device_probes(
|
||||
@@ -135,27 +145,29 @@ async def test_diagnostics_include_speculative_device_probes(
|
||||
|
||||
coordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
coordinator._identity = DeviceIdentity(
|
||||
manufacturer='Samsung Electronics',
|
||||
model='RF9000B',
|
||||
name='Family Hub',
|
||||
manufacturer="Samsung Electronics",
|
||||
model="RF9000B",
|
||||
name="Family Hub",
|
||||
serial=None,
|
||||
device_types=('oic.wk.d', 'oic.d.refrigerator'),
|
||||
device_types=("oic.wk.d", "oic.d.refrigerator"),
|
||||
raw={
|
||||
'/oic/p': {}, '/oic/d': {}, '/oic/res': [],
|
||||
'/device/1': {
|
||||
'/information/vs/0': {'x.com.samsung.da.serialNum': 'SECRET123'},
|
||||
'/power/vs/0': {'x.com.samsung.da.power': 'On'},
|
||||
"/oic/p": {},
|
||||
"/oic/d": {},
|
||||
"/oic/res": [],
|
||||
"/device/1": {
|
||||
"/information/vs/0": {"x.com.samsung.da.serialNum": "SECRET123"},
|
||||
"/power/vs/0": {"x.com.samsung.da.power": "On"},
|
||||
},
|
||||
'/device/2': {},
|
||||
"/device/2": {},
|
||||
},
|
||||
)
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, mock_entry)
|
||||
|
||||
device1 = diag['identity']['resources']['/device/1']
|
||||
assert device1['/information/vs/0']['x.com.samsung.da.serialNum'] == REDACTED
|
||||
assert device1['/power/vs/0']['x.com.samsung.da.power'] == 'On'
|
||||
assert diag['identity']['resources']['/device/2'] == {}
|
||||
device1 = diag["identity"]["resources"]["/device/1"]
|
||||
assert device1["/information/vs/0"]["x.com.samsung.da.serialNum"] == REDACTED
|
||||
assert device1["/power/vs/0"]["x.com.samsung.da.power"] == "On"
|
||||
assert diag["identity"]["resources"]["/device/2"] == {}
|
||||
|
||||
|
||||
async def test_diagnostics_identity_none_when_unavailable(
|
||||
@@ -168,7 +180,7 @@ async def test_diagnostics_identity_none_when_unavailable(
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, mock_entry)
|
||||
|
||||
assert diag['identity'] is None
|
||||
assert diag["identity"] is None
|
||||
|
||||
|
||||
async def test_diagnostics_include_observe_mode_fields(
|
||||
@@ -179,11 +191,11 @@ async def test_diagnostics_include_observe_mode_fields(
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, mock_entry)
|
||||
|
||||
assert diag['observe_mode'] == 'poll'
|
||||
assert diag['observe_subscribed_hrefs'] == []
|
||||
assert diag['observe_fallback_hrefs'] == []
|
||||
assert 'observe_last_mode_change' in diag
|
||||
assert diag['observe_href_freshness_s'] == {}
|
||||
assert diag["observe_mode"] == "poll"
|
||||
assert diag["observe_subscribed_hrefs"] == []
|
||||
assert diag["observe_fallback_hrefs"] == []
|
||||
assert "observe_last_mode_change" in diag
|
||||
assert diag["observe_href_freshness_s"] == {}
|
||||
|
||||
|
||||
async def test_dependency_version_read_off_the_event_loop(
|
||||
@@ -199,12 +211,12 @@ async def test_dependency_version_read_off_the_event_loop(
|
||||
real_pkg_version = diagnostics_mod.pkg_version
|
||||
|
||||
def _spy(name: str) -> str:
|
||||
seen['thread_id'] = threading.get_ident()
|
||||
seen["thread_id"] = threading.get_ident()
|
||||
return real_pkg_version(name)
|
||||
|
||||
monkeypatch.setattr(diagnostics_mod, 'pkg_version', _spy)
|
||||
monkeypatch.setattr(diagnostics_mod, "pkg_version", _spy)
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, mock_entry)
|
||||
|
||||
assert diag['smartthings_local_version']
|
||||
assert seen['thread_id'] != loop_thread_id
|
||||
assert diag["smartthings_local_version"]
|
||||
assert seen["thread_id"] != loop_thread_id
|
||||
@@ -1,16 +1,17 @@
|
||||
"""Tests for ObserveManager: write-settle guard and mode defaults."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
import cbor2
|
||||
import pytest
|
||||
|
||||
from smartthings_local.ocf.state_cache import StateCache
|
||||
|
||||
from custom_components.localthings.observe import (
|
||||
ObserveManager, MODE_POLL, _rep_diff,
|
||||
MODE_POLL,
|
||||
ObserveManager,
|
||||
_rep_diff,
|
||||
)
|
||||
|
||||
|
||||
@@ -30,8 +31,8 @@ def test_starts_in_poll_mode():
|
||||
|
||||
def test_apply_writes_through_when_not_settling():
|
||||
mgr = _manager()
|
||||
assert mgr.apply('/oven/vs/0', {'a': 1}, source='poll') is True
|
||||
assert mgr.cache.get('/oven/vs/0') == {'a': 1}
|
||||
assert mgr.apply("/oven/vs/0", {"a": 1}, source="poll") is True
|
||||
assert mgr.cache.get("/oven/vs/0") == {"a": 1}
|
||||
|
||||
|
||||
def test_apply_merges_partial_update_onto_prior_rep():
|
||||
@@ -43,28 +44,28 @@ def test_apply_merges_partial_update_onto_prior_rep():
|
||||
which is exactly what made the flex-zone select disappear."""
|
||||
mgr = _manager()
|
||||
full = {
|
||||
'x.com.samsung.da.modes': ['CVN_CONVERTIBLE_ZONE', 'CV_FDR_MEAT'],
|
||||
'x.com.samsung.da.supportedOptions': ['CV_FDR_WINE', 'CV_FDR_MEAT'],
|
||||
"x.com.samsung.da.modes": ["CVN_CONVERTIBLE_ZONE", "CV_FDR_MEAT"],
|
||||
"x.com.samsung.da.supportedOptions": ["CV_FDR_WINE", "CV_FDR_MEAT"],
|
||||
}
|
||||
mgr.apply('/mode/vs/0', full, source='poll')
|
||||
mgr.apply("/mode/vs/0", full, source="poll")
|
||||
|
||||
partial = {'x.com.samsung.da.modes': ['CVN_CONVERTIBLE_ZONE', 'WATERFILTER_ENABLE']}
|
||||
mgr.apply('/mode/vs/0', partial, source='observe')
|
||||
partial = {"x.com.samsung.da.modes": ["CVN_CONVERTIBLE_ZONE", "WATERFILTER_ENABLE"]}
|
||||
mgr.apply("/mode/vs/0", partial, source="observe")
|
||||
|
||||
cached = mgr.cache.get('/mode/vs/0')
|
||||
assert cached['x.com.samsung.da.modes'] == ['CVN_CONVERTIBLE_ZONE', 'WATERFILTER_ENABLE']
|
||||
assert cached['x.com.samsung.da.supportedOptions'] == ['CV_FDR_WINE', 'CV_FDR_MEAT']
|
||||
cached = mgr.cache.get("/mode/vs/0")
|
||||
assert cached["x.com.samsung.da.modes"] == ["CVN_CONVERTIBLE_ZONE", "WATERFILTER_ENABLE"]
|
||||
assert cached["x.com.samsung.da.supportedOptions"] == ["CV_FDR_WINE", "CV_FDR_MEAT"]
|
||||
|
||||
|
||||
def test_apply_drops_update_during_settle_window():
|
||||
mgr = _manager()
|
||||
mgr.cache.apply_rep('/oven/vs/0', {'a': 1}, source='seed')
|
||||
mgr.mark_write_pending('/oven/vs/0', settle_s=1.0)
|
||||
mgr.cache.apply_rep("/oven/vs/0", {"a": 1}, source="seed")
|
||||
mgr.mark_write_pending("/oven/vs/0", settle_s=1.0)
|
||||
|
||||
result = mgr.apply('/oven/vs/0', {'a': 2}, source='poll')
|
||||
result = mgr.apply("/oven/vs/0", {"a": 2}, source="poll")
|
||||
|
||||
assert result is False
|
||||
assert mgr.cache.get('/oven/vs/0') == {'a': 1}
|
||||
assert mgr.cache.get("/oven/vs/0") == {"a": 1}
|
||||
|
||||
|
||||
def test_apply_optimistic_bypasses_an_in_progress_settle_window():
|
||||
@@ -77,29 +78,29 @@ def test_apply_optimistic_bypasses_an_in_progress_settle_window():
|
||||
dropped by a guard that exists to protect optimistic writes, not
|
||||
suppress them."""
|
||||
mgr = _manager()
|
||||
mgr.cache.apply_rep('/course/vs/0', {'Course': '1C', 'Detergent': '1'}, source='seed')
|
||||
mgr.mark_write_pending('/course/vs/0', settle_s=30.0)
|
||||
mgr.cache.apply_rep("/course/vs/0", {"Course": "1C", "Detergent": "1"}, source="seed")
|
||||
mgr.mark_write_pending("/course/vs/0", settle_s=30.0)
|
||||
|
||||
result = mgr.apply('/course/vs/0', {'Detergent': '2'}, source='optimistic')
|
||||
result = mgr.apply("/course/vs/0", {"Detergent": "2"}, source="optimistic")
|
||||
|
||||
assert result is True
|
||||
assert mgr.cache.get('/course/vs/0') == {'Course': '1C', 'Detergent': '2'}
|
||||
assert mgr.cache.get("/course/vs/0") == {"Course": "1C", "Detergent": "2"}
|
||||
|
||||
# A poll/sweep/observe update racing in right behind it is still
|
||||
# gated -- the second write's own guard (re-armed by mark_write_pending,
|
||||
# not exercised directly here) is what protects it going forward.
|
||||
assert mgr.apply('/course/vs/0', {'Detergent': '1'}, source='poll') is False
|
||||
assert mgr.apply("/course/vs/0", {"Detergent": "1"}, source="poll") is False
|
||||
|
||||
|
||||
def test_apply_accepts_update_after_settle_window_elapses():
|
||||
mgr = _manager()
|
||||
mgr.mark_write_pending('/oven/vs/0', settle_s=0.05)
|
||||
mgr.mark_write_pending("/oven/vs/0", settle_s=0.05)
|
||||
time.sleep(0.1)
|
||||
|
||||
result = mgr.apply('/oven/vs/0', {'a': 2}, source='poll')
|
||||
result = mgr.apply("/oven/vs/0", {"a": 2}, source="poll")
|
||||
|
||||
assert result is True
|
||||
assert mgr.cache.get('/oven/vs/0') == {'a': 2}
|
||||
assert mgr.cache.get("/oven/vs/0") == {"a": 2}
|
||||
|
||||
|
||||
class _FakeSession:
|
||||
@@ -110,28 +111,29 @@ class _FakeSession:
|
||||
`mgr.on_notification(href, payload)` itself to simulate delivery,
|
||||
since real notify delivery is async/threaded in production.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.subscribed: list[str] = []
|
||||
self.fail_hrefs: set[str] = set()
|
||||
|
||||
def subscribe(self, path_segs):
|
||||
href = '/' + '/'.join(path_segs)
|
||||
href = "/" + "/".join(path_segs)
|
||||
if href in self.fail_hrefs:
|
||||
raise ConnectionError("subscribe failed")
|
||||
self.subscribed.append(href)
|
||||
return b'\x01'
|
||||
return b"\x01"
|
||||
|
||||
|
||||
def test_try_enter_observe_mode_succeeds_when_all_hrefs_notify():
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
hrefs = ['/oven/vs/0', '/power/vs/0']
|
||||
hrefs = ["/oven/vs/0", "/power/vs/0"]
|
||||
|
||||
def _notify_during_grace_period():
|
||||
# Simulate notifications arriving during the grace period
|
||||
time.sleep(0.005) # Let the sleep start, then notify partway through
|
||||
for href in hrefs:
|
||||
mgr.on_notification(href, cbor2.dumps({'x': 1}))
|
||||
mgr.on_notification(href, cbor2.dumps({"x": 1}))
|
||||
|
||||
# Start background thread to deliver notifications during grace period
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
@@ -142,7 +144,7 @@ def test_try_enter_observe_mode_succeeds_when_all_hrefs_notify():
|
||||
notifier.join()
|
||||
|
||||
assert entered is True
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
assert mgr.subscribed_hrefs == set(hrefs)
|
||||
finally:
|
||||
mgr.close()
|
||||
@@ -151,57 +153,60 @@ def test_try_enter_observe_mode_succeeds_when_all_hrefs_notify():
|
||||
def test_try_enter_observe_mode_falls_back_when_no_notifies_arrive():
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
hrefs = ['/oven/vs/0', '/power/vs/0']
|
||||
hrefs = ["/oven/vs/0", "/power/vs/0"]
|
||||
|
||||
entered = mgr.try_enter_observe_mode(session, hrefs, grace_period_s=0.01)
|
||||
|
||||
assert entered is False
|
||||
assert mgr.mode == 'poll'
|
||||
assert mgr.mode == "poll"
|
||||
assert mgr.subscribed_hrefs == set()
|
||||
|
||||
|
||||
def test_try_enter_observe_mode_falls_back_when_subscribe_fails_for_all():
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
session.fail_hrefs = {'/oven/vs/0', '/power/vs/0'}
|
||||
hrefs = ['/oven/vs/0', '/power/vs/0']
|
||||
session.fail_hrefs = {"/oven/vs/0", "/power/vs/0"}
|
||||
hrefs = ["/oven/vs/0", "/power/vs/0"]
|
||||
|
||||
entered = mgr.try_enter_observe_mode(session, hrefs, grace_period_s=0.01)
|
||||
|
||||
assert entered is False
|
||||
assert mgr.mode == 'poll'
|
||||
assert mgr.mode == "poll"
|
||||
|
||||
|
||||
def test_try_enter_observe_mode_meets_success_fraction_with_partial_notifies():
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
hrefs = ['/a/vs/0', '/b/vs/0', '/c/vs/0', '/d/vs/0']
|
||||
hrefs = ["/a/vs/0", "/b/vs/0", "/c/vs/0", "/d/vs/0"]
|
||||
|
||||
def _notify_partial():
|
||||
# Simulate partial notifications arriving during grace period
|
||||
time.sleep(0.005)
|
||||
for href in hrefs[:3]: # 3/4 = 0.75
|
||||
mgr.on_notification(href, cbor2.dumps({'x': 1}))
|
||||
mgr.on_notification(href, cbor2.dumps({"x": 1}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_partial, daemon=True)
|
||||
notifier.start()
|
||||
|
||||
try:
|
||||
entered = mgr.try_enter_observe_mode(
|
||||
session, hrefs, grace_period_s=0.02, success_fraction=0.7,
|
||||
session,
|
||||
hrefs,
|
||||
grace_period_s=0.02,
|
||||
success_fraction=0.7,
|
||||
)
|
||||
notifier.join()
|
||||
|
||||
assert entered is True
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
finally:
|
||||
mgr.close()
|
||||
|
||||
|
||||
def test_on_notification_ignores_malformed_cbor():
|
||||
mgr = _manager()
|
||||
mgr.on_notification('/oven/vs/0', b'\xff\xff\xff not cbor')
|
||||
assert mgr.cache.get('/oven/vs/0') is None
|
||||
mgr.on_notification("/oven/vs/0", b"\xff\xff\xff not cbor")
|
||||
assert mgr.cache.get("/oven/vs/0") is None
|
||||
|
||||
|
||||
def test_recently_notified_false_before_any_notify():
|
||||
@@ -211,13 +216,13 @@ def test_recently_notified_false_before_any_notify():
|
||||
|
||||
def test_recently_notified_true_just_after_a_notify():
|
||||
mgr = _manager()
|
||||
mgr.on_notification('/oven/vs/0', cbor2.dumps({'a': 1}))
|
||||
mgr.on_notification("/oven/vs/0", cbor2.dumps({"a": 1}))
|
||||
assert mgr.recently_notified() is True
|
||||
|
||||
|
||||
def test_recently_notified_false_after_window_elapses():
|
||||
mgr = _manager()
|
||||
mgr.on_notification('/oven/vs/0', cbor2.dumps({'a': 1}))
|
||||
mgr.on_notification("/oven/vs/0", cbor2.dumps({"a": 1}))
|
||||
assert mgr.recently_notified(window_s=0.01) is True
|
||||
time.sleep(0.02)
|
||||
assert mgr.recently_notified(window_s=0.01) is False
|
||||
@@ -229,21 +234,21 @@ def test_try_enter_observe_mode_clears_stale_notifications_on_retry():
|
||||
usage when poll-only mode periodically retries entering observe mode."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
hrefs = ['/a/vs/0', '/b/vs/0']
|
||||
hrefs = ["/a/vs/0", "/b/vs/0"]
|
||||
|
||||
try:
|
||||
# First call: all hrefs notify -> succeeds and enters observe mode
|
||||
def _notify_all_first():
|
||||
time.sleep(0.005)
|
||||
for href in hrefs:
|
||||
mgr.on_notification(href, cbor2.dumps({'x': 1}))
|
||||
mgr.on_notification(href, cbor2.dumps({"x": 1}))
|
||||
|
||||
notifier1 = threading.Thread(target=_notify_all_first, daemon=True)
|
||||
notifier1.start()
|
||||
entered = mgr.try_enter_observe_mode(session, hrefs, grace_period_s=0.02)
|
||||
notifier1.join()
|
||||
assert entered is True
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
|
||||
# Second call: retry with same hrefs, but only one notifies.
|
||||
# Without the fix (missing self._notified.clear()), the old notifications
|
||||
@@ -253,7 +258,7 @@ def test_try_enter_observe_mode_clears_stale_notifications_on_retry():
|
||||
|
||||
def _notify_partial_second():
|
||||
time.sleep(0.005)
|
||||
mgr.on_notification(hrefs[0], cbor2.dumps({'x': 2})) # only one notifies
|
||||
mgr.on_notification(hrefs[0], cbor2.dumps({"x": 2})) # only one notifies
|
||||
|
||||
notifier2 = threading.Thread(target=_notify_partial_second, daemon=True)
|
||||
notifier2.start()
|
||||
@@ -261,7 +266,7 @@ def test_try_enter_observe_mode_clears_stale_notifications_on_retry():
|
||||
notifier2.join()
|
||||
|
||||
assert entered is False
|
||||
assert mgr.mode == 'poll'
|
||||
assert mgr.mode == "poll"
|
||||
assert mgr.subscribed_hrefs == set()
|
||||
finally:
|
||||
mgr.close()
|
||||
@@ -269,9 +274,9 @@ def test_try_enter_observe_mode_clears_stale_notifications_on_retry():
|
||||
|
||||
def test_log_sweep_discrepancies_noop_when_not_in_observe_mode(caplog):
|
||||
mgr = _manager()
|
||||
with caplog.at_level('DEBUG'):
|
||||
mgr.log_sweep_discrepancies({'/oven/vs/0': {'a': 2}})
|
||||
assert 'observe missed a change' not in caplog.text
|
||||
with caplog.at_level("DEBUG"):
|
||||
mgr.log_sweep_discrepancies({"/oven/vs/0": {"a": 2}})
|
||||
assert "observe missed a change" not in caplog.text
|
||||
|
||||
|
||||
def test_log_sweep_discrepancies_never_changes_mode():
|
||||
@@ -282,12 +287,12 @@ def test_log_sweep_discrepancies_never_changes_mode():
|
||||
away working push coverage on every other subscribed href."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
hrefs = ['/oven/vs/0', '/power/vs/0']
|
||||
hrefs = ["/oven/vs/0", "/power/vs/0"]
|
||||
|
||||
def _notify_during_grace_period():
|
||||
time.sleep(0.005)
|
||||
for href in hrefs:
|
||||
mgr.on_notification(href, cbor2.dumps({'a': 1}))
|
||||
mgr.on_notification(href, cbor2.dumps({"a": 1}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
@@ -295,12 +300,12 @@ def test_log_sweep_discrepancies_never_changes_mode():
|
||||
try:
|
||||
mgr.try_enter_observe_mode(session, hrefs, grace_period_s=0.02)
|
||||
notifier.join()
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
|
||||
# Sweep sees values the cache never got via notify on BOTH hrefs.
|
||||
mgr.log_sweep_discrepancies({hrefs[0]: {'a': 2}, hrefs[1]: {'a': 2}})
|
||||
mgr.log_sweep_discrepancies({hrefs[0]: {"a": 2}, hrefs[1]: {"a": 2}})
|
||||
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
finally:
|
||||
mgr.close()
|
||||
|
||||
@@ -310,9 +315,9 @@ def test_rep_diff_reports_only_shared_fields_that_differ():
|
||||
sweep vs. individual GET/notify returning different fields for the
|
||||
same href) must not be reported — only shared fields with different
|
||||
values."""
|
||||
diff = _rep_diff({'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 5, 'd': 9})
|
||||
diff = _rep_diff({"a": 1, "b": 2, "c": 3}, {"a": 1, "b": 5, "d": 9})
|
||||
|
||||
assert diff == {'b': (2, 5)}
|
||||
assert diff == {"b": (2, 5)}
|
||||
|
||||
|
||||
def test_log_sweep_discrepancies_ignores_shape_only_differences(caplog):
|
||||
@@ -321,11 +326,11 @@ def test_log_sweep_discrepancies_ignores_shape_only_differences(caplog):
|
||||
must not be logged as a discrepancy."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
href = '/oven/vs/0'
|
||||
href = "/oven/vs/0"
|
||||
|
||||
def _notify_during_grace_period():
|
||||
time.sleep(0.005)
|
||||
mgr.on_notification(href, cbor2.dumps({'a': 1, 'rt': ['x'], 'if': ['y']}))
|
||||
mgr.on_notification(href, cbor2.dumps({"a": 1, "rt": ["x"], "if": ["y"]}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
@@ -333,16 +338,16 @@ def test_log_sweep_discrepancies_ignores_shape_only_differences(caplog):
|
||||
try:
|
||||
mgr.try_enter_observe_mode(session, [href], grace_period_s=0.02)
|
||||
notifier.join()
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
|
||||
# Sweep rep has the same 'a' value but lacks rt/if and adds 'href' —
|
||||
# a shape difference (batch interface), not a missed content change.
|
||||
with caplog.at_level('DEBUG'):
|
||||
mgr.log_sweep_discrepancies({href: {'a': 1, 'href': href}})
|
||||
with caplog.at_level("DEBUG"):
|
||||
mgr.log_sweep_discrepancies({href: {"a": 1, "href": href}})
|
||||
finally:
|
||||
mgr.close()
|
||||
|
||||
assert 'observe missed a change' not in caplog.text
|
||||
assert "observe missed a change" not in caplog.text
|
||||
|
||||
|
||||
def test_log_sweep_discrepancies_includes_the_diff(caplog):
|
||||
@@ -350,12 +355,12 @@ def test_log_sweep_discrepancies_includes_the_diff(caplog):
|
||||
did."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
hrefs = ['/oven/vs/0', '/power/vs/0']
|
||||
hrefs = ["/oven/vs/0", "/power/vs/0"]
|
||||
|
||||
def _notify_during_grace_period():
|
||||
time.sleep(0.005)
|
||||
for href in hrefs:
|
||||
mgr.on_notification(href, cbor2.dumps({'a': 1, 'b': 2}))
|
||||
mgr.on_notification(href, cbor2.dumps({"a": 1, "b": 2}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
@@ -363,15 +368,13 @@ def test_log_sweep_discrepancies_includes_the_diff(caplog):
|
||||
try:
|
||||
mgr.try_enter_observe_mode(session, hrefs, grace_period_s=0.02)
|
||||
notifier.join()
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
|
||||
with caplog.at_level('DEBUG'):
|
||||
mgr.log_sweep_discrepancies(
|
||||
{hrefs[0]: {'a': 1, 'b': 5}, hrefs[1]: {'a': 1, 'b': 9}}
|
||||
)
|
||||
with caplog.at_level("DEBUG"):
|
||||
mgr.log_sweep_discrepancies({hrefs[0]: {"a": 1, "b": 5}, hrefs[1]: {"a": 1, "b": 9}})
|
||||
|
||||
assert "{'b': (2, 5)}" in caplog.text
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
finally:
|
||||
mgr.close()
|
||||
|
||||
@@ -379,25 +382,25 @@ def test_log_sweep_discrepancies_includes_the_diff(caplog):
|
||||
def test_log_sweep_discrepancies_ignores_href_during_settle_window(caplog):
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
href = '/oven/vs/0'
|
||||
mgr.on_notification(href, cbor2.dumps({'a': 1}))
|
||||
href = "/oven/vs/0"
|
||||
mgr.on_notification(href, cbor2.dumps({"a": 1}))
|
||||
mgr.try_enter_observe_mode(session, [href], grace_period_s=0.01)
|
||||
mgr.mark_write_pending(href, settle_s=5.0)
|
||||
|
||||
with caplog.at_level('DEBUG'):
|
||||
mgr.log_sweep_discrepancies({href: {'a': 2}})
|
||||
with caplog.at_level("DEBUG"):
|
||||
mgr.log_sweep_discrepancies({href: {"a": 2}})
|
||||
|
||||
assert 'observe missed a change' not in caplog.text
|
||||
assert "observe missed a change" not in caplog.text
|
||||
|
||||
|
||||
def test_downgrade_to_poll_moves_subscribed_to_fallback():
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
href = '/oven/vs/0'
|
||||
href = "/oven/vs/0"
|
||||
|
||||
def _notify_during_grace_period():
|
||||
time.sleep(0.005)
|
||||
mgr.on_notification(href, cbor2.dumps({'a': 1}))
|
||||
mgr.on_notification(href, cbor2.dumps({"a": 1}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
@@ -407,14 +410,14 @@ def test_downgrade_to_poll_moves_subscribed_to_fallback():
|
||||
|
||||
mgr.downgrade_to_poll()
|
||||
|
||||
assert mgr.mode == 'poll'
|
||||
assert mgr.mode == "poll"
|
||||
assert mgr.subscribed_hrefs == set()
|
||||
assert mgr.fallback_hrefs == {href}
|
||||
|
||||
|
||||
def test_start_refresh_task_spawns_a_daemon_thread():
|
||||
mgr = _manager()
|
||||
mgr.subscribed_hrefs = {'/oven/vs/0'}
|
||||
mgr.subscribed_hrefs = {"/oven/vs/0"}
|
||||
session = _FakeSession()
|
||||
|
||||
mgr.start_refresh_task(session)
|
||||
@@ -428,7 +431,7 @@ def test_start_refresh_task_spawns_a_daemon_thread():
|
||||
|
||||
def test_close_stops_the_refresh_thread():
|
||||
mgr = _manager()
|
||||
mgr.subscribed_hrefs = {'/oven/vs/0'}
|
||||
mgr.subscribed_hrefs = {"/oven/vs/0"}
|
||||
session = _FakeSession()
|
||||
mgr.start_refresh_task(session)
|
||||
thread = mgr._refresh_thread
|
||||
@@ -442,7 +445,7 @@ def test_close_stops_the_refresh_thread():
|
||||
|
||||
def test_downgrade_to_poll_stops_refresh_task():
|
||||
mgr = _manager()
|
||||
mgr.subscribed_hrefs = {'/oven/vs/0'}
|
||||
mgr.subscribed_hrefs = {"/oven/vs/0"}
|
||||
session = _FakeSession()
|
||||
mgr.start_refresh_task(session)
|
||||
thread = mgr._refresh_thread
|
||||
@@ -462,14 +465,14 @@ def test_try_enter_observe_mode_exits_early_when_fraction_reached():
|
||||
first-refresh / observe-retry fetch paid that dead time."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
hrefs = ['/a/vs/0', '/b/vs/0']
|
||||
hrefs = ["/a/vs/0", "/b/vs/0"]
|
||||
|
||||
def _notify_after_subscribe():
|
||||
# Let try_enter clear _notified + subscribe first (matches the existing
|
||||
# test pattern's 0.005 lead), then notify well before the 2s ceiling.
|
||||
time.sleep(0.01)
|
||||
for href in hrefs:
|
||||
mgr.on_notification(href, cbor2.dumps({'x': 1}))
|
||||
mgr.on_notification(href, cbor2.dumps({"x": 1}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_after_subscribe, daemon=True)
|
||||
notifier.start()
|
||||
@@ -481,7 +484,7 @@ def test_try_enter_observe_mode_exits_early_when_fraction_reached():
|
||||
notifier.join()
|
||||
|
||||
assert entered is True
|
||||
assert mgr.mode == 'observe'
|
||||
assert mgr.mode == "observe"
|
||||
# Early exit: returns near the notify (~0.01s), not the 2.0s ceiling.
|
||||
# The old fixed sleep would make this >= 2.0.
|
||||
assert elapsed < 0.5
|
||||
@@ -496,11 +499,11 @@ def test_try_enter_observe_mode_waits_full_ceiling_when_fraction_not_reached():
|
||||
against an over-eager predicate that enters observe on too few notifies."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
hrefs = ['/a/vs/0', '/b/vs/0', '/c/vs/0', '/d/vs/0'] # 4 hrefs
|
||||
hrefs = ["/a/vs/0", "/b/vs/0", "/c/vs/0", "/d/vs/0"] # 4 hrefs
|
||||
|
||||
def _notify_one():
|
||||
time.sleep(0.01)
|
||||
mgr.on_notification(hrefs[0], cbor2.dumps({'x': 1})) # 1/4 = 0.25
|
||||
mgr.on_notification(hrefs[0], cbor2.dumps({"x": 1})) # 1/4 = 0.25
|
||||
|
||||
notifier = threading.Thread(target=_notify_one, daemon=True)
|
||||
notifier.start()
|
||||
@@ -508,13 +511,16 @@ def test_try_enter_observe_mode_waits_full_ceiling_when_fraction_not_reached():
|
||||
try:
|
||||
t0 = time.monotonic()
|
||||
entered = mgr.try_enter_observe_mode(
|
||||
session, hrefs, grace_period_s=0.2, success_fraction=0.8,
|
||||
session,
|
||||
hrefs,
|
||||
grace_period_s=0.2,
|
||||
success_fraction=0.8,
|
||||
)
|
||||
elapsed = time.monotonic() - t0
|
||||
notifier.join()
|
||||
|
||||
assert entered is False
|
||||
assert mgr.mode == 'poll'
|
||||
assert mgr.mode == "poll"
|
||||
assert mgr.subscribed_hrefs == set()
|
||||
# Waited the full 0.2s ceiling (1/4 = 0.25 < 0.8); did not early-exit.
|
||||
assert elapsed >= 0.18
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Tests for the sensor platform."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
@@ -18,7 +18,7 @@ async def test_sensors_registered(
|
||||
|
||||
ent_reg = er.async_get(hass)
|
||||
entries = er.async_entries_for_config_entry(ent_reg, mock_entry.entry_id)
|
||||
sensor_entries = [e for e in entries if e.domain == 'sensor']
|
||||
sensor_entries = [e for e in entries if e.domain == "sensor"]
|
||||
assert sensor_entries, "Expected at least one sensor entity"
|
||||
|
||||
|
||||
@@ -34,18 +34,11 @@ async def test_sensor_state_from_coordinator(
|
||||
await hass.config_entries.async_setup(mock_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
states = hass.states.async_all('sensor')
|
||||
temp_states = [
|
||||
s for s in states
|
||||
if s.attributes.get('icon') == 'mdi:thermometer'
|
||||
]
|
||||
assert temp_states, (
|
||||
f"No thermometer sensor found. Sensors: {[s.entity_id for s in states]}"
|
||||
)
|
||||
states = hass.states.async_all("sensor")
|
||||
temp_states = [s for s in states if s.attributes.get("icon") == "mdi:thermometer"]
|
||||
assert temp_states, f"No thermometer sensor found. Sensors: {[s.entity_id for s in states]}"
|
||||
state = temp_states[0]
|
||||
assert state.state not in ('unknown', 'unavailable'), (
|
||||
f"Sensor state is {state.state}"
|
||||
)
|
||||
assert state.state not in ("unknown", "unavailable"), f"Sensor state is {state.state}"
|
||||
|
||||
|
||||
async def test_connection_mode_sensor_registered_disabled_by_default(
|
||||
@@ -58,11 +51,11 @@ async def test_connection_mode_sensor_registered_disabled_by_default(
|
||||
|
||||
ent_reg = er.async_get(hass)
|
||||
entries = er.async_entries_for_config_entry(ent_reg, mock_entry.entry_id)
|
||||
mode_entries = [e for e in entries if e.unique_id.endswith('_connection_mode')]
|
||||
mode_entries = [e for e in entries if e.unique_id.endswith("_connection_mode")]
|
||||
assert len(mode_entries) == 1
|
||||
entry = mode_entries[0]
|
||||
assert entry.disabled_by is not None
|
||||
assert entry.entity_category == 'diagnostic'
|
||||
assert entry.entity_category == "diagnostic"
|
||||
|
||||
|
||||
async def test_connection_mode_sensor_reflects_coordinator_mode(
|
||||
@@ -78,5 +71,5 @@ async def test_connection_mode_sensor_reflects_coordinator_mode(
|
||||
sensor = LocalThingsConnectionModeSensor(coordinator)
|
||||
assert sensor.native_value == MODE_POLL
|
||||
|
||||
coordinator._observe._set_mode('observe')
|
||||
assert sensor.native_value == 'observe'
|
||||
coordinator._observe._set_mode("observe")
|
||||
assert sensor.native_value == "observe"
|
||||
@@ -1,16 +1,17 @@
|
||||
"""Tests for the AirDresser device type (DA_DF_A51_20_COMMON, issue #162)."""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _air_dresser():
|
||||
resources = _load_device('air_dresser')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("air_dresser")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
|
||||
@@ -22,7 +23,7 @@ def _state():
|
||||
|
||||
def test_resolves_to_air_dresser_registry():
|
||||
reg, _ = _air_dresser()
|
||||
assert reg is not None and reg.name == 'air_dresser'
|
||||
assert reg is not None and reg.name == "air_dresser"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -36,7 +37,7 @@ def test_course_select_present_and_reads_current_selection():
|
||||
"""This was the actual reported gap: /course/vs/0 was previously
|
||||
entirely unbound, so no cycle/mode select existed at all."""
|
||||
state = _state()
|
||||
assert state['cycle'] == '01'
|
||||
assert state["cycle"] == "01"
|
||||
|
||||
|
||||
def test_course_options_derived_from_supported_options_fallback():
|
||||
@@ -44,9 +45,10 @@ def test_course_options_derived_from_supported_options_fallback():
|
||||
come from laundry.cycle_options' supportedOptions decode rather than
|
||||
editCourseList -- confirmed distinct codes, current selection included."""
|
||||
from custom_components.localthings.registry.capabilities.laundry import cycle_options
|
||||
|
||||
_, resources = _air_dresser()
|
||||
codes = cycle_options(resources)
|
||||
assert codes == ['01', '02', '04', '03', '05', '1A', '1B', '1C', '07', '08']
|
||||
assert codes == ["01", "02", "04", "03", "05", "1A", "1B", "1C", "07", "08"]
|
||||
|
||||
|
||||
def test_wrinkle_prevent_present_dry_level_fields_absent():
|
||||
@@ -54,17 +56,27 @@ def test_wrinkle_prevent_present_dry_level_fields_absent():
|
||||
dryerType are dryer-only fields this device never reports, so they
|
||||
should not appear as always-empty entities."""
|
||||
state = _state()
|
||||
assert state['wrinkle_prevent'] is False
|
||||
for key in ('dry_level', 'dry_time', 'dryer_type'):
|
||||
assert state["wrinkle_prevent"] is False
|
||||
for key in ("dry_level", "dry_time", "dryer_type"):
|
||||
assert key not in state, key
|
||||
|
||||
|
||||
def test_expected_entities_present():
|
||||
state = _state()
|
||||
for key in (
|
||||
'power_switch', 'child_lock', 'remote_control', 'cycle',
|
||||
'machine_state', 'progress', 'progress_percentage', 'finish_time',
|
||||
'completion_minutes', 'delay_start_hours', 'diagnosis_status',
|
||||
'job_beginning_status', 'wrinkle_prevent', 'energy_kwh',
|
||||
"power_switch",
|
||||
"child_lock",
|
||||
"remote_control",
|
||||
"cycle",
|
||||
"machine_state",
|
||||
"progress",
|
||||
"progress_percentage",
|
||||
"finish_time",
|
||||
"completion_minutes",
|
||||
"delay_start_hours",
|
||||
"diagnosis_status",
|
||||
"job_beginning_status",
|
||||
"wrinkle_prevent",
|
||||
"energy_kwh",
|
||||
):
|
||||
assert key in state, key
|
||||
@@ -9,18 +9,19 @@ labelling problem, not a coverage one; this board's course table isn't
|
||||
identified yet either (same as #162's), so 'cycle' still renders as the
|
||||
raw code until a reporter can map codes to names in the SmartThings app.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import air_dresser, for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _air_dresser():
|
||||
resources = _load_device('air_dresser_tp1_21')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("air_dresser_tp1_21")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
|
||||
@@ -32,7 +33,7 @@ def _state():
|
||||
|
||||
def test_resolves_to_air_dresser_registry():
|
||||
reg, _ = _air_dresser()
|
||||
assert reg is not None and reg.name == 'air_dresser'
|
||||
assert reg is not None and reg.name == "air_dresser"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -46,34 +47,36 @@ def test_buzzer_sound_present_and_writable():
|
||||
"""Issue #208's actual coverage gap: /buzzersound/vs/0 was unbound on
|
||||
this board before laundry.BUZZER_SOUND was added to the registry."""
|
||||
state = _state()
|
||||
assert state['buzzer_sound'] == 'On'
|
||||
assert 'finish_sound' not in state # supportedFinishSound absent -- self-gated off
|
||||
assert state["buzzer_sound"] == "On"
|
||||
assert "finish_sound" not in state # supportedFinishSound absent -- self-gated off
|
||||
|
||||
desc = next(
|
||||
e for e in air_dresser.REGISTRY.capabilities['/buzzersound/vs/0'][0].entities
|
||||
if e.key == 'buzzer_sound'
|
||||
e
|
||||
for e in air_dresser.REGISTRY.capabilities["/buzzersound/vs/0"][0].entities
|
||||
if e.key == "buzzer_sound"
|
||||
)
|
||||
path, body = desc.write_fn('Off', {})
|
||||
assert path == ['buzzersound', 'vs', '0']
|
||||
assert body == {'setBuzzerSound': 'Off'}
|
||||
path, body = desc.write_fn("Off", {})
|
||||
assert path == ["buzzersound", "vs", "0"]
|
||||
assert body == {"setBuzzerSound": "Off"}
|
||||
|
||||
|
||||
def test_course_translation_key_falls_back_to_cycle_for_unidentified_table():
|
||||
"""Same as issue #162's board: Table_00's course codes aren't
|
||||
identified yet, so the select renders raw codes rather than names."""
|
||||
_, resources = _air_dresser()
|
||||
desc = air_dresser.REGISTRY.capabilities['/course/vs/0'][0].entities[0]
|
||||
assert desc.translation_key(resources) == 'cycle'
|
||||
desc = air_dresser.REGISTRY.capabilities["/course/vs/0"][0].entities[0]
|
||||
assert desc.translation_key(resources) == "cycle"
|
||||
|
||||
|
||||
def test_sanitize_present_and_toggles():
|
||||
state = _state()
|
||||
assert state['sanitize'] is False
|
||||
assert state["sanitize"] is False
|
||||
|
||||
desc = next(
|
||||
e for e in air_dresser.REGISTRY.capabilities['/airdresseroption/sanitize/vs/0'][0].entities
|
||||
if e.key == 'sanitize'
|
||||
e
|
||||
for e in air_dresser.REGISTRY.capabilities["/airdresseroption/sanitize/vs/0"][0].entities
|
||||
if e.key == "sanitize"
|
||||
)
|
||||
path, body = desc.write_fn('On', {})
|
||||
assert path == ['airdresseroption', 'sanitize', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.sanitize': 'On'}
|
||||
path, body = desc.write_fn("On", {})
|
||||
assert path == ["airdresseroption", "sanitize", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.sanitize": "On"}
|
||||
@@ -7,18 +7,19 @@ Exercises the two things this board does differently: a populated
|
||||
fallback #162 relies on) and the new /airdresseroption/sanitize/vs/0
|
||||
capability #162's dump doesn't report at all.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import air_dresser, for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _air_dresser():
|
||||
resources = _load_device('air_dresser_tp2_20')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("air_dresser_tp2_20")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
|
||||
@@ -30,7 +31,7 @@ def _state():
|
||||
|
||||
def test_resolves_to_air_dresser_registry():
|
||||
reg, _ = _air_dresser()
|
||||
assert reg is not None and reg.name == 'air_dresser'
|
||||
assert reg is not None and reg.name == "air_dresser"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -48,15 +49,16 @@ def test_course_options_come_from_edit_course_list_not_the_fallback():
|
||||
directly, so cycle_options() should never reach the
|
||||
supportedOptions-decode fallback."""
|
||||
from custom_components.localthings.registry.capabilities.laundry import cycle_options
|
||||
|
||||
_, resources = _air_dresser()
|
||||
codes = cycle_options(resources)
|
||||
assert codes[:3] == ['22', '23', '0C']
|
||||
assert codes == cycle_options({'/wm/editcourse/vs/0': resources['/wm/editcourse/vs/0']})
|
||||
assert codes[:3] == ["22", "23", "0C"]
|
||||
assert codes == cycle_options({"/wm/editcourse/vs/0": resources["/wm/editcourse/vs/0"]})
|
||||
|
||||
|
||||
def test_course_select_reads_current_selection():
|
||||
state = _state()
|
||||
assert state['cycle'] == '22'
|
||||
assert state["cycle"] == "22"
|
||||
|
||||
|
||||
def test_course_translation_key_falls_back_to_cycle_for_unidentified_table():
|
||||
@@ -64,19 +66,20 @@ def test_course_translation_key_falls_back_to_cycle_for_unidentified_table():
|
||||
translation_key resolves to the generic 'cycle' catalog entry rather
|
||||
than a table-specific one that doesn't exist."""
|
||||
_, resources = _air_dresser()
|
||||
desc = air_dresser.REGISTRY.capabilities['/course/vs/0'][0].entities[0]
|
||||
assert desc.translation_key(resources) == 'cycle'
|
||||
desc = air_dresser.REGISTRY.capabilities["/course/vs/0"][0].entities[0]
|
||||
assert desc.translation_key(resources) == "cycle"
|
||||
|
||||
|
||||
def test_sanitize_present_and_toggles():
|
||||
state = _state()
|
||||
assert state['sanitize'] is False
|
||||
assert state["sanitize"] is False
|
||||
|
||||
desc = next(
|
||||
e for e in air_dresser.REGISTRY.capabilities['/airdresseroption/sanitize/vs/0'][0].entities
|
||||
if e.key == 'sanitize'
|
||||
e
|
||||
for e in air_dresser.REGISTRY.capabilities["/airdresseroption/sanitize/vs/0"][0].entities
|
||||
if e.key == "sanitize"
|
||||
)
|
||||
path, body = desc.write_fn('On', {})
|
||||
assert path == ['airdresseroption', 'sanitize', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.sanitize': 'On'}
|
||||
assert desc.write_fn('Sparkle', {}) is None
|
||||
path, body = desc.write_fn("On", {})
|
||||
assert path == ["airdresseroption", "sanitize", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.sanitize": "On"}
|
||||
assert desc.write_fn("Sparkle", {}) is None
|
||||
@@ -2,17 +2,17 @@
|
||||
issue #210) -- a standalone, battery-powered air-quality sensor puck. No
|
||||
controllable appliance state at all beyond the do-not-disturb window.
|
||||
"""
|
||||
|
||||
from datetime import time as dt_time
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_oic_type, resolve
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _air_monitor():
|
||||
resources = _load_device('air_monitor')
|
||||
resources = _load_device("air_monitor")
|
||||
reg = resolve(resources)
|
||||
return reg, resources
|
||||
|
||||
@@ -34,15 +34,15 @@ def _desc(key):
|
||||
|
||||
def test_resolves_to_air_monitor_registry():
|
||||
reg, _ = _air_monitor()
|
||||
assert reg is not None and reg.name == 'air_monitor'
|
||||
assert reg is not None and reg.name == "air_monitor"
|
||||
|
||||
|
||||
def test_resolves_via_oic_type_too():
|
||||
"""This board's real dump carries /oic/d's device type
|
||||
('x.com.st.d.airqualitysensor') as well as the 'ASM' modelNum token --
|
||||
both paths must agree."""
|
||||
reg = for_device_by_oic_type(('x.com.st.d.airqualitysensor',))
|
||||
assert reg is not None and reg.name == 'air_monitor'
|
||||
reg = for_device_by_oic_type(("x.com.st.d.airqualitysensor",))
|
||||
assert reg is not None and reg.name == "air_monitor"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -57,12 +57,12 @@ def test_air_quality_sensors_read_from_shared_items_decode():
|
||||
decode air_purifier.AIR_QUALITY already uses -- this board adds CO2,
|
||||
which neither air_purifier nor range_hood report."""
|
||||
state = _state()
|
||||
assert state['dust'] == 31
|
||||
assert state['fine_dust'] == 23
|
||||
assert state['super_fine_dust'] == 18
|
||||
assert state['odor'] == 1
|
||||
assert state['clean_level'] == 2
|
||||
assert state['co2'] == 498
|
||||
assert state["dust"] == 31
|
||||
assert state["fine_dust"] == 23
|
||||
assert state["super_fine_dust"] == 18
|
||||
assert state["odor"] == 1
|
||||
assert state["clean_level"] == 2
|
||||
assert state["co2"] == 498
|
||||
|
||||
|
||||
def test_second_value_slot_is_not_exposed():
|
||||
@@ -72,27 +72,27 @@ def test_second_value_slot_is_not_exposed():
|
||||
nothing' rule, only the raw reading (value[0]) is bound, not a second
|
||||
'dust_level' or similar entity for that code."""
|
||||
state = _state()
|
||||
assert 'dust_level' not in state
|
||||
assert 'dust_grade' not in state
|
||||
assert "dust_level" not in state
|
||||
assert "dust_grade" not in state
|
||||
|
||||
|
||||
def test_humidity_and_battery_present():
|
||||
state = _state()
|
||||
assert state['humidity'] == 57
|
||||
assert state['battery'] == 80
|
||||
assert state['battery_charging'] is False
|
||||
assert state["humidity"] == 57
|
||||
assert state["battery"] == 80
|
||||
assert state["battery_charging"] is False
|
||||
|
||||
|
||||
def test_air_quality_standard_present():
|
||||
state = _state()
|
||||
assert state['air_quality_standard'] == 'AirCleanAssociation'
|
||||
assert state["air_quality_standard"] == "AirCleanAssociation"
|
||||
|
||||
|
||||
def test_dnd_read_contract():
|
||||
state = _state()
|
||||
assert state['dnd'] is False
|
||||
assert state['dnd_start'] == dt_time(14, 0)
|
||||
assert state['dnd_end'] == dt_time(22, 0)
|
||||
assert state["dnd"] is False
|
||||
assert state["dnd_start"] == dt_time(14, 0)
|
||||
assert state["dnd_end"] == dt_time(22, 0)
|
||||
|
||||
|
||||
def test_dnd_write_contracts_are_flagged_educated_guesses():
|
||||
@@ -102,14 +102,14 @@ def test_dnd_write_contracts_are_flagged_educated_guesses():
|
||||
string/time-format shape, not invented from nothing, but still
|
||||
unconfirmed on real hardware. Only the wiring is tested here; whether
|
||||
the device actually accepts these writes needs a reporter to confirm."""
|
||||
dnd = _desc('dnd')
|
||||
path, body = dnd.write_fn('On', {})
|
||||
assert path == ['dnd', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.value': 'true'}
|
||||
path, body = dnd.write_fn('Off', {})
|
||||
assert body == {'x.com.samsung.da.value': 'false'}
|
||||
dnd = _desc("dnd")
|
||||
path, body = dnd.write_fn("On", {})
|
||||
assert path == ["dnd", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.value": "true"}
|
||||
path, body = dnd.write_fn("Off", {})
|
||||
assert body == {"x.com.samsung.da.value": "false"}
|
||||
|
||||
start = _desc('dnd_start')
|
||||
start = _desc("dnd_start")
|
||||
path, body = start.write_fn(dt_time(9, 30), {})
|
||||
assert path == ['dnd', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.startTime': '09:30:00'}
|
||||
assert path == ["dnd", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.startTime": "09:30:00"}
|
||||
@@ -1,5 +1,8 @@
|
||||
"""HA fan-entity mapping tests for the ARTIK051_TVTL air purifier (issue #56)."""
|
||||
|
||||
from typing import ClassVar, cast
|
||||
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
from custom_components.localthings.fan import LocalThingsAirflowFan
|
||||
from custom_components.localthings.registry.by_type import air_purifier
|
||||
from custom_components.localthings.registry.capabilities.air_purifier import HREF_AIRFLOW
|
||||
@@ -9,9 +12,9 @@ from tests.conftest import _load_device
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-AIRFLOW-SERIAL'
|
||||
device_info = {}
|
||||
data = {}
|
||||
device_serial = "TEST-AIRFLOW-SERIAL"
|
||||
device_info: ClassVar[dict] = {}
|
||||
data: ClassVar[dict] = {}
|
||||
|
||||
def __init__(self, resources):
|
||||
self.last_resources = resources
|
||||
@@ -37,16 +40,16 @@ def _entity(resources, coordinator=None):
|
||||
air_purifier.REGISTRY.pattern_capabilities,
|
||||
)
|
||||
fan_bound = next(
|
||||
item for item in bound
|
||||
if isinstance(item.desc, FanDesc) and item.href == HREF_AIRFLOW
|
||||
item for item in bound if isinstance(item.desc, FanDesc) and item.href == HREF_AIRFLOW
|
||||
)
|
||||
return LocalThingsAirflowFan(
|
||||
coordinator or _FakeCoordinator(resources), fan_bound,
|
||||
cast(LocalThingsCoordinator, coordinator or _FakeCoordinator(resources)),
|
||||
fan_bound,
|
||||
)
|
||||
|
||||
|
||||
def test_power_off_maps_to_zero_percent_and_five_retained_speeds():
|
||||
entity = _entity(_load_device('air_purifier'))
|
||||
entity = _entity(_load_device("air_purifier"))
|
||||
assert entity.is_on is False
|
||||
assert entity.speed_count == 5
|
||||
assert entity.percentage == 0
|
||||
@@ -55,11 +58,11 @@ def test_power_off_maps_to_zero_percent_and_five_retained_speeds():
|
||||
def test_active_codes_map_to_ordered_percentages():
|
||||
"""Confirmed via issue #56's second, properly-spaced diagnostics round:
|
||||
/airflow/0's speed is a clean 0-4 code across Auto/Sleep/Low/Medium/High."""
|
||||
resources = _load_device('air_purifier')
|
||||
resources['/power/0']['value'] = True
|
||||
resources = _load_device("air_purifier")
|
||||
resources["/power/0"]["value"] = True
|
||||
|
||||
for code, expected_percentage in ((0, 20), (1, 40), (2, 60), (3, 80), (4, 100)):
|
||||
resources['/airflow/0']['speed'] = code
|
||||
resources["/airflow/0"]["speed"] = code
|
||||
assert _entity(resources).percentage == expected_percentage
|
||||
|
||||
|
||||
@@ -69,43 +72,43 @@ async def test_power_write_prefers_standard_resource_when_both_exist():
|
||||
power_switch entity is unconditionally bound to /power/0 whenever it's
|
||||
present, so writing here to /power/vs/0 first would leave the two
|
||||
entities disagreeing until the next poll)."""
|
||||
resources = _load_device('air_purifier')
|
||||
resources = _load_device("air_purifier")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_turn_on()
|
||||
|
||||
assert coordinator.commands[-1][1] == ('power', True, '/power/0')
|
||||
assert coordinator.commands[-1][1] == ("power", True, "/power/0")
|
||||
|
||||
|
||||
async def test_power_write_falls_back_to_vendor_resource():
|
||||
resources = _load_device('air_purifier')
|
||||
resources.pop('/power/0')
|
||||
resources = _load_device("air_purifier")
|
||||
resources.pop("/power/0")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_turn_off()
|
||||
|
||||
assert coordinator.commands[-1][1] == ('power', False, '/power/vs/0')
|
||||
assert coordinator.commands[-1][1] == ("power", False, "/power/vs/0")
|
||||
|
||||
|
||||
async def test_set_percentage_writes_raw_speed_code():
|
||||
resources = _load_device('air_purifier')
|
||||
resources['/power/0']['value'] = True
|
||||
resources = _load_device("air_purifier")
|
||||
resources["/power/0"]["value"] = True
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_percentage(60)
|
||||
|
||||
assert coordinator.commands[-1][1] == ('speed', 2)
|
||||
assert coordinator.commands[-1][1] == ("speed", 2)
|
||||
|
||||
|
||||
async def test_set_percentage_zero_turns_off():
|
||||
resources = _load_device('air_purifier')
|
||||
resources['/power/0']['value'] = True
|
||||
resources = _load_device("air_purifier")
|
||||
resources["/power/0"]["value"] = True
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_percentage(0)
|
||||
|
||||
assert coordinator.commands[-1][1] == ('power', False, '/power/0')
|
||||
assert coordinator.commands[-1][1] == ("power", False, "/power/0")
|
||||
@@ -8,25 +8,26 @@ diagnostics showed device_type 'unknown' with empty oneUiVersion and every
|
||||
resource unbound -- once routed to the existing air_purifier registry, every
|
||||
resource here binds with zero gaps.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _resources():
|
||||
return _load_device('air_purifier_avt_ww')
|
||||
return _load_device("air_purifier_avt_ww")
|
||||
|
||||
|
||||
def _reg(resources):
|
||||
info = resources['/information/vs/0']
|
||||
info = resources["/information/vs/0"]
|
||||
return for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
|
||||
|
||||
def test_resolves_to_air_purifier_registry():
|
||||
assert _reg(_resources()).name == 'air_purifier'
|
||||
assert _reg(_resources()).name == "air_purifier"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -45,9 +46,9 @@ def test_wind_strength_fan_preset_names():
|
||||
reg = _reg(resources)
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
state = flatten(bound, resources)
|
||||
assert state['wind_strength_fan'] == '87'
|
||||
wind = resources['/wind/strength/vs/0']
|
||||
assert wind['x.com.samsung.da.modesName'] == ['SMART', 'MAX', 'WINDFREE', 'Sleep']
|
||||
assert state["wind_strength_fan"] == "87"
|
||||
wind = resources["/wind/strength/vs/0"]
|
||||
assert wind["x.com.samsung.da.modesName"] == ["SMART", "MAX", "WINDFREE", "Sleep"]
|
||||
|
||||
|
||||
def test_air_quality_and_filter_sensors_present():
|
||||
@@ -55,8 +56,8 @@ def test_air_quality_and_filter_sensors_present():
|
||||
reg = _reg(resources)
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
state = flatten(bound, resources)
|
||||
assert state['dust'] == 10
|
||||
assert state['fine_dust'] == 9
|
||||
assert state['odor'] == 1
|
||||
assert state['hepa_filter_usage'] == 0
|
||||
assert state['hepa_filter_status'] == 'normal'
|
||||
assert state["dust"] == 10
|
||||
assert state["fine_dust"] == 9
|
||||
assert state["odor"] == 1
|
||||
assert state["hepa_filter_usage"] == 0
|
||||
assert state["hepa_filter_status"] == "normal"
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Tests for the ARTIK051_TVTL_18K air-purifier profile (issue #56)."""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.capabilities import air_purifier
|
||||
@@ -7,10 +8,11 @@ from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _purifier():
|
||||
resources = _load_device('air_purifier')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("air_purifier")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -24,7 +26,7 @@ def _state():
|
||||
def test_model_resolves_to_air_purifier_registry():
|
||||
reg, _ = _purifier()
|
||||
assert reg is not None
|
||||
assert reg.name == 'air_purifier'
|
||||
assert reg.name == "air_purifier"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -39,10 +41,20 @@ def test_no_unbound_hrefs():
|
||||
def test_expected_entities_present():
|
||||
state = _state()
|
||||
for key in (
|
||||
'power_switch', 'alarm_code', 'dust', 'fine_dust', 'super_fine_dust',
|
||||
'odor', 'clean_level', 'filter_progress', 'device_active',
|
||||
'diagnosis_status', 'airflow_fan', 'fan_direction',
|
||||
'display_light', 'operating_mode',
|
||||
"power_switch",
|
||||
"alarm_code",
|
||||
"dust",
|
||||
"fine_dust",
|
||||
"super_fine_dust",
|
||||
"odor",
|
||||
"clean_level",
|
||||
"filter_progress",
|
||||
"device_active",
|
||||
"diagnosis_status",
|
||||
"airflow_fan",
|
||||
"fan_direction",
|
||||
"display_light",
|
||||
"operating_mode",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
@@ -51,25 +63,26 @@ def test_air_quality_sensor_values():
|
||||
"""Dust/FineDust/SuperFineDust/Odor/CleanLevel read index 0 of each
|
||||
items[] entry's value list (the raw measurement, per common.sensor_item_value)."""
|
||||
state = _state()
|
||||
assert state['dust'] == 11
|
||||
assert state['fine_dust'] == 9
|
||||
assert state['super_fine_dust'] == 5
|
||||
assert state['odor'] == 0
|
||||
assert state['clean_level'] == 0
|
||||
assert state["dust"] == 11
|
||||
assert state["fine_dust"] == 9
|
||||
assert state["super_fine_dust"] == 5
|
||||
assert state["odor"] == 0
|
||||
assert state["clean_level"] == 0
|
||||
|
||||
|
||||
def test_filter_progress_reads_named_consumable_item():
|
||||
"""FilterProgress is confirmed (issue #56) to count up as the filter
|
||||
wears -- 100 means fully used and needs replacing, not "brand new"."""
|
||||
assert _state()['filter_progress'] == 100
|
||||
assert _state()["filter_progress"] == 100
|
||||
|
||||
|
||||
def test_diagnosis_reuses_dishwasher_capability():
|
||||
"""/diagnosis/vs/0 has the identical field/write contract as
|
||||
dishwasher.DIAGNOSIS, so the by_type registry reuses it directly."""
|
||||
from custom_components.localthings.registry.capabilities import dishwasher
|
||||
|
||||
reg, _ = _purifier()
|
||||
assert dishwasher.DIAGNOSIS in reg.capabilities['/diagnosis/vs/0']
|
||||
assert dishwasher.DIAGNOSIS in reg.capabilities["/diagnosis/vs/0"]
|
||||
|
||||
|
||||
def test_light_switch_write_contract():
|
||||
@@ -77,14 +90,19 @@ def test_light_switch_write_contract():
|
||||
(via laundry.option_write) -- confirmed on real hardware (issue #54)
|
||||
that the device merges by prefix itself, so no read-modify-write of the
|
||||
whole packed /mode/vs/0 options list is needed."""
|
||||
desc = next(e for e in air_purifier.MODE.entities if e.key == 'display_light')
|
||||
rep = {'x.com.samsung.da.options': [
|
||||
'Comode_Off', 'Blooming_0', 'Light_On', 'OptionCode_60282',
|
||||
]}
|
||||
desc = next(e for e in air_purifier.MODE.entities if e.key == "display_light")
|
||||
rep = {
|
||||
"x.com.samsung.da.options": [
|
||||
"Comode_Off",
|
||||
"Blooming_0",
|
||||
"Light_On",
|
||||
"OptionCode_60282",
|
||||
]
|
||||
}
|
||||
assert desc.rep_fn(rep) is True
|
||||
assert desc.write_fn('Off', rep) == (
|
||||
['mode', 'vs', '0'],
|
||||
{'x.com.samsung.da.options': ['Light_Off']},
|
||||
assert desc.write_fn("Off", rep) == (
|
||||
["mode", "vs", "0"],
|
||||
{"x.com.samsung.da.options": ["Light_Off"]},
|
||||
)
|
||||
|
||||
|
||||
@@ -94,25 +112,29 @@ def test_operating_mode_is_a_read_only_diagnostic():
|
||||
regardless of the device's actual fan setting, ruling out the original
|
||||
guess that it was the fan-speed selector; its real purpose is still
|
||||
unconfirmed (see the air_purifier.py module docstring)."""
|
||||
operating_mode = next(e for e in air_purifier.MODE.entities if e.key == 'operating_mode')
|
||||
rep = {'x.com.samsung.da.options': ['Comode_Off']}
|
||||
assert operating_mode.rep_fn(rep) == 'Off'
|
||||
assert not hasattr(operating_mode, 'write_fn')
|
||||
operating_mode = next(e for e in air_purifier.MODE.entities if e.key == "operating_mode")
|
||||
rep = {"x.com.samsung.da.options": ["Comode_Off"]}
|
||||
assert operating_mode.rep_fn(rep) == "Off"
|
||||
assert not hasattr(operating_mode, "write_fn")
|
||||
|
||||
|
||||
def test_blooming_not_modeled():
|
||||
"""Confirmed (issue #56) to have no corresponding SmartThings app
|
||||
setting -- dropped entirely rather than kept as an unexplained
|
||||
diagnostic."""
|
||||
assert not any(e.key == 'blooming_level' for e in air_purifier.MODE.entities)
|
||||
assert not any(e.key == "blooming_level" for e in air_purifier.MODE.entities)
|
||||
|
||||
|
||||
def test_airflow_vs_fallback_only_binds_without_generic():
|
||||
"""/airflow/vs/0 is a match_fn fallback -- it must not bind when the
|
||||
OCF-standard /airflow/0 is also present (both are on every dump seen)."""
|
||||
assert air_purifier.AIRFLOW_VS_FALLBACK.match_fn(
|
||||
{}, {'/airflow/0': {'speed': 0, 'direction': 'Off'}},
|
||||
) is False
|
||||
assert (
|
||||
air_purifier.AIRFLOW_VS_FALLBACK.match_fn(
|
||||
{},
|
||||
{"/airflow/0": {"speed": 0, "direction": "Off"}},
|
||||
)
|
||||
is False
|
||||
)
|
||||
assert air_purifier.AIRFLOW_VS_FALLBACK.match_fn({}, {}) is True
|
||||
|
||||
|
||||
@@ -121,13 +143,15 @@ def test_airflow_fan_write_contract():
|
||||
(two independent units, 60-90s apart per setting): /airflow/0's `speed`
|
||||
is a clean, monotonic 0-4 code, so the write is a plain int passthrough
|
||||
-- no named-preset table needed (see fan.py's LocalThingsAirflowFan)."""
|
||||
fan_desc = next(e for e in air_purifier.AIRFLOW_GENERIC.entities if e.key == 'airflow_fan')
|
||||
assert fan_desc.write_fn(('speed', 3), {}) == (['airflow', '0'], {'speed': 3})
|
||||
assert fan_desc.write_fn(('power', True, '/power/vs/0'), {}) == (
|
||||
['power', 'vs', '0'], {'x.com.samsung.da.power': 'On'},
|
||||
fan_desc = next(e for e in air_purifier.AIRFLOW_GENERIC.entities if e.key == "airflow_fan")
|
||||
assert fan_desc.write_fn(("speed", 3), {}) == (["airflow", "0"], {"speed": 3})
|
||||
assert fan_desc.write_fn(("power", True, "/power/vs/0"), {}) == (
|
||||
["power", "vs", "0"],
|
||||
{"x.com.samsung.da.power": "On"},
|
||||
)
|
||||
assert fan_desc.write_fn(('power', False, '/power/0'), {}) == (
|
||||
['power', '0'], {'value': False},
|
||||
assert fan_desc.write_fn(("power", False, "/power/0"), {}) == (
|
||||
["power", "0"],
|
||||
{"value": False},
|
||||
)
|
||||
|
||||
|
||||
@@ -136,5 +160,5 @@ def test_airflow_speed_reads_from_dump():
|
||||
fan_direction stays a plain diagnostic (every dump seen reads 'Off'
|
||||
regardless of fan setting)."""
|
||||
state = _state()
|
||||
assert state['airflow_fan'] == 0
|
||||
assert state['fan_direction'] == 'Off'
|
||||
assert state["airflow_fan"] == 0
|
||||
assert state["fan_direction"] == "Off"
|
||||
@@ -8,6 +8,7 @@ capability (modes/supportedModes reported directly). Pure function, no
|
||||
coordinator/entity dependency needed to test it directly -- same rationale
|
||||
as test_climate_wind_oscillation_fallback.py's `_oscillation_swing`.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.capabilities.air_purifier import (
|
||||
_has_top_level_modes,
|
||||
)
|
||||
@@ -15,8 +16,8 @@ from custom_components.localthings.registry.capabilities.air_purifier import (
|
||||
|
||||
def test_new_family_with_supported_modes_list_matches():
|
||||
rep = {
|
||||
'x.com.samsung.da.modes': ['Smart'],
|
||||
'x.com.samsung.da.supportedModes': ['Smart', 'Max', 'Mid', 'WindFree', 'Sleep'],
|
||||
"x.com.samsung.da.modes": ["Smart"],
|
||||
"x.com.samsung.da.supportedModes": ["Smart", "Max", "Mid", "WindFree", "Sleep"],
|
||||
}
|
||||
assert _has_top_level_modes(rep, {}) is True
|
||||
|
||||
@@ -26,13 +27,13 @@ def test_old_family_with_no_supported_modes_field_does_not_match():
|
||||
options[] (Light_On, Comode_Off, ...) and has no top-level
|
||||
supportedModes at all."""
|
||||
rep = {
|
||||
'x.com.samsung.da.options': ['Light_On', 'Comode_Off', 'OptionCode_60282'],
|
||||
"x.com.samsung.da.options": ["Light_On", "Comode_Off", "OptionCode_60282"],
|
||||
}
|
||||
assert _has_top_level_modes(rep, {}) is False
|
||||
|
||||
|
||||
def test_non_list_supported_modes_does_not_match():
|
||||
assert _has_top_level_modes({'x.com.samsung.da.supportedModes': 'Smart'}, {}) is False
|
||||
assert _has_top_level_modes({"x.com.samsung.da.supportedModes": "Smart"}, {}) is False
|
||||
|
||||
|
||||
def test_empty_rep_does_not_match():
|
||||
|
||||
@@ -8,19 +8,22 @@ family's /mode/vs/0 (issue #130) where supportedModes IS the name list
|
||||
already. LocalThingsAirPurifierFan._label_for_code resolves both shapes
|
||||
without a per-model map.
|
||||
"""
|
||||
|
||||
from typing import ClassVar, cast
|
||||
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
from custom_components.localthings.fan import LocalThingsAirPurifierFan
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.capabilities.air_purifier import HREF_WIND_STRENGTH
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.entities import FanDesc
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-VTWW-SERIAL'
|
||||
device_info = {}
|
||||
data = {}
|
||||
device_serial = "TEST-VTWW-SERIAL"
|
||||
device_info: ClassVar[dict] = {}
|
||||
data: ClassVar[dict] = {}
|
||||
|
||||
def __init__(self, resources):
|
||||
self.last_resources = resources
|
||||
@@ -40,27 +43,29 @@ class _FakeCoordinator:
|
||||
|
||||
|
||||
def _resources():
|
||||
return _load_device('air_purifier_vtww')
|
||||
return _load_device("air_purifier_vtww")
|
||||
|
||||
|
||||
def _reg(resources):
|
||||
info = resources['/information/vs/0']
|
||||
info = resources["/information/vs/0"]
|
||||
return for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
|
||||
|
||||
def _entity(resources, coordinator=None):
|
||||
reg = _reg(resources)
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
fan_bound = next(
|
||||
item for item in bound
|
||||
if isinstance(item.desc, FanDesc) and item.href == HREF_WIND_STRENGTH
|
||||
item for item in bound if isinstance(item.desc, FanDesc) and item.href == HREF_WIND_STRENGTH
|
||||
)
|
||||
return LocalThingsAirPurifierFan(
|
||||
cast(LocalThingsCoordinator, coordinator or _FakeCoordinator(resources)), fan_bound
|
||||
)
|
||||
return LocalThingsAirPurifierFan(coordinator or _FakeCoordinator(resources), fan_bound)
|
||||
|
||||
|
||||
def test_resolves_to_air_purifier_registry():
|
||||
assert _reg(_resources()).name == 'air_purifier'
|
||||
assert _reg(_resources()).name == "air_purifier"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -73,13 +78,13 @@ def test_no_unbound_hrefs():
|
||||
|
||||
def test_preset_modes_come_from_modes_name_not_the_raw_codes():
|
||||
entity = _entity(_resources())
|
||||
assert entity.preset_modes == ['smart', 'max', 'windfree', 'sleep']
|
||||
assert entity.preset_modes == ["smart", "max", "windfree", "sleep"]
|
||||
|
||||
|
||||
def test_preset_mode_reads_the_current_code_via_modes_name():
|
||||
"""Fixture's current mode is '87' -> modesName[0] 'SMART'."""
|
||||
entity = _entity(_resources())
|
||||
assert entity.preset_mode == 'smart'
|
||||
assert entity.preset_mode == "smart"
|
||||
|
||||
|
||||
async def test_set_preset_mode_writes_back_the_raw_code():
|
||||
@@ -87,9 +92,9 @@ async def test_set_preset_mode_writes_back_the_raw_code():
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_preset_mode('windfree')
|
||||
await entity.async_set_preset_mode("windfree")
|
||||
|
||||
assert coordinator.commands[-1][1] == ('mode', '90')
|
||||
assert coordinator.commands[-1][1] == ("mode", "90")
|
||||
|
||||
|
||||
def test_is_on_reads_vendor_power():
|
||||
@@ -111,7 +116,7 @@ def test_wind_strength_fan_key_does_not_collide_with_mode_fan():
|
||||
for cap in (air_purifier.FAN, air_purifier.WIND_STRENGTH_FAN)
|
||||
for entity in cap.entities
|
||||
}
|
||||
assert fan_keys == {'fan', 'wind_strength_fan'}
|
||||
assert fan_keys == {"fan", "wind_strength_fan"}
|
||||
|
||||
|
||||
def test_both_fan_hrefs_bound_simultaneously_produce_distinct_entities():
|
||||
@@ -121,14 +126,14 @@ def test_both_fan_hrefs_bound_simultaneously_produce_distinct_entities():
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
|
||||
resources = _resources()
|
||||
resources['/mode/vs/0'] = {
|
||||
'x.com.samsung.da.modes': ['Smart'],
|
||||
'x.com.samsung.da.supportedModes': ['Smart', 'Max', 'Mid', 'WindFree', 'Sleep'],
|
||||
resources["/mode/vs/0"] = {
|
||||
"x.com.samsung.da.modes": ["Smart"],
|
||||
"x.com.samsung.da.supportedModes": ["Smart", "Max", "Mid", "WindFree", "Sleep"],
|
||||
}
|
||||
reg = _reg(resources)
|
||||
unbound = []
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['fan'] == 'Smart'
|
||||
assert state['wind_strength_fan'] == '87'
|
||||
assert state["fan"] == "Smart"
|
||||
assert state["wind_strength_fan"] == "87"
|
||||
@@ -18,27 +18,34 @@ the same model with a slightly different token set (no ``Spi``,
|
||||
``FilterTime_5460``, ``OutdoorTemp_81``), which the token entities' presence
|
||||
gating handles the same way it handles newer boards.
|
||||
"""
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from custom_components.localthings.climate import LocalThingsClimate
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import (
|
||||
airconditioner, for_device_by_model,
|
||||
airconditioner,
|
||||
for_device_by_model,
|
||||
)
|
||||
from custom_components.localthings.registry.capabilities.airconditioner import (
|
||||
HREF_AIRFLOW, HREF_WIND_STRENGTH, _option_number_write,
|
||||
_option_switch_write, is_legacy_board,
|
||||
HREF_AIRFLOW,
|
||||
HREF_WIND_STRENGTH,
|
||||
_option_number_write,
|
||||
_option_switch_write,
|
||||
is_legacy_board,
|
||||
)
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.entities import ClimateDesc
|
||||
from tests.conftest import _load_device
|
||||
|
||||
FIXTURE = 'airconditioner_artik051_krac_18k'
|
||||
MODEL = 'ARTIK051_KRAC_18K|10193441|60010119001111010100000000000000'
|
||||
FIXTURE = "airconditioner_artik051_krac_18k"
|
||||
MODEL = "ARTIK051_KRAC_18K|10193441|60010119001111010100000000000000"
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-KRAC-SERIAL'
|
||||
device_info = {}
|
||||
data = {}
|
||||
device_serial = "TEST-KRAC-SERIAL"
|
||||
device_info: ClassVar[dict] = {}
|
||||
data: ClassVar[dict] = {}
|
||||
|
||||
def __init__(self, resources):
|
||||
self.last_resources = resources
|
||||
@@ -59,8 +66,9 @@ class _FakeCoordinator:
|
||||
|
||||
def _discover(resources, registry=airconditioner.REGISTRY):
|
||||
unbound = []
|
||||
bound = discover(resources, registry.capabilities,
|
||||
registry.pattern_capabilities, log=unbound.append)
|
||||
bound = discover(
|
||||
resources, registry.capabilities, registry.pattern_capabilities, log=unbound.append
|
||||
)
|
||||
return bound, unbound
|
||||
|
||||
|
||||
@@ -72,24 +80,24 @@ def _state(fixture=FIXTURE):
|
||||
|
||||
def _climate(resources, coordinator=None):
|
||||
bound, _ = _discover(resources)
|
||||
climate_bound = next(
|
||||
item for item in bound if isinstance(item.desc, ClimateDesc)
|
||||
)
|
||||
climate_bound = next(item for item in bound if isinstance(item.desc, ClimateDesc))
|
||||
return LocalThingsClimate(
|
||||
coordinator or _FakeCoordinator(resources), climate_bound,
|
||||
coordinator or _FakeCoordinator(resources),
|
||||
climate_bound,
|
||||
)
|
||||
|
||||
|
||||
# -- device type --------------------------------------------------------------
|
||||
|
||||
|
||||
def test_krac_model_resolves_to_the_airconditioner_registry():
|
||||
"""The '_RAC_' token check can't see '_KRAC_' -- the 'K' sits between the
|
||||
underscore and 'RAC' -- and the consumer-prefix fallback only covers
|
||||
washers/dryers/dishwashers, so this model resolved to 'unknown' and
|
||||
exposed nothing but power."""
|
||||
registry = for_device_by_model(MODEL, 'ARTIK051_KRAC_18K')
|
||||
registry = for_device_by_model(MODEL, "ARTIK051_KRAC_18K")
|
||||
assert registry is not None
|
||||
assert registry.name == 'airconditioner'
|
||||
assert registry.name == "airconditioner"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -99,20 +107,21 @@ def test_no_unbound_hrefs():
|
||||
|
||||
# -- option-token entities ----------------------------------------------------
|
||||
|
||||
|
||||
def test_token_entities_present_with_calibrated_values():
|
||||
state = _state()
|
||||
# token/10 hours: 1715 displayed as "171 hours 0 minutes"... at 1710 in the
|
||||
# official app on this unit, which pins the scale (the .5 here is a later
|
||||
# reading). It counts up -- see the descriptor comment and
|
||||
# test_filter_alarm_tracks_the_counter_against_its_threshold below.
|
||||
assert state['filter_time'] == 171.5
|
||||
assert state["filter_time"] == 171.5
|
||||
# token - 55 == 19 C, against a 19.4 C forecast at the time of the dump.
|
||||
assert state['outdoor_temperature'] == 19.0
|
||||
assert state['beep'] is True
|
||||
assert state['good_sleep'] == 0.0
|
||||
assert state['spi'] is False
|
||||
assert state['auto_clean_legacy'] is False
|
||||
assert state['air_monitoring'] is False
|
||||
assert state["outdoor_temperature"] == 19.0
|
||||
assert state["beep"] is True
|
||||
assert state["good_sleep"] == 0.0
|
||||
assert state["spi"] is False
|
||||
assert state["auto_clean_legacy"] is False
|
||||
assert state["air_monitoring"] is False
|
||||
|
||||
|
||||
def test_token_entities_stay_off_newer_boards():
|
||||
@@ -120,9 +129,15 @@ def test_token_entities_stay_off_newer_boards():
|
||||
while also exposing those settings as dedicated resources -- ungated, the
|
||||
token entities would duplicate them (auto clean) or apply a scale
|
||||
calibrated on another board generation (outdoor temperature)."""
|
||||
state = _state('airconditioner_tp1x_rac')
|
||||
for key in ('spi', 'auto_clean_legacy', 'air_monitoring',
|
||||
'good_sleep', 'outdoor_temperature', 'filter_time'):
|
||||
state = _state("airconditioner_tp1x_rac")
|
||||
for key in (
|
||||
"spi",
|
||||
"auto_clean_legacy",
|
||||
"air_monitoring",
|
||||
"good_sleep",
|
||||
"outdoor_temperature",
|
||||
"filter_time",
|
||||
):
|
||||
assert key not in state, key
|
||||
|
||||
|
||||
@@ -136,7 +151,7 @@ def test_climate_legacy_airflow_gate_agrees_with_is_legacy_board():
|
||||
assert is_legacy_board(legacy_resources) is True
|
||||
assert _climate(legacy_resources)._legacy_airflow() == legacy_resources[HREF_AIRFLOW]
|
||||
|
||||
newer_resources = _load_device('airconditioner_tp1x_rac')
|
||||
newer_resources = _load_device("airconditioner_tp1x_rac")
|
||||
assert is_legacy_board(newer_resources) is False
|
||||
assert _climate(newer_resources)._legacy_airflow() == {}
|
||||
assert HREF_WIND_STRENGTH in newer_resources
|
||||
@@ -145,12 +160,12 @@ def test_climate_legacy_airflow_gate_agrees_with_is_legacy_board():
|
||||
def test_absent_token_yields_no_entity():
|
||||
"""The issue #136 unit of this same model reports no Spi token."""
|
||||
resources = _load_device(FIXTURE)
|
||||
options = resources['/mode/vs/0']['x.com.samsung.da.options']
|
||||
resources['/mode/vs/0']['x.com.samsung.da.options'] = [
|
||||
option for option in options if not option.startswith('Spi_')
|
||||
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
|
||||
resources["/mode/vs/0"]["x.com.samsung.da.options"] = [
|
||||
option for option in options if not option.startswith("Spi_")
|
||||
]
|
||||
bound, _ = _discover(resources)
|
||||
assert 'spi' not in flatten(bound, resources)
|
||||
assert "spi" not in flatten(bound, resources)
|
||||
|
||||
|
||||
def test_humidity_reads_the_vendor_field_and_treats_zero_as_unknown():
|
||||
@@ -158,30 +173,33 @@ def test_humidity_reads_the_vendor_field_and_treats_zero_as_unknown():
|
||||
only carries a reading while Air monitoring is on, and the unit switches
|
||||
that back off by itself after about a minute."""
|
||||
resources = _load_device(FIXTURE)
|
||||
assert resources['/humidity/vs/0']['x.com.samsung.da.humidity'] == '0'
|
||||
assert resources["/humidity/vs/0"]["x.com.samsung.da.humidity"] == "0"
|
||||
bound, _ = _discover(resources)
|
||||
assert flatten(bound, resources)['humidity'] is None
|
||||
assert flatten(bound, resources)["humidity"] is None
|
||||
|
||||
resources['/humidity/vs/0']['x.com.samsung.da.humidity'] = '51'
|
||||
resources["/humidity/vs/0"]["x.com.samsung.da.humidity"] = "51"
|
||||
bound, _ = _discover(resources)
|
||||
assert flatten(bound, resources)['humidity'] == 51.0
|
||||
assert flatten(bound, resources)["humidity"] == 51.0
|
||||
|
||||
|
||||
def test_option_writes_carry_one_token():
|
||||
"""Both go through option_write's single-token merge, the same mechanism
|
||||
the display light already uses on this href. Confirmed on hardware by
|
||||
read-back: Spi_On/Spi_Off, and the volume token surviving a write."""
|
||||
assert _option_switch_write('Spi')('On', {}) == (
|
||||
['mode', 'vs', '0'], {'x.com.samsung.da.options': ['Spi_On']},
|
||||
assert _option_switch_write("Spi")("On", {}) == (
|
||||
["mode", "vs", "0"],
|
||||
{"x.com.samsung.da.options": ["Spi_On"]},
|
||||
)
|
||||
# The number platform hands over a float; the device wants an integer token.
|
||||
assert _option_number_write('Volume')(70.0, {}) == (
|
||||
['mode', 'vs', '0'], {'x.com.samsung.da.options': ['Volume_70']},
|
||||
assert _option_number_write("Volume")(70.0, {}) == (
|
||||
["mode", "vs", "0"],
|
||||
{"x.com.samsung.da.options": ["Volume_70"]},
|
||||
)
|
||||
|
||||
|
||||
# -- filter counter and its reset ---------------------------------------------
|
||||
|
||||
|
||||
def _desc(resources, key):
|
||||
"""The bound descriptor for `key`, or None when its exists_fn declines it.
|
||||
|
||||
@@ -206,13 +224,13 @@ def test_filter_alarm_time_reads_the_threshold_and_writes_one_token():
|
||||
options tuple defensible here (the board advertises no supported-values
|
||||
list for options[] tokens)."""
|
||||
state = _state()
|
||||
assert state['filter_alarm_time'] == '500' # the fixture's own value
|
||||
assert state["filter_alarm_time"] == "500" # the fixture's own value
|
||||
|
||||
desc = _desc(_load_device(FIXTURE), 'filter_alarm_time')
|
||||
assert desc.options == ('180', '300', '500', '700')
|
||||
assert desc.write_fn('180', {}) == (
|
||||
['mode', 'vs', '0'],
|
||||
{'x.com.samsung.da.options': ['FilterAlarmTime_180']},
|
||||
desc = _desc(_load_device(FIXTURE), "filter_alarm_time")
|
||||
assert desc.options == ("180", "300", "500", "700")
|
||||
assert desc.write_fn("180", {}) == (
|
||||
["mode", "vs", "0"],
|
||||
{"x.com.samsung.da.options": ["FilterAlarmTime_180"]},
|
||||
)
|
||||
|
||||
|
||||
@@ -225,15 +243,16 @@ def test_filter_alarm_time_stays_off_boards_with_a_real_threshold_resource():
|
||||
would pass for the wrong reason -- absent token rather than the
|
||||
board-generation gate. The token is injected to exercise the gate itself,
|
||||
test_absent_token_yields_no_entity's technique in reverse."""
|
||||
newer = _load_device('airconditioner_tp1x_rac')
|
||||
assert _desc(newer, 'filter_alarm_time') is None
|
||||
newer = _load_device("airconditioner_tp1x_rac")
|
||||
assert _desc(newer, "filter_alarm_time") is None
|
||||
|
||||
mode = newer['/mode/vs/0']
|
||||
mode['x.com.samsung.da.options'] = [
|
||||
*(mode.get('x.com.samsung.da.options') or []), 'FilterAlarmTime_500',
|
||||
mode = newer["/mode/vs/0"]
|
||||
mode["x.com.samsung.da.options"] = [
|
||||
*(mode.get("x.com.samsung.da.options") or []),
|
||||
"FilterAlarmTime_500",
|
||||
]
|
||||
assert is_legacy_board(newer) is False
|
||||
assert _desc(newer, 'filter_alarm_time') is None
|
||||
assert _desc(newer, "filter_alarm_time") is None
|
||||
|
||||
|
||||
def test_filter_alarm_tracks_the_counter_against_its_threshold():
|
||||
@@ -243,36 +262,36 @@ def test_filter_alarm_tracks_the_counter_against_its_threshold():
|
||||
same site, at FilterTime_5595 against the same FilterAlarmTime_500, instead
|
||||
reported an unsuffixed 'FilterAlarm' in state 'Created'."""
|
||||
resources = _load_device(FIXTURE)
|
||||
options = resources['/mode/vs/0']['x.com.samsung.da.options']
|
||||
assert 'FilterTime_1715' in options
|
||||
assert 'FilterAlarmTime_500' in options
|
||||
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
|
||||
assert "FilterTime_1715" in options
|
||||
assert "FilterAlarmTime_500" in options
|
||||
|
||||
alarms = resources['/alarms/vs/0']['x.com.samsung.da.items']
|
||||
alarms = resources["/alarms/vs/0"]["x.com.samsung.da.items"]
|
||||
filter_alarm = next(
|
||||
item for item in alarms
|
||||
if item['x.com.samsung.da.code'].startswith('FilterAlarm')
|
||||
item for item in alarms if item["x.com.samsung.da.code"].startswith("FilterAlarm")
|
||||
)
|
||||
assert filter_alarm['x.com.samsung.da.code'] == 'FilterAlarm_OFF'
|
||||
assert filter_alarm['x.com.samsung.da.state'] == 'Deleted'
|
||||
assert filter_alarm["x.com.samsung.da.code"] == "FilterAlarm_OFF"
|
||||
assert filter_alarm["x.com.samsung.da.state"] == "Deleted"
|
||||
|
||||
|
||||
# -- climate entity: fan, swing and preset off /airflow/vs/0 ------------------
|
||||
|
||||
|
||||
def test_fan_mode_reads_the_airflow_speed_level():
|
||||
entity = _climate(_load_device(FIXTURE))
|
||||
assert entity.fan_mode == 'high' # speedLevel 3 in the fixture
|
||||
assert entity.fan_mode == "high" # speedLevel 3 in the fixture
|
||||
# No supportedModes on this resource, so the full 0-4 scale is offered.
|
||||
assert entity.fan_modes == ['auto', 'low', 'medium', 'high', 'turbo']
|
||||
assert entity.fan_modes == ["auto", "low", "medium", "high", "turbo"]
|
||||
|
||||
|
||||
def test_swing_mode_reads_the_airflow_direction():
|
||||
resources = _load_device(FIXTURE)
|
||||
entity = _climate(resources)
|
||||
assert entity.swing_mode == 'off' # 'Fix' in the fixture
|
||||
assert entity.swing_mode == "off" # 'Fix' in the fixture
|
||||
|
||||
resources[HREF_AIRFLOW]['x.com.samsung.da.direction'] = 'All'
|
||||
assert _climate(resources).swing_mode == 'both'
|
||||
assert 'both' in _climate(resources).swing_modes
|
||||
resources[HREF_AIRFLOW]["x.com.samsung.da.direction"] = "All"
|
||||
assert _climate(resources).swing_mode == "both"
|
||||
assert "both" in _climate(resources).swing_modes
|
||||
|
||||
|
||||
async def test_fan_and_swing_writes_target_the_airflow_resource():
|
||||
@@ -280,32 +299,37 @@ async def test_fan_and_swing_writes_target_the_airflow_resource():
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _climate(resources, coordinator)
|
||||
|
||||
await entity.async_set_fan_mode('turbo')
|
||||
await entity.async_set_swing_mode('both')
|
||||
await entity.async_set_fan_mode("turbo")
|
||||
await entity.async_set_swing_mode("both")
|
||||
|
||||
assert [payload for _, payload in coordinator.commands] == [
|
||||
('fan_legacy', '4'), ('swing_legacy', 'All'),
|
||||
("fan_legacy", "4"),
|
||||
("swing_legacy", "All"),
|
||||
]
|
||||
|
||||
|
||||
def test_preset_comes_from_the_comode_token():
|
||||
resources = _load_device(FIXTURE)
|
||||
entity = _climate(resources)
|
||||
assert entity.preset_mode == 'none' # Comode_Off in the fixture
|
||||
assert entity.preset_mode == "none" # Comode_Off in the fixture
|
||||
# Codes learned by driving this unit through its cloud integration and
|
||||
# reading the token back. They go through the same dynamic resolver as a
|
||||
# real convenient resource's supportedModes, so 'Nano' resolves to the
|
||||
# existing 'nano' preset -- already labelled WindFree in the catalog.
|
||||
assert entity.preset_modes == [
|
||||
'none', 'nano', 'quiet', 'comfort', '2step', 'speed',
|
||||
"none",
|
||||
"nano",
|
||||
"quiet",
|
||||
"comfort",
|
||||
"2step",
|
||||
"speed",
|
||||
]
|
||||
|
||||
options = resources['/mode/vs/0']['x.com.samsung.da.options']
|
||||
resources['/mode/vs/0']['x.com.samsung.da.options'] = [
|
||||
'Comode_Nano' if option.startswith('Comode_') else option
|
||||
for option in options
|
||||
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
|
||||
resources["/mode/vs/0"]["x.com.samsung.da.options"] = [
|
||||
"Comode_Nano" if option.startswith("Comode_") else option for option in options
|
||||
]
|
||||
assert _climate(resources).preset_mode == 'nano'
|
||||
assert _climate(resources).preset_mode == "nano"
|
||||
|
||||
|
||||
async def test_preset_write_uses_the_token_path():
|
||||
@@ -313,21 +337,21 @@ async def test_preset_write_uses_the_token_path():
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _climate(resources, coordinator)
|
||||
|
||||
await entity.async_set_preset_mode('nano')
|
||||
await entity.async_set_preset_mode("nano")
|
||||
|
||||
assert coordinator.commands[-1][1] == ('preset_legacy', 'Nano')
|
||||
assert coordinator.commands[-1][1] == ("preset_legacy", "Nano")
|
||||
|
||||
|
||||
async def test_newer_boards_keep_the_resource_paths():
|
||||
"""The legacy fallbacks are gated on this board's resource shape, so a
|
||||
board with /wind/* and /mode/convenient/vs/0 must be untouched by them."""
|
||||
resources = _load_device('airconditioner_tp1x_rac')
|
||||
resources = _load_device("airconditioner_tp1x_rac")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _climate(resources, coordinator)
|
||||
|
||||
await entity.async_set_fan_mode('high')
|
||||
await entity.async_set_swing_mode('off')
|
||||
await entity.async_set_preset_mode('quiet') # from its own supportedModes
|
||||
await entity.async_set_fan_mode("high")
|
||||
await entity.async_set_swing_mode("off")
|
||||
await entity.async_set_preset_mode("quiet") # from its own supportedModes
|
||||
|
||||
kinds = [payload[0] for _, payload in coordinator.commands]
|
||||
assert kinds == ['fan', 'swing', 'preset']
|
||||
assert kinds == ["fan", "swing", "preset"]
|
||||
@@ -13,38 +13,41 @@ new to this board generation. That's a real device-support gap, left
|
||||
documented here rather than guessed at, per the 'don't guess' rule -- fixing
|
||||
the routing regression was the scope of #191.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
_STILL_UNBOUND = frozenset({
|
||||
'/edgelighting/vs/0',
|
||||
'/filter/airdustPM1filter/vs/0',
|
||||
'/light/stateful/vs/0',
|
||||
'/mds/absenceclean/vs/0',
|
||||
'/settings/sound/mode/vs/0',
|
||||
'/settings/sound/optimization/vs/0',
|
||||
'/settings/sound/output/vs/0',
|
||||
'/settings/sound/volume/vs/0',
|
||||
'/smartsensingcooling/vs/0',
|
||||
'/uvled/vs/0',
|
||||
})
|
||||
_STILL_UNBOUND = frozenset(
|
||||
{
|
||||
"/edgelighting/vs/0",
|
||||
"/filter/airdustPM1filter/vs/0",
|
||||
"/light/stateful/vs/0",
|
||||
"/mds/absenceclean/vs/0",
|
||||
"/settings/sound/mode/vs/0",
|
||||
"/settings/sound/optimization/vs/0",
|
||||
"/settings/sound/output/vs/0",
|
||||
"/settings/sound/volume/vs/0",
|
||||
"/smartsensingcooling/vs/0",
|
||||
"/uvled/vs/0",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _resources():
|
||||
return _load_device('airconditioner_cac')
|
||||
return _load_device("airconditioner_cac")
|
||||
|
||||
|
||||
def _reg(resources):
|
||||
info = resources['/information/vs/0']
|
||||
info = resources["/information/vs/0"]
|
||||
return for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
|
||||
|
||||
def test_resolves_to_airconditioner_registry():
|
||||
assert _reg(_resources()).name == 'airconditioner'
|
||||
assert _reg(_resources()).name == "airconditioner"
|
||||
|
||||
|
||||
def test_documented_coverage_gap_is_exactly_this_set():
|
||||
@@ -67,4 +70,4 @@ def test_non_legacy_board_uses_the_generic_energy_scale():
|
||||
reg = _reg(resources)
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
state = flatten(bound, resources)
|
||||
assert state['energy_kwh'] == round(84044 / 1000.0, 2)
|
||||
assert state["energy_kwh"] == round(84044 / 1000.0, 2)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,22 +10,26 @@ device's own modesName labels (parallel-indexed with supportedModes) for
|
||||
any code _DEVICE_TO_FAN doesn't already cover, instead of hardcoding a
|
||||
second numeric scale.
|
||||
"""
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from custom_components.localthings.climate import (
|
||||
LocalThingsClimate, _DEVICE_TO_FAN, _wind_strength_label,
|
||||
_DEVICE_TO_FAN,
|
||||
LocalThingsClimate,
|
||||
_wind_strength_label,
|
||||
)
|
||||
from custom_components.localthings.registry import by_type
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.entities import ClimateDesc
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
FIXTURE = 'airconditioner_tp1x_rac_01001'
|
||||
FIXTURE = "airconditioner_tp1x_rac_01001"
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-RAC-01001-SERIAL'
|
||||
device_info = {}
|
||||
data = {}
|
||||
device_serial = "TEST-RAC-01001-SERIAL"
|
||||
device_info: ClassVar[dict] = {}
|
||||
data: ClassVar[dict] = {}
|
||||
|
||||
def __init__(self, resources):
|
||||
self.last_resources = resources
|
||||
@@ -45,9 +49,10 @@ class _FakeCoordinator:
|
||||
|
||||
|
||||
def _climate(resources, coordinator=None):
|
||||
info = resources['/information/vs/0']
|
||||
info = resources["/information/vs/0"]
|
||||
reg = by_type.for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
climate_bound = next(item for item in bound if isinstance(item.desc, ClimateDesc))
|
||||
return LocalThingsClimate(coordinator or _FakeCoordinator(resources), climate_bound)
|
||||
@@ -55,15 +60,15 @@ def _climate(resources, coordinator=None):
|
||||
|
||||
def test_wind_strength_label_reads_the_devices_own_modes_name():
|
||||
rep = {
|
||||
'x.com.samsung.da.supportedModes': ['0', '31', '32', '33', '34', '35'],
|
||||
'x.com.samsung.da.modesName': ['Auto', '1', '2', '3', '4', 'MAX'],
|
||||
"x.com.samsung.da.supportedModes": ["0", "31", "32", "33", "34", "35"],
|
||||
"x.com.samsung.da.modesName": ["Auto", "1", "2", "3", "4", "MAX"],
|
||||
}
|
||||
assert _wind_strength_label('32', rep) == '2'
|
||||
assert _wind_strength_label('35', rep) == 'max'
|
||||
assert _wind_strength_label("32", rep) == "2"
|
||||
assert _wind_strength_label("35", rep) == "max"
|
||||
|
||||
|
||||
def test_wind_strength_label_falls_back_to_raw_code_when_names_absent():
|
||||
assert _wind_strength_label('32', {}) == '32'
|
||||
assert _wind_strength_label("32", {}) == "32"
|
||||
|
||||
|
||||
def test_fan_modes_include_every_supported_speed_not_just_auto():
|
||||
@@ -71,14 +76,14 @@ def test_fan_modes_include_every_supported_speed_not_just_auto():
|
||||
['auto'] -- exactly the reported symptom."""
|
||||
resources = _load_device(FIXTURE)
|
||||
entity = _climate(resources)
|
||||
assert entity.fan_modes == ['auto', '1', '2', '3', '4', 'max']
|
||||
assert entity.fan_modes == ["auto", "1", "2", "3", "4", "max"]
|
||||
|
||||
|
||||
def test_fan_mode_reads_the_current_dynamic_code():
|
||||
"""Fixture's /wind/strength/vs/0 modes is '32' -> modesName '2'."""
|
||||
resources = _load_device(FIXTURE)
|
||||
entity = _climate(resources)
|
||||
assert entity.fan_mode == '2'
|
||||
assert entity.fan_mode == "2"
|
||||
|
||||
|
||||
def test_standard_scale_codes_still_use_device_to_fan():
|
||||
@@ -86,9 +91,9 @@ def test_standard_scale_codes_still_use_device_to_fan():
|
||||
label rather than falling through to the device's own (blunter) one --
|
||||
no regression for boards using the standard "0"-"4" scale."""
|
||||
resources = _load_device(FIXTURE)
|
||||
resources['/wind/strength/vs/0']['x.com.samsung.da.modes'] = '0'
|
||||
resources["/wind/strength/vs/0"]["x.com.samsung.da.modes"] = "0"
|
||||
entity = _climate(resources)
|
||||
assert entity.fan_mode == _DEVICE_TO_FAN['0'] == 'auto'
|
||||
assert entity.fan_mode == _DEVICE_TO_FAN["0"] == "auto"
|
||||
|
||||
|
||||
async def test_set_fan_mode_resolves_a_dynamic_label_back_to_its_code():
|
||||
@@ -96,9 +101,9 @@ async def test_set_fan_mode_resolves_a_dynamic_label_back_to_its_code():
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _climate(resources, coordinator)
|
||||
|
||||
await entity.async_set_fan_mode('max')
|
||||
await entity.async_set_fan_mode("max")
|
||||
|
||||
assert coordinator.commands[-1][1] == ('fan', '35')
|
||||
assert coordinator.commands[-1][1] == ("fan", "35")
|
||||
|
||||
|
||||
async def test_set_fan_mode_still_resolves_standard_scale_labels():
|
||||
@@ -106,9 +111,9 @@ async def test_set_fan_mode_still_resolves_standard_scale_labels():
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _climate(resources, coordinator)
|
||||
|
||||
await entity.async_set_fan_mode('auto')
|
||||
await entity.async_set_fan_mode("auto")
|
||||
|
||||
assert coordinator.commands[-1][1] == ('fan', '0')
|
||||
assert coordinator.commands[-1][1] == ("fan", "0")
|
||||
|
||||
|
||||
async def test_set_fan_mode_does_not_misroute_when_static_map_and_live_codes_collide():
|
||||
@@ -120,21 +125,21 @@ async def test_set_fan_mode_does_not_misroute_when_static_map_and_live_codes_col
|
||||
supportedModes would silently write a code the device doesn't have.
|
||||
"""
|
||||
resources = _load_device(FIXTURE)
|
||||
resources['/wind/strength/vs/0'] = {
|
||||
'x.com.samsung.da.modes': '0',
|
||||
'x.com.samsung.da.supportedModes': ['0', '31', '32', '33'],
|
||||
'x.com.samsung.da.modesName': ['Auto', 'Low', 'High', 'Turbo'],
|
||||
resources["/wind/strength/vs/0"] = {
|
||||
"x.com.samsung.da.modes": "0",
|
||||
"x.com.samsung.da.supportedModes": ["0", "31", "32", "33"],
|
||||
"x.com.samsung.da.modesName": ["Auto", "Low", "High", "Turbo"],
|
||||
}
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _climate(resources, coordinator)
|
||||
|
||||
assert entity.fan_modes == ['auto', 'low', 'high', 'turbo']
|
||||
assert entity.fan_modes == ["auto", "low", "high", "turbo"]
|
||||
|
||||
await entity.async_set_fan_mode('high')
|
||||
assert coordinator.commands[-1][1] == ('fan', '32')
|
||||
await entity.async_set_fan_mode("high")
|
||||
assert coordinator.commands[-1][1] == ("fan", "32")
|
||||
|
||||
await entity.async_set_fan_mode('low')
|
||||
assert coordinator.commands[-1][1] == ('fan', '31')
|
||||
await entity.async_set_fan_mode("low")
|
||||
assert coordinator.commands[-1][1] == ("fan", "31")
|
||||
|
||||
await entity.async_set_fan_mode('turbo')
|
||||
assert coordinator.commands[-1][1] == ('fan', '33')
|
||||
await entity.async_set_fan_mode("turbo")
|
||||
assert coordinator.commands[-1][1] == ("fan", "33")
|
||||
+13
-12
@@ -8,49 +8,50 @@ empty" apart from "haven't polled it yet" and created phantom always-
|
||||
"unknown" entities either way. is_stub_rep/parse_device0_batch now keep the
|
||||
two shapes distinct.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.batch import is_stub_rep, parse_device0_batch
|
||||
|
||||
|
||||
class TestIsStubRep:
|
||||
def test_true_for_bare_href_marker(self):
|
||||
assert is_stub_rep({'href': '/energy/consumption/vs/0'}) is True
|
||||
assert is_stub_rep({"href": "/energy/consumption/vs/0"}) is True
|
||||
|
||||
def test_false_for_genuinely_empty_rep(self):
|
||||
assert is_stub_rep({}) is False
|
||||
|
||||
def test_false_for_populated_rep(self):
|
||||
assert is_stub_rep({'x.com.samsung.da.cumulativePower': '58900'}) is False
|
||||
assert is_stub_rep({"x.com.samsung.da.cumulativePower": "58900"}) is False
|
||||
|
||||
def test_false_for_href_plus_data(self):
|
||||
"""A real, populated rep may legitimately echo 'href' alongside
|
||||
actual fields -- only a rep with *no other keys* is the stub."""
|
||||
assert is_stub_rep({'href': '/x/0', 'value': True}) is False
|
||||
assert is_stub_rep({"href": "/x/0", "value": True}) is False
|
||||
|
||||
|
||||
class TestParseDevice0Batch:
|
||||
def test_stub_rep_kept_distinct_from_genuine_empty(self):
|
||||
device0 = [
|
||||
{},
|
||||
{'href': '/energy/consumption/vs/0', 'rep': {'href': '/energy/consumption/vs/0'}},
|
||||
{'href': '/sabbath/vs/0', 'rep': {}},
|
||||
{"href": "/energy/consumption/vs/0", "rep": {"href": "/energy/consumption/vs/0"}},
|
||||
{"href": "/sabbath/vs/0", "rep": {}},
|
||||
]
|
||||
resources = parse_device0_batch(device0)
|
||||
assert is_stub_rep(resources['/energy/consumption/vs/0']) is True
|
||||
assert is_stub_rep(resources['/sabbath/vs/0']) is False
|
||||
assert resources['/sabbath/vs/0'] == {}
|
||||
assert is_stub_rep(resources["/energy/consumption/vs/0"]) is True
|
||||
assert is_stub_rep(resources["/sabbath/vs/0"]) is False
|
||||
assert resources["/sabbath/vs/0"] == {}
|
||||
|
||||
def test_populated_rep_passes_through_unchanged(self):
|
||||
device0 = [
|
||||
{},
|
||||
{'href': '/door/cooler/0', 'rep': {'openState': 'Close'}},
|
||||
{"href": "/door/cooler/0", "rep": {"openState": "Close"}},
|
||||
]
|
||||
resources = parse_device0_batch(device0)
|
||||
assert resources['/door/cooler/0'] == {'openState': 'Close'}
|
||||
assert resources["/door/cooler/0"] == {"openState": "Close"}
|
||||
|
||||
def test_skips_entries_without_href(self):
|
||||
device0 = [{}, {'rep': {'a': 1}}]
|
||||
device0 = [{}, {"rep": {"a": 1}}]
|
||||
assert parse_device0_batch(device0) == {}
|
||||
|
||||
def test_skips_non_dict_rep(self):
|
||||
device0 = [{}, {'href': '/x/0', 'rep': 'not-a-dict'}]
|
||||
device0 = [{}, {"href": "/x/0", "rep": "not-a-dict"}]
|
||||
assert parse_device0_batch(device0) == {}
|
||||
+340
-234
File diff suppressed because it is too large.
Load diff
@@ -1,44 +1,42 @@
|
||||
"""Tests for device-type registries and DOOR_GENERIC pattern capability."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.localthings.registry.adapter import _key
|
||||
from custom_components.localthings.registry.by_type import dishwasher, refrigerator
|
||||
from custom_components.localthings.registry.capabilities import fridge
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_resources
|
||||
|
||||
GOLDEN = Path(__file__).parent / 'fixtures' / 'golden'
|
||||
GOLDEN = Path(__file__).parent / "fixtures" / "golden"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration: dishwasher and refrigerator registries
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_dishwasher_registry_discovers_expected_keys():
|
||||
"""Discover over dishwasher dump and verify golden state_keys are a subset."""
|
||||
resources = _load_resources('10.0.0.129')
|
||||
resources = _load_resources("10.0.0.129")
|
||||
reg = dishwasher.REGISTRY
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
actual_keys = {_key(b) for b in bound}
|
||||
golden = json.loads((GOLDEN / 'dishwasher.json').read_text())
|
||||
golden_keys = set(golden['state_keys'])
|
||||
golden = json.loads((GOLDEN / "dishwasher.json").read_text())
|
||||
golden_keys = set(golden["state_keys"])
|
||||
missing = golden_keys - actual_keys
|
||||
assert not missing, (
|
||||
f"Golden keys not found in dishwasher discover output:\n {sorted(missing)}"
|
||||
)
|
||||
assert not missing, f"Golden keys not found in dishwasher discover output:\n {sorted(missing)}"
|
||||
|
||||
|
||||
def test_refrigerator_registry_discovers_expected_keys():
|
||||
"""Discover over refrigerator dump and verify golden state_keys are a subset."""
|
||||
resources = _load_resources('10.0.0.254')
|
||||
resources = _load_resources("10.0.0.254")
|
||||
reg = refrigerator.REGISTRY
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
actual_keys = {_key(b) for b in bound}
|
||||
golden = json.loads((GOLDEN / 'refrigerator.json').read_text())
|
||||
golden_keys = set(golden['state_keys'])
|
||||
golden = json.loads((GOLDEN / "refrigerator.json").read_text())
|
||||
golden_keys = set(golden["state_keys"])
|
||||
missing = golden_keys - actual_keys
|
||||
assert not missing, (
|
||||
f"Golden keys not found in refrigerator discover output:\n {sorted(missing)}"
|
||||
@@ -49,23 +47,24 @@ def test_refrigerator_registry_discovers_expected_keys():
|
||||
# DOOR_GENERIC pattern capability unit tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_door_generic_binds_unknown_door_href():
|
||||
"""/door/wine/0 binds via DOOR_GENERIC (href_prefix='/door/') with key door_wine_open."""
|
||||
resources = {
|
||||
'/door/wine/0': {'openState': 'Open'},
|
||||
"/door/wine/0": {"openState": "Open"},
|
||||
}
|
||||
bound = discover(resources, {}, [fridge.DOOR_GENERIC])
|
||||
assert len(bound) == 1
|
||||
b = bound[0]
|
||||
# entity key 'open' + href segs ['door','wine'] -> 'door_wine_open'
|
||||
assert _key(b) == 'door_wine_open', f"Expected 'door_wine_open', got {_key(b)!r}"
|
||||
assert _key(b) == "door_wine_open", f"Expected 'door_wine_open', got {_key(b)!r}"
|
||||
|
||||
|
||||
def test_door_generic_does_not_bind_doors_aggregate():
|
||||
"""/doors/vs/0 does not start with '/door/' so DOOR_GENERIC must not bind it."""
|
||||
resources = {
|
||||
'/doors/vs/0': {
|
||||
'x.com.samsung.da.items': [],
|
||||
"/doors/vs/0": {
|
||||
"x.com.samsung.da.items": [],
|
||||
},
|
||||
}
|
||||
bound = discover(resources, {}, [fridge.DOOR_GENERIC])
|
||||
@@ -73,18 +72,17 @@ def test_door_generic_does_not_bind_doors_aggregate():
|
||||
|
||||
|
||||
def test_door_generic_binds_cooler_door_with_auto_derived_key():
|
||||
"""/door/cooler/0 is now handled by DOOR_GENERIC pattern cap with auto-derived key door_cooler_open."""
|
||||
"""/door/cooler/0 is now handled by DOOR_GENERIC pattern cap with
|
||||
auto-derived key door_cooler_open."""
|
||||
resources = {
|
||||
'/door/cooler/0': {'openState': 'Closed'},
|
||||
"/door/cooler/0": {"openState": "Closed"},
|
||||
}
|
||||
reg = refrigerator.REGISTRY
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
cooler_bindings = [b for b in bound if b.href == '/door/cooler/0']
|
||||
cooler_bindings = [b for b in bound if b.href == "/door/cooler/0"]
|
||||
assert len(cooler_bindings) == 1, (
|
||||
f"Expected exactly one binding for /door/cooler/0, got {len(cooler_bindings)}"
|
||||
)
|
||||
b = cooler_bindings[0]
|
||||
assert b.capability is fridge.DOOR_GENERIC, (
|
||||
f"Expected DOOR_GENERIC, got {b.capability!r}"
|
||||
)
|
||||
assert _key(b) == 'door_cooler_open', f"Expected 'door_cooler_open', got {_key(b)!r}"
|
||||
assert b.capability is fridge.DOOR_GENERIC, f"Expected DOOR_GENERIC, got {b.capability!r}"
|
||||
assert _key(b) == "door_cooler_open", f"Expected 'door_cooler_open', got {_key(b)!r}"
|
||||
@@ -3,16 +3,18 @@ from custom_components.localthings.registry.entities import BinarySensorDesc
|
||||
|
||||
|
||||
def test_capability_defaults():
|
||||
c = Capability(href='/kidslock/vs/0',
|
||||
entities=(BinarySensorDesc(key='child_lock', field='x.com.samsung.da.kidsLock'),))
|
||||
assert c.poll_tier == 'cold'
|
||||
c = Capability(
|
||||
href="/kidslock/vs/0",
|
||||
entities=(BinarySensorDesc(key="child_lock", field="x.com.samsung.da.kidsLock"),),
|
||||
)
|
||||
assert c.poll_tier == "cold"
|
||||
assert len(c.entities) == 1
|
||||
|
||||
|
||||
def test_capability_is_frozen():
|
||||
c = Capability(href='/kidslock/vs/0', entities=())
|
||||
c = Capability(href="/kidslock/vs/0", entities=())
|
||||
try:
|
||||
c.href = '/other/vs/0'
|
||||
c.href = "/other/vs/0"
|
||||
except Exception:
|
||||
return
|
||||
raise AssertionError("expected frozen dataclass")
|
||||
@@ -4,11 +4,15 @@ Module-level dicts/constants with no coordinator/entity dependency, so --
|
||||
like `_temps_vs_item` in test_climate_temperature_fallback.py -- they're
|
||||
testable directly.
|
||||
"""
|
||||
|
||||
from homeassistant.components.climate import HVACMode
|
||||
|
||||
from custom_components.localthings.climate import (
|
||||
_AI_COMFORT_MODE, _DEVICE_TO_HVAC, _HVAC_TO_DEVICE,
|
||||
PRESET_AI_COMFORT, _preset_to_ha,
|
||||
_AI_COMFORT_MODE,
|
||||
_DEVICE_TO_HVAC,
|
||||
_HVAC_TO_DEVICE,
|
||||
PRESET_AI_COMFORT,
|
||||
_preset_to_ha,
|
||||
)
|
||||
|
||||
|
||||
@@ -18,7 +22,7 @@ def test_auto_maps_to_hvac_auto():
|
||||
two-setpoint heat+cool range these single-setpoint units (including
|
||||
cool-only models) don't have. AIComfort is handled separately, not
|
||||
folded into this map."""
|
||||
assert _DEVICE_TO_HVAC['Auto'] == HVACMode.AUTO
|
||||
assert _DEVICE_TO_HVAC["Auto"] == HVACMode.AUTO
|
||||
|
||||
|
||||
def test_aicomfort_not_in_flat_hvac_map():
|
||||
@@ -34,19 +38,19 @@ def test_hvac_auto_writes_back_to_plain_auto_not_aicomfort():
|
||||
ai_comfort preset, since it isn't a flat _DEVICE_TO_HVAC entry (see
|
||||
test_aicomfort_not_in_flat_hvac_map) and so can never win the reverse
|
||||
{v: k} dict even though both map to HVACMode.AUTO conceptually."""
|
||||
assert _HVAC_TO_DEVICE[HVACMode.AUTO] == 'Auto'
|
||||
assert _HVAC_TO_DEVICE[HVACMode.AUTO] == "Auto"
|
||||
|
||||
|
||||
def test_fan_only_still_reachable_via_wind():
|
||||
"""Guard against regressing the existing 'Wind' -> FAN_ONLY entry while
|
||||
editing this map."""
|
||||
assert _DEVICE_TO_HVAC['Wind'] == HVACMode.FAN_ONLY
|
||||
assert _DEVICE_TO_HVAC["Wind"] == HVACMode.FAN_ONLY
|
||||
|
||||
|
||||
def test_fan_only_still_reachable_via_fan():
|
||||
"""'Fan' (e.g. TP1X_DA-AC-RAC-01011) is a second FAN_ONLY spelling
|
||||
alongside 'Wind' -- issue #91."""
|
||||
assert _DEVICE_TO_HVAC['Fan'] == HVACMode.FAN_ONLY
|
||||
assert _DEVICE_TO_HVAC["Fan"] == HVACMode.FAN_ONLY
|
||||
|
||||
|
||||
def test_fan_only_reverse_fallback_prefers_wind():
|
||||
@@ -56,24 +60,25 @@ def test_fan_only_reverse_fallback_prefers_wind():
|
||||
original single spelling, predating 'Fan') rather than silently
|
||||
flipping to whichever of the two duplicate-value entries happens to
|
||||
come last in _DEVICE_TO_HVAC."""
|
||||
assert _HVAC_TO_DEVICE[HVACMode.FAN_ONLY] == 'Wind'
|
||||
assert _HVAC_TO_DEVICE[HVACMode.FAN_ONLY] == "Wind"
|
||||
|
||||
|
||||
def test_preset_ai_comfort_constant():
|
||||
assert PRESET_AI_COMFORT == 'ai_comfort'
|
||||
assert PRESET_AI_COMFORT == "ai_comfort"
|
||||
|
||||
|
||||
def test_preset_to_ha_off_maps_to_preset_none():
|
||||
from homeassistant.components.climate import PRESET_NONE
|
||||
assert _preset_to_ha('Off') == PRESET_NONE
|
||||
|
||||
assert _preset_to_ha("Off") == PRESET_NONE
|
||||
|
||||
|
||||
def test_preset_to_ha_lowercases_other_codes():
|
||||
"""Every other device code is exposed as its lowercased self -- resolved
|
||||
dynamically, not via a per-model table (issue #91)."""
|
||||
assert _preset_to_ha('Sleep') == 'sleep'
|
||||
assert _preset_to_ha('NanoSleep') == 'nanosleep'
|
||||
assert _preset_to_ha('MotionIndirect') == 'motionindirect'
|
||||
assert _preset_to_ha("Sleep") == "sleep"
|
||||
assert _preset_to_ha("NanoSleep") == "nanosleep"
|
||||
assert _preset_to_ha("MotionIndirect") == "motionindirect"
|
||||
|
||||
|
||||
def test_fac_bora_wind_strength_codes_fit_the_standard_scale():
|
||||
@@ -89,16 +94,19 @@ def test_fac_bora_wind_strength_codes_fit_the_standard_scale():
|
||||
even if fan_modes/fan_mode were completely broken, since it never
|
||||
touches the entity at all.
|
||||
"""
|
||||
from typing import ClassVar, cast
|
||||
|
||||
from custom_components.localthings.climate import LocalThingsClimate
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
from custom_components.localthings.registry import by_type
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.entities import ClimateDesc
|
||||
from tests.conftest import _load_device
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-FAC-BORA-SERIAL'
|
||||
device_info = {}
|
||||
data = {}
|
||||
device_serial = "TEST-FAC-BORA-SERIAL"
|
||||
device_info: ClassVar[dict] = {}
|
||||
data: ClassVar[dict] = {}
|
||||
|
||||
def __init__(self, resources):
|
||||
self.last_resources = resources
|
||||
@@ -111,13 +119,17 @@ def test_fac_bora_wind_strength_codes_fit_the_standard_scale():
|
||||
# canonical view is just the raw snapshot (issue #177).
|
||||
return self.last_resources
|
||||
|
||||
resources = _load_device('airconditioner_fac_bora')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("airconditioner_fac_bora")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = by_type.for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
assert reg is not None
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
climate_bound = next(item for item in bound if isinstance(item.desc, ClimateDesc))
|
||||
entity = LocalThingsClimate(_FakeCoordinator(resources), climate_bound)
|
||||
entity = LocalThingsClimate(
|
||||
cast(LocalThingsCoordinator, _FakeCoordinator(resources)), climate_bound
|
||||
)
|
||||
|
||||
assert entity.fan_modes == ['auto', 'medium', 'high', 'turbo']
|
||||
assert entity.fan_mode == 'auto'
|
||||
assert entity.fan_modes == ["auto", "medium", "high", "turbo"]
|
||||
assert entity.fan_mode == "auto"
|
||||
@@ -9,6 +9,7 @@ master and its materialized sibling, which is exactly the shape climate.py's
|
||||
own comments warn is easy to get wrong if the canonical view leaks between
|
||||
subdevices.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
@@ -17,13 +18,13 @@ from homeassistant.core import HomeAssistant
|
||||
|
||||
from custom_components.localthings.climate import LocalThingsClimate
|
||||
from custom_components.localthings.registry.entities import ClimateDesc
|
||||
|
||||
from tests.test_subdevice_discovery import _coordinator, _discover
|
||||
|
||||
|
||||
def _climate_entities(coordinator):
|
||||
"""{subdevice_key_or_None: LocalThingsClimate}, None standing for MAIN."""
|
||||
from custom_components.localthings.registry.subdevices import MAIN
|
||||
|
||||
out = {}
|
||||
for b in coordinator.bound:
|
||||
if isinstance(b.desc, ClimateDesc):
|
||||
@@ -35,7 +36,7 @@ def _climate_entities(coordinator):
|
||||
@pytest.fixture
|
||||
async def climates(hass: HomeAssistant):
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_dongle_fac_18k')
|
||||
await _discover(coordinator, "airconditioner_artik051_dongle_fac_18k")
|
||||
return _climate_entities(coordinator)
|
||||
|
||||
|
||||
@@ -44,7 +45,7 @@ async def test_subdevice_climate_reads_its_own_mode_and_power(climates):
|
||||
confirmed distinct in the real captured fixture. If the subdevice
|
||||
entity's _rep() weren't translating through its own subdevice, it would
|
||||
read the master's /mode/vs/0 instead and report the master's mode."""
|
||||
main, sub1 = climates[None], climates['1']
|
||||
main, sub1 = climates[None], climates["1"]
|
||||
assert main.hvac_mode == HVACMode.AUTO
|
||||
assert sub1.hvac_mode == HVACMode.COOL
|
||||
|
||||
@@ -53,7 +54,7 @@ async def test_subdevice_climate_reads_its_own_temperature(climates):
|
||||
"""Master: current 25.0 / desired 26.0. Subdevice 1: current 27.0 / desired
|
||||
28.0 -- distinct values in the real fixture, so a href mix-up here
|
||||
would show up as a wrong number, not just a wrong mode string."""
|
||||
main, sub1 = climates[None], climates['1']
|
||||
main, sub1 = climates[None], climates["1"]
|
||||
assert main.current_temperature == 25.0
|
||||
assert main.target_temperature == 26.0
|
||||
assert sub1.current_temperature == 27.0
|
||||
@@ -66,7 +67,7 @@ async def test_subdevice_climate_reads_its_own_power_state(climates):
|
||||
hardcoded /power/vs/0, by checking the entity resolves without falling
|
||||
back to OFF (which _is_on() would do if it silently read an absent
|
||||
href instead of the subdevice's actual one)."""
|
||||
main, sub1 = climates[None], climates['1']
|
||||
main, sub1 = climates[None], climates["1"]
|
||||
assert main.hvac_mode != HVACMode.OFF
|
||||
assert sub1.hvac_mode != HVACMode.OFF
|
||||
|
||||
@@ -82,7 +83,7 @@ async def test_legacy_board_test_is_evaluated_per_subdevice(climates):
|
||||
future board with one legacy + one modern subdevice sharing a
|
||||
connection would silently read the wrong fan/swing channel on one
|
||||
side."""
|
||||
main, sub1 = climates[None], climates['1']
|
||||
main, sub1 = climates[None], climates["1"]
|
||||
assert main._legacy_airflow() != {}
|
||||
assert sub1._legacy_airflow() != {}
|
||||
# Both resolve to *some* fan mode via the legacy path rather than the
|
||||
@@ -99,7 +100,7 @@ async def test_subdevice_climate_writes_are_scoped_to_its_own_bound_entity(clima
|
||||
per-subdevice reads/writes possible at all -- see async_send_command's
|
||||
translation test in test_coordinator_send_command.py for the write
|
||||
side of this."""
|
||||
main, sub1 = climates[None], climates['1']
|
||||
assert main._bound.href == '/mode/vs/0'
|
||||
assert sub1._bound.href == '/mode/vs/1'
|
||||
main, sub1 = climates[None], climates["1"]
|
||||
assert main._bound.href == "/mode/vs/0"
|
||||
assert sub1._bound.href == "/mode/vs/1"
|
||||
assert main._bound is not sub1._bound
|
||||
@@ -10,17 +10,19 @@ don't reach: TP1X-class firmware has no OCF-standard
|
||||
/temperature/current+desired pair, so current_temperature/target_temperature
|
||||
would silently be None without this fallback.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.climate import _temps_vs_item
|
||||
|
||||
|
||||
def test_temps_vs_item_returns_first_item():
|
||||
rep = {
|
||||
'x.com.samsung.da.items': [
|
||||
{'x.com.samsung.da.current': '17.0', 'x.com.samsung.da.desired': '25.0'},
|
||||
"x.com.samsung.da.items": [
|
||||
{"x.com.samsung.da.current": "17.0", "x.com.samsung.da.desired": "25.0"},
|
||||
],
|
||||
}
|
||||
assert _temps_vs_item(rep) == {
|
||||
'x.com.samsung.da.current': '17.0', 'x.com.samsung.da.desired': '25.0',
|
||||
"x.com.samsung.da.current": "17.0",
|
||||
"x.com.samsung.da.desired": "25.0",
|
||||
}
|
||||
|
||||
|
||||
@@ -31,8 +33,8 @@ def test_temps_vs_item_empty_when_items_missing():
|
||||
|
||||
|
||||
def test_temps_vs_item_empty_when_items_is_empty_list():
|
||||
assert _temps_vs_item({'x.com.samsung.da.items': []}) == {}
|
||||
assert _temps_vs_item({"x.com.samsung.da.items": []}) == {}
|
||||
|
||||
|
||||
def test_temps_vs_item_empty_when_items_entry_is_not_a_dict():
|
||||
assert _temps_vs_item({'x.com.samsung.da.items': ['not-a-dict']}) == {}
|
||||
assert _temps_vs_item({"x.com.samsung.da.items": ["not-a-dict"]}) == {}
|
||||
@@ -8,23 +8,24 @@ registry-level "no unbound hrefs" test in test_golden_regression.py doesn't
|
||||
reach: newer WindFree firmware reports no /wind/direction/vs/0 at all, so
|
||||
swing_mode/swing_modes would silently be None/empty without this fallback.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.climate import _oscillation_swing
|
||||
|
||||
|
||||
def test_oscillation_swing_off_when_both_fixed():
|
||||
assert _oscillation_swing({'vertical': 'Fix', 'horizontal': 'Fix'}) == 'off'
|
||||
assert _oscillation_swing({"vertical": "Fix", "horizontal": "Fix"}) == "off"
|
||||
|
||||
|
||||
def test_oscillation_swing_vertical_only():
|
||||
assert _oscillation_swing({'vertical': 'Swing', 'horizontal': 'Fix'}) == 'vertical'
|
||||
assert _oscillation_swing({"vertical": "Swing", "horizontal": "Fix"}) == "vertical"
|
||||
|
||||
|
||||
def test_oscillation_swing_horizontal_only():
|
||||
assert _oscillation_swing({'vertical': 'Fix', 'horizontal': 'Swing'}) == 'horizontal'
|
||||
assert _oscillation_swing({"vertical": "Fix", "horizontal": "Swing"}) == "horizontal"
|
||||
|
||||
|
||||
def test_oscillation_swing_both():
|
||||
assert _oscillation_swing({'vertical': 'Swing', 'horizontal': 'Swing'}) == 'both'
|
||||
assert _oscillation_swing({"vertical": "Swing", "horizontal": "Swing"}) == "both"
|
||||
|
||||
|
||||
def test_oscillation_swing_none_when_resource_absent():
|
||||
|
||||
@@ -10,15 +10,16 @@ table with a generic resolver that covers WindFree/motion generically
|
||||
instead of a per-model dict -- duplicating that here would just conflict
|
||||
with it.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.climate import _DEVICE_TO_SWING, _SWING_TO_DEVICE
|
||||
|
||||
|
||||
def test_horizontal_swing_maps_both_directions():
|
||||
assert _DEVICE_TO_SWING['Left_And_Right'] == 'horizontal'
|
||||
assert _SWING_TO_DEVICE['horizontal'] == 'Left_And_Right'
|
||||
assert _DEVICE_TO_SWING["Left_And_Right"] == "horizontal"
|
||||
assert _SWING_TO_DEVICE["horizontal"] == "Left_And_Right"
|
||||
|
||||
|
||||
def test_existing_swing_modes_unchanged():
|
||||
assert _DEVICE_TO_SWING['Fix'] == 'off'
|
||||
assert _DEVICE_TO_SWING['All'] == 'both'
|
||||
assert _DEVICE_TO_SWING['Up_And_Low'] == 'vertical'
|
||||
assert _DEVICE_TO_SWING["Fix"] == "off"
|
||||
assert _DEVICE_TO_SWING["All"] == "both"
|
||||
assert _DEVICE_TO_SWING["Up_And_Low"] == "vertical"
|
||||
+232
-177
@@ -5,13 +5,21 @@ from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _reg():
|
||||
return {c.href: [c] for c in (
|
||||
common.KIDS_LOCK_GENERIC, common.KIDS_LOCK_VS_FALLBACK,
|
||||
common.REMOTE_CONTROL_GENERIC, common.REMOTE_CONTROL_VS_FALLBACK,
|
||||
common.POWER_GENERIC, common.POWER_VS_FALLBACK,
|
||||
common.ALARMS, common.ENERGY_METER, common.WATER_METER,
|
||||
common.WATER_FILTER,
|
||||
)}
|
||||
return {
|
||||
c.href: [c]
|
||||
for c in (
|
||||
common.KIDS_LOCK_GENERIC,
|
||||
common.KIDS_LOCK_VS_FALLBACK,
|
||||
common.REMOTE_CONTROL_GENERIC,
|
||||
common.REMOTE_CONTROL_VS_FALLBACK,
|
||||
common.POWER_GENERIC,
|
||||
common.POWER_VS_FALLBACK,
|
||||
common.ALARMS,
|
||||
common.ENERGY_METER,
|
||||
common.WATER_METER,
|
||||
common.WATER_FILTER,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def test_kids_lock_vs_value_fn():
|
||||
@@ -20,16 +28,16 @@ def test_kids_lock_vs_value_fn():
|
||||
TestKidsLockFallback.test_vs_fallback_is_read_only for why this is a
|
||||
binary_sensor at all)."""
|
||||
desc = common.KIDS_LOCK_VS_FALLBACK.entities[0]
|
||||
assert desc.value_fn('Lock') is False
|
||||
assert desc.value_fn('Ready') is True
|
||||
assert desc.value_fn("Lock") is False
|
||||
assert desc.value_fn("Ready") is True
|
||||
|
||||
|
||||
def test_common_caps_discover_on_dishwasher(dishwasher_resources):
|
||||
bound = discover(dishwasher_resources, _reg())
|
||||
keys = {b.desc.key for b in bound}
|
||||
assert 'child_lock' in keys
|
||||
assert 'remote_control' in keys
|
||||
assert 'power_switch' in keys
|
||||
assert "child_lock" in keys
|
||||
assert "remote_control" in keys
|
||||
assert "power_switch" in keys
|
||||
|
||||
|
||||
class TestMergeOptionsField:
|
||||
@@ -39,28 +47,31 @@ class TestMergeOptionsField:
|
||||
still present) without waiting on a real poll."""
|
||||
|
||||
def test_replaces_matching_prefix(self):
|
||||
cached = ['DeviceType_0167', 'Course_16', 'GMT_04']
|
||||
assert common.merge_options_field(cached, ['Course_1D']) == [
|
||||
'DeviceType_0167', 'Course_1D', 'GMT_04',
|
||||
cached = ["DeviceType_0167", "Course_16", "GMT_04"]
|
||||
assert common.merge_options_field(cached, ["Course_1D"]) == [
|
||||
"DeviceType_0167",
|
||||
"Course_1D",
|
||||
"GMT_04",
|
||||
]
|
||||
|
||||
def test_appends_when_prefix_absent(self):
|
||||
cached = ['DeviceType_0167']
|
||||
assert common.merge_options_field(cached, ['NaturalSteam_On']) == [
|
||||
'DeviceType_0167', 'NaturalSteam_On',
|
||||
cached = ["DeviceType_0167"]
|
||||
assert common.merge_options_field(cached, ["NaturalSteam_On"]) == [
|
||||
"DeviceType_0167",
|
||||
"NaturalSteam_On",
|
||||
]
|
||||
|
||||
def test_merges_multiple_tokens_independently(self):
|
||||
cached = ['DetergentLevelCtrl_1', 'SoftenerLevelCtrl_0', 'GMT_04']
|
||||
merged = common.merge_options_field(cached, ['SoftenerLevelCtrl_2'])
|
||||
assert merged == ['DetergentLevelCtrl_1', 'SoftenerLevelCtrl_2', 'GMT_04']
|
||||
cached = ["DetergentLevelCtrl_1", "SoftenerLevelCtrl_0", "GMT_04"]
|
||||
merged = common.merge_options_field(cached, ["SoftenerLevelCtrl_2"])
|
||||
assert merged == ["DetergentLevelCtrl_1", "SoftenerLevelCtrl_2", "GMT_04"]
|
||||
|
||||
def test_handles_missing_cache(self):
|
||||
assert common.merge_options_field(None, ['Course_1D']) == ['Course_1D']
|
||||
assert common.merge_options_field(None, ["Course_1D"]) == ["Course_1D"]
|
||||
|
||||
def test_ignores_malformed_tokens(self):
|
||||
cached = ['Course_16']
|
||||
assert common.merge_options_field(cached, ['nounderscore']) == ['Course_16']
|
||||
cached = ["Course_16"]
|
||||
assert common.merge_options_field(cached, ["nounderscore"]) == ["Course_16"]
|
||||
|
||||
|
||||
class TestMergeItemsField:
|
||||
@@ -72,31 +83,45 @@ class TestMergeItemsField:
|
||||
present) without waiting on a real poll."""
|
||||
|
||||
def test_merges_fields_into_matching_id(self):
|
||||
cached = [{'x.com.samsung.da.id': '0', 'x.com.samsung.da.current': '20.0',
|
||||
'x.com.samsung.da.maximum': '30', 'x.com.samsung.da.minimum': '16'}]
|
||||
cached = [
|
||||
{
|
||||
"x.com.samsung.da.id": "0",
|
||||
"x.com.samsung.da.current": "20.0",
|
||||
"x.com.samsung.da.maximum": "30",
|
||||
"x.com.samsung.da.minimum": "16",
|
||||
}
|
||||
]
|
||||
merged = common.merge_items_field(
|
||||
cached, [{'x.com.samsung.da.id': '0', 'x.com.samsung.da.desired': '22'}])
|
||||
assert merged == [{'x.com.samsung.da.id': '0', 'x.com.samsung.da.current': '20.0',
|
||||
'x.com.samsung.da.maximum': '30', 'x.com.samsung.da.minimum': '16',
|
||||
'x.com.samsung.da.desired': '22'}]
|
||||
cached, [{"x.com.samsung.da.id": "0", "x.com.samsung.da.desired": "22"}]
|
||||
)
|
||||
assert merged == [
|
||||
{
|
||||
"x.com.samsung.da.id": "0",
|
||||
"x.com.samsung.da.current": "20.0",
|
||||
"x.com.samsung.da.maximum": "30",
|
||||
"x.com.samsung.da.minimum": "16",
|
||||
"x.com.samsung.da.desired": "22",
|
||||
}
|
||||
]
|
||||
|
||||
def test_appends_when_id_absent(self):
|
||||
cached = [{'x.com.samsung.da.id': '0', 'x.com.samsung.da.current': '20.0'}]
|
||||
cached = [{"x.com.samsung.da.id": "0", "x.com.samsung.da.current": "20.0"}]
|
||||
merged = common.merge_items_field(
|
||||
cached, [{'x.com.samsung.da.id': '1', 'x.com.samsung.da.desired': '22'}])
|
||||
cached, [{"x.com.samsung.da.id": "1", "x.com.samsung.da.desired": "22"}]
|
||||
)
|
||||
assert merged == [
|
||||
{'x.com.samsung.da.id': '0', 'x.com.samsung.da.current': '20.0'},
|
||||
{'x.com.samsung.da.id': '1', 'x.com.samsung.da.desired': '22'},
|
||||
{"x.com.samsung.da.id": "0", "x.com.samsung.da.current": "20.0"},
|
||||
{"x.com.samsung.da.id": "1", "x.com.samsung.da.desired": "22"},
|
||||
]
|
||||
|
||||
def test_handles_missing_cache(self):
|
||||
assert common.merge_items_field(
|
||||
None, [{'x.com.samsung.da.id': '0', 'x.com.samsung.da.desired': '22'}]
|
||||
) == [{'x.com.samsung.da.id': '0', 'x.com.samsung.da.desired': '22'}]
|
||||
None, [{"x.com.samsung.da.id": "0", "x.com.samsung.da.desired": "22"}]
|
||||
) == [{"x.com.samsung.da.id": "0", "x.com.samsung.da.desired": "22"}]
|
||||
|
||||
def test_ignores_malformed_new_items(self):
|
||||
cached = [{'x.com.samsung.da.id': '0', 'x.com.samsung.da.current': '20.0'}]
|
||||
assert common.merge_items_field(cached, ['not-a-dict']) == cached
|
||||
cached = [{"x.com.samsung.da.id": "0", "x.com.samsung.da.current": "20.0"}]
|
||||
assert common.merge_items_field(cached, ["not-a-dict"]) == cached
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -106,95 +131,104 @@ class TestMergeItemsField:
|
||||
|
||||
class TestPowerFallback:
|
||||
def test_generic_href_read_write(self):
|
||||
assert common.POWER_GENERIC.href == '/power/0'
|
||||
assert common.POWER_GENERIC.href == "/power/0"
|
||||
desc = next(e for e in common.POWER_GENERIC.entities if isinstance(e, SwitchDesc))
|
||||
assert desc.value_fn(True) is True
|
||||
assert desc.value_fn(False) is False
|
||||
path, body = desc.write_fn('On', {})
|
||||
assert path == ['power', '0']
|
||||
assert body == {'value': True}
|
||||
assert desc.write_fn('Off', {})[1] == {'value': False}
|
||||
path, body = desc.write_fn("On", {})
|
||||
assert path == ["power", "0"]
|
||||
assert body == {"value": True}
|
||||
assert desc.write_fn("Off", {})[1] == {"value": False}
|
||||
|
||||
def test_vs_fallback_binds_only_when_generic_absent(self):
|
||||
assert common.POWER_VS_FALLBACK.href == '/power/vs/0'
|
||||
assert common.POWER_VS_FALLBACK.match_fn({}, {'/power/vs/0': {}}) is True
|
||||
assert common.POWER_VS_FALLBACK.match_fn(
|
||||
{}, {'/power/0': {}, '/power/vs/0': {}}) is False
|
||||
assert common.POWER_VS_FALLBACK.href == "/power/vs/0"
|
||||
assert common.POWER_VS_FALLBACK.match_fn({}, {"/power/vs/0": {}}) is True
|
||||
assert common.POWER_VS_FALLBACK.match_fn({}, {"/power/0": {}, "/power/vs/0": {}}) is False
|
||||
|
||||
def test_vs_fallback_read_write(self):
|
||||
desc = next(e for e in common.POWER_VS_FALLBACK.entities if isinstance(e, SwitchDesc))
|
||||
assert desc.value_fn('On') is True
|
||||
assert desc.value_fn('Off') is False
|
||||
path, body = desc.write_fn('On', {})
|
||||
assert path == ['power', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.power': 'On'}
|
||||
assert desc.value_fn("On") is True
|
||||
assert desc.value_fn("Off") is False
|
||||
path, body = desc.write_fn("On", {})
|
||||
assert path == ["power", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.power": "On"}
|
||||
|
||||
def test_power_switch_hidden_when_firmware_disallows(self):
|
||||
switch = next(e for e in common.POWER_GENERIC.entities if isinstance(e, SwitchDesc))
|
||||
sensor = next(e for e in common.POWER_GENERIC.entities if isinstance(e, BinarySensorDesc))
|
||||
resources = {
|
||||
'/power/0': {'value': True},
|
||||
'/wm/setinfo/vs/0': {'x.com.samsung.da.isModelSettingPowerOnOff': 'false'},
|
||||
"/power/0": {"value": True},
|
||||
"/wm/setinfo/vs/0": {"x.com.samsung.da.isModelSettingPowerOnOff": "false"},
|
||||
}
|
||||
assert switch.exists_fn(resources['/power/0'], resources) is False
|
||||
assert sensor.exists_fn(resources['/power/0'], resources) is True
|
||||
assert switch.exists_fn(resources["/power/0"], resources) is False
|
||||
assert sensor.exists_fn(resources["/power/0"], resources) is True
|
||||
|
||||
def test_power_switch_writable_when_firmware_allows(self):
|
||||
switch = next(e for e in common.POWER_GENERIC.entities if isinstance(e, SwitchDesc))
|
||||
sensor = next(e for e in common.POWER_GENERIC.entities if isinstance(e, BinarySensorDesc))
|
||||
resources = {
|
||||
'/power/0': {'value': True},
|
||||
'/wm/setinfo/vs/0': {'x.com.samsung.da.isModelSettingPowerOnOff': 'true'},
|
||||
"/power/0": {"value": True},
|
||||
"/wm/setinfo/vs/0": {"x.com.samsung.da.isModelSettingPowerOnOff": "true"},
|
||||
}
|
||||
assert switch.exists_fn(resources['/power/0'], resources) is True
|
||||
assert sensor.exists_fn(resources['/power/0'], resources) is False
|
||||
assert switch.exists_fn(resources["/power/0"], resources) is True
|
||||
assert sensor.exists_fn(resources["/power/0"], resources) is False
|
||||
|
||||
def test_power_switch_default_writable_without_setinfo(self):
|
||||
switch = next(e for e in common.POWER_GENERIC.entities if isinstance(e, SwitchDesc))
|
||||
sensor = next(e for e in common.POWER_GENERIC.entities if isinstance(e, BinarySensorDesc))
|
||||
resources = {'/power/0': {'value': True}}
|
||||
assert switch.exists_fn(resources['/power/0'], resources) is True
|
||||
assert sensor.exists_fn(resources['/power/0'], resources) is False
|
||||
resources = {"/power/0": {"value": True}}
|
||||
assert switch.exists_fn(resources["/power/0"], resources) is True
|
||||
assert sensor.exists_fn(resources["/power/0"], resources) is False
|
||||
|
||||
def test_polled_warm_so_power_state_reflects_quickly(self):
|
||||
"""issue #56 follow-up: neither href had a poll_tier, so power state
|
||||
only ever refreshed on the once-per-30s summary poll instead of the
|
||||
subscribe/subpoll cadence 'warm'/'hot' hrefs get -- same reasoning
|
||||
as REMOTE_CONTROL_GENERIC/VS_FALLBACK's own 'warm' tier."""
|
||||
assert common.POWER_GENERIC.poll_tier == 'warm'
|
||||
assert common.POWER_VS_FALLBACK.poll_tier == 'warm'
|
||||
assert common.POWER_GENERIC.poll_tier == "warm"
|
||||
assert common.POWER_VS_FALLBACK.poll_tier == "warm"
|
||||
|
||||
|
||||
class TestWmSetinfoFlags:
|
||||
def test_washer_fixture_carries_setinfo_from_device0(self):
|
||||
"""/wm/setinfo/vs/0 lands in the seed snapshot -- no dedicated capability."""
|
||||
resources = _load_device('washer')
|
||||
assert '/wm/setinfo/vs/0' in resources
|
||||
resources = _load_device("washer")
|
||||
assert "/wm/setinfo/vs/0" in resources
|
||||
assert common.model_allows_power_on_off(resources) is False
|
||||
assert common.model_setting_without_sc(resources) is True
|
||||
|
||||
def test_dishwasher_allows_power_on_off(self):
|
||||
resources = _load_device('dishwasher')
|
||||
resources = _load_device("dishwasher")
|
||||
assert common.model_allows_power_on_off(resources) is True
|
||||
assert common.model_setting_without_sc(resources) is False
|
||||
|
||||
def test_deleted_alarms_filtered(self):
|
||||
assert common._active_alarm_codes([
|
||||
{
|
||||
'x.com.samsung.da.code': 'ErrorCode',
|
||||
'x.com.samsung.da.state': 'Deleted',
|
||||
},
|
||||
]) == 'none'
|
||||
assert common._active_alarm_codes([
|
||||
{
|
||||
'x.com.samsung.da.code': 'LE',
|
||||
'x.com.samsung.da.state': 'Triggered',
|
||||
},
|
||||
{
|
||||
'x.com.samsung.da.code': 'ErrorCode',
|
||||
'x.com.samsung.da.state': 'Deleted',
|
||||
},
|
||||
]) == 'LE'
|
||||
assert (
|
||||
common._active_alarm_codes(
|
||||
[
|
||||
{
|
||||
"x.com.samsung.da.code": "ErrorCode",
|
||||
"x.com.samsung.da.state": "Deleted",
|
||||
},
|
||||
]
|
||||
)
|
||||
== "none"
|
||||
)
|
||||
assert (
|
||||
common._active_alarm_codes(
|
||||
[
|
||||
{
|
||||
"x.com.samsung.da.code": "LE",
|
||||
"x.com.samsung.da.state": "Triggered",
|
||||
},
|
||||
{
|
||||
"x.com.samsung.da.code": "ErrorCode",
|
||||
"x.com.samsung.da.state": "Deleted",
|
||||
},
|
||||
]
|
||||
)
|
||||
== "LE"
|
||||
)
|
||||
|
||||
def test_off_suffixed_placeholder_codes_filtered(self):
|
||||
"""issue #166: Samsung pre-populates /alarms/vs/0 with one row per
|
||||
@@ -203,32 +237,42 @@ class TestWmSetinfoFlags:
|
||||
confirmed not just for 'ErrorCode_OFF' but also 'FilterAlarm_OFF'
|
||||
on the same dump. These were previously shown as if they were
|
||||
active alarms."""
|
||||
assert common._active_alarm_codes([
|
||||
{
|
||||
'x.com.samsung.da.code': 'ErrorCode_OFF',
|
||||
'x.com.samsung.da.triggeredTime': '2026-07-28T12:59:22',
|
||||
},
|
||||
{
|
||||
'x.com.samsung.da.code': 'FilterAlarm_OFF',
|
||||
'x.com.samsung.da.triggeredTime': '2026-07-28T12:59:22',
|
||||
},
|
||||
]) == 'none'
|
||||
assert (
|
||||
common._active_alarm_codes(
|
||||
[
|
||||
{
|
||||
"x.com.samsung.da.code": "ErrorCode_OFF",
|
||||
"x.com.samsung.da.triggeredTime": "2026-07-28T12:59:22",
|
||||
},
|
||||
{
|
||||
"x.com.samsung.da.code": "FilterAlarm_OFF",
|
||||
"x.com.samsung.da.triggeredTime": "2026-07-28T12:59:22",
|
||||
},
|
||||
]
|
||||
)
|
||||
== "none"
|
||||
)
|
||||
|
||||
def test_real_filter_alarm_not_off_suffixed_still_shown(self):
|
||||
"""issue #166's actual live filter alert: code 'FilterAlarm' (no
|
||||
'_OFF' suffix), state 'Created' -- distinct from the 'FilterAlarm_OFF'
|
||||
placeholder and must still surface."""
|
||||
assert common._active_alarm_codes([
|
||||
{
|
||||
'x.com.samsung.da.code': 'ErrorCode_OFF',
|
||||
'x.com.samsung.da.triggeredTime': '2026-07-28T12:59:22',
|
||||
},
|
||||
{
|
||||
'x.com.samsung.da.code': 'FilterAlarm',
|
||||
'x.com.samsung.da.state': 'Created',
|
||||
'x.com.samsung.da.triggeredTime': '2026-07-28T12:59:22',
|
||||
},
|
||||
]) == 'FilterAlarm'
|
||||
assert (
|
||||
common._active_alarm_codes(
|
||||
[
|
||||
{
|
||||
"x.com.samsung.da.code": "ErrorCode_OFF",
|
||||
"x.com.samsung.da.triggeredTime": "2026-07-28T12:59:22",
|
||||
},
|
||||
{
|
||||
"x.com.samsung.da.code": "FilterAlarm",
|
||||
"x.com.samsung.da.state": "Created",
|
||||
"x.com.samsung.da.triggeredTime": "2026-07-28T12:59:22",
|
||||
},
|
||||
]
|
||||
)
|
||||
== "FilterAlarm"
|
||||
)
|
||||
|
||||
|
||||
class TestKidsLockFallback:
|
||||
@@ -240,16 +284,18 @@ class TestKidsLockFallback:
|
||||
KIDS_LOCK_VS_FALLBACK now share the same shape (BinarySensorDesc,
|
||||
device_class='lock', same key) so both surfaces render with the
|
||||
same polarity: 'On' means open/unlocked."""
|
||||
assert common.KIDS_LOCK_GENERIC.href == '/kidslock/0'
|
||||
assert common.KIDS_LOCK_GENERIC.href == "/kidslock/0"
|
||||
desc = common.KIDS_LOCK_GENERIC.entities[0]
|
||||
assert isinstance(desc, BinarySensorDesc)
|
||||
assert desc.value_fn(False) is True # value=False -> On=Unlocked
|
||||
assert desc.value_fn(True) is False # value=True -> Off=Locked
|
||||
assert desc.value_fn(False) is True # value=False -> On=Unlocked
|
||||
assert desc.value_fn(True) is False # value=True -> Off=Locked
|
||||
|
||||
def test_vs_fallback_gated(self):
|
||||
assert common.KIDS_LOCK_VS_FALLBACK.match_fn({}, {'/kidslock/vs/0': {}}) is True
|
||||
assert common.KIDS_LOCK_VS_FALLBACK.match_fn(
|
||||
{}, {'/kidslock/0': {}, '/kidslock/vs/0': {}}) is False
|
||||
assert common.KIDS_LOCK_VS_FALLBACK.match_fn({}, {"/kidslock/vs/0": {}}) is True
|
||||
assert (
|
||||
common.KIDS_LOCK_VS_FALLBACK.match_fn({}, {"/kidslock/0": {}, "/kidslock/vs/0": {}})
|
||||
is False
|
||||
)
|
||||
|
||||
def test_vs_fallback_is_read_only(self):
|
||||
"""Issues #181/#183: writing this resource 4.05s on real hardware
|
||||
@@ -264,23 +310,27 @@ class TestKidsLockFallback:
|
||||
|
||||
class TestRemoteControlFallback:
|
||||
def test_generic_read(self):
|
||||
assert common.REMOTE_CONTROL_GENERIC.href == '/remotectrl/0'
|
||||
assert common.REMOTE_CONTROL_GENERIC.href == "/remotectrl/0"
|
||||
desc = common.REMOTE_CONTROL_GENERIC.entities[0]
|
||||
assert desc.value_fn(True) is True
|
||||
assert desc.value_fn(False) is False
|
||||
|
||||
def test_vs_fallback_gated(self):
|
||||
assert common.REMOTE_CONTROL_VS_FALLBACK.match_fn({}, {'/remotectrl/vs/0': {}}) is True
|
||||
assert common.REMOTE_CONTROL_VS_FALLBACK.match_fn(
|
||||
{}, {'/remotectrl/0': {}, '/remotectrl/vs/0': {}}) is False
|
||||
assert common.REMOTE_CONTROL_VS_FALLBACK.match_fn({}, {"/remotectrl/vs/0": {}}) is True
|
||||
assert (
|
||||
common.REMOTE_CONTROL_VS_FALLBACK.match_fn(
|
||||
{}, {"/remotectrl/0": {}, "/remotectrl/vs/0": {}}
|
||||
)
|
||||
is False
|
||||
)
|
||||
|
||||
def test_polled_warm_so_write_gating_stays_fresh(self):
|
||||
"""coordinator.async_send_command blocks writes on this signal, so
|
||||
it can't sit in the default 'cold' tier (refreshed only once per
|
||||
30s summary poll) -- it needs the subscribe/subpoll cadence 'warm'
|
||||
and 'hot' hrefs get instead."""
|
||||
assert common.REMOTE_CONTROL_GENERIC.poll_tier == 'warm'
|
||||
assert common.REMOTE_CONTROL_VS_FALLBACK.poll_tier == 'warm'
|
||||
assert common.REMOTE_CONTROL_GENERIC.poll_tier == "warm"
|
||||
assert common.REMOTE_CONTROL_VS_FALLBACK.poll_tier == "warm"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -292,36 +342,36 @@ class TestRemoteControlFallback:
|
||||
|
||||
class TestEnergyMeter:
|
||||
def test_href(self):
|
||||
assert common.ENERGY_METER.href == '/energy/consumption/vs/0'
|
||||
assert common.ENERGY_METER.href == "/energy/consumption/vs/0"
|
||||
|
||||
def test_power_clamps_negative(self):
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == 'power_watts')
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == "power_watts")
|
||||
assert pw.value_fn(-500.0) == 0.0
|
||||
assert pw.value_fn(93.0) == 93.0
|
||||
|
||||
def test_power_watts_hidden_for_dead_sentinel(self):
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == 'power_watts')
|
||||
assert pw.exists_fn({'x.com.samsung.da.instantaneousPower': '-500'}, {}) is False
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == "power_watts")
|
||||
assert pw.exists_fn({"x.com.samsung.da.instantaneousPower": "-500"}, {}) is False
|
||||
|
||||
def test_power_watts_shown_for_real_value(self):
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == 'power_watts')
|
||||
assert pw.exists_fn({'x.com.samsung.da.instantaneousPower': '150'}, {}) is True
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == "power_watts")
|
||||
assert pw.exists_fn({"x.com.samsung.da.instantaneousPower": "150"}, {}) is True
|
||||
|
||||
def test_energy_kwh_hidden_when_cumulative_power_absent(self):
|
||||
kwh = next(e for e in common.ENERGY_METER.entities if e.key == 'energy_kwh')
|
||||
assert kwh.exists_fn({'x.com.samsung.da.instantaneousPower': '-500'}, {}) is False
|
||||
kwh = next(e for e in common.ENERGY_METER.entities if e.key == "energy_kwh")
|
||||
assert kwh.exists_fn({"x.com.samsung.da.instantaneousPower": "-500"}, {}) is False
|
||||
|
||||
def test_energy_kwh_shown_when_present(self):
|
||||
kwh = next(e for e in common.ENERGY_METER.entities if e.key == 'energy_kwh')
|
||||
assert kwh.exists_fn({'x.com.samsung.da.cumulativePower': '58900'}, {}) is True
|
||||
kwh = next(e for e in common.ENERGY_METER.entities if e.key == "energy_kwh")
|
||||
assert kwh.exists_fn({"x.com.samsung.da.cumulativePower": "58900"}, {}) is True
|
||||
|
||||
def test_both_entities_included_on_true_stub(self):
|
||||
"""A true stub -- /device/0's {"href": "..."} "not fetched yet"
|
||||
marker (see registry.batch.is_stub_rep) -- means the resource exists
|
||||
but data isn't fetched yet; include both so sub-polls populate them."""
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == 'power_watts')
|
||||
kwh = next(e for e in common.ENERGY_METER.entities if e.key == 'energy_kwh')
|
||||
stub = {'href': '/energy/consumption/vs/0'}
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == "power_watts")
|
||||
kwh = next(e for e in common.ENERGY_METER.entities if e.key == "energy_kwh")
|
||||
stub = {"href": "/energy/consumption/vs/0"}
|
||||
assert pw.exists_fn(stub, {}) is True
|
||||
assert kwh.exists_fn(stub, {}) is True
|
||||
|
||||
@@ -329,16 +379,16 @@ class TestEnergyMeter:
|
||||
"""A real {} rep (no 'href' key) is the device's confirmed -- if
|
||||
empty -- answer, not a stub, so a model that never populates this
|
||||
resource doesn't get a phantom always-"unknown" entity (issue #127)."""
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == 'power_watts')
|
||||
kwh = next(e for e in common.ENERGY_METER.entities if e.key == 'energy_kwh')
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == "power_watts")
|
||||
kwh = next(e for e in common.ENERGY_METER.entities if e.key == "energy_kwh")
|
||||
assert pw.exists_fn({}, {}) is False
|
||||
assert kwh.exists_fn({}, {}) is False
|
||||
|
||||
def test_power_watts_hidden_when_field_absent_in_populated_rep(self):
|
||||
"""A populated rep that lacks instantaneousPower must not spawn a
|
||||
phantom power sensor (the exists_fn replaces the field-presence gate)."""
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == 'power_watts')
|
||||
assert pw.exists_fn({'x.com.samsung.da.cumulativePower': '5'}, {}) is False
|
||||
pw = next(e for e in common.ENERGY_METER.entities if e.key == "power_watts")
|
||||
assert pw.exists_fn({"x.com.samsung.da.cumulativePower": "5"}, {}) is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -352,36 +402,35 @@ class TestEnergyMeter:
|
||||
|
||||
|
||||
def _ai_energy_level_desc(cls_name):
|
||||
return next(e for e in common.AI_ENERGY_LEVEL.entities
|
||||
if e.__class__.__name__ == cls_name)
|
||||
return next(e for e in common.AI_ENERGY_LEVEL.entities if e.__class__.__name__ == cls_name)
|
||||
|
||||
|
||||
class TestAiEnergyLevelSwitch:
|
||||
def _desc(self):
|
||||
return _ai_energy_level_desc('SwitchDesc')
|
||||
return _ai_energy_level_desc("SwitchDesc")
|
||||
|
||||
def test_href(self):
|
||||
assert common.AI_ENERGY_LEVEL.href == '/energy/ailevel/vs/0'
|
||||
assert common.AI_ENERGY_LEVEL.href == "/energy/ailevel/vs/0"
|
||||
|
||||
def test_shown_only_with_single_supported_level(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'aiLevel': '1', 'supportedAiLevel': ['1']}, {}) is True
|
||||
assert desc.exists_fn({'aiLevel': '1', 'supportedAiLevel': ['1', '2']}, {}) is False
|
||||
assert desc.exists_fn({"aiLevel": "1", "supportedAiLevel": ["1"]}, {}) is True
|
||||
assert desc.exists_fn({"aiLevel": "1", "supportedAiLevel": ["1", "2"]}, {}) is False
|
||||
|
||||
def test_hidden_when_supported_level_is_non_list_scalar(self):
|
||||
"""A stray scalar (e.g. a string) must not be len()-checked as if it
|
||||
were a list -- a 2-char string would otherwise wrongly pass `== 1`
|
||||
style checks."""
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'aiLevel': '1', 'supportedAiLevel': '1'}, {}) is False
|
||||
assert desc.exists_fn({"aiLevel": "1", "supportedAiLevel": "1"}, {}) is False
|
||||
|
||||
def test_hidden_when_supported_level_missing(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'aiLevel': '1'}, {}) is False
|
||||
assert desc.exists_fn({"aiLevel": "1"}, {}) is False
|
||||
|
||||
def test_hidden_when_supported_level_empty_list(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'aiLevel': '0', 'supportedAiLevel': []}, {}) is False
|
||||
assert desc.exists_fn({"aiLevel": "0", "supportedAiLevel": []}, {}) is False
|
||||
|
||||
def test_hidden_on_empty_stub_rep(self):
|
||||
desc = self._desc()
|
||||
@@ -389,43 +438,43 @@ class TestAiEnergyLevelSwitch:
|
||||
|
||||
def test_value_fn(self):
|
||||
desc = self._desc()
|
||||
assert desc.value_fn('0') is False
|
||||
assert desc.value_fn('1') is True
|
||||
assert desc.value_fn("0") is False
|
||||
assert desc.value_fn("1") is True
|
||||
|
||||
def test_write_on_uses_the_single_supported_level(self):
|
||||
"""The on-value is whatever the device calls its one level, not a
|
||||
hardcoded '1'."""
|
||||
desc = self._desc()
|
||||
path, body = desc.write_fn('On', {'supportedAiLevel': ['2']})
|
||||
assert path == ['energy', 'ailevel', 'vs', '0']
|
||||
assert body == {'aiLevel': '2'}
|
||||
path, body = desc.write_fn("On", {"supportedAiLevel": ["2"]})
|
||||
assert path == ["energy", "ailevel", "vs", "0"]
|
||||
assert body == {"aiLevel": "2"}
|
||||
|
||||
def test_write_off(self):
|
||||
desc = self._desc()
|
||||
path, body = desc.write_fn('Off', {'supportedAiLevel': ['1']})
|
||||
assert body == {'aiLevel': '0'}
|
||||
_path, body = desc.write_fn("Off", {"supportedAiLevel": ["1"]})
|
||||
assert body == {"aiLevel": "0"}
|
||||
|
||||
|
||||
class TestAiEnergyLevelSelect:
|
||||
def _desc(self):
|
||||
return _ai_energy_level_desc('SelectDesc')
|
||||
return _ai_energy_level_desc("SelectDesc")
|
||||
|
||||
def test_shown_only_with_multiple_supported_levels(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'aiLevel': '1', 'supportedAiLevel': ['1', '2']}, {}) is True
|
||||
assert desc.exists_fn({'aiLevel': '1', 'supportedAiLevel': ['1']}, {}) is False
|
||||
assert desc.exists_fn({"aiLevel": "1", "supportedAiLevel": ["1", "2"]}, {}) is True
|
||||
assert desc.exists_fn({"aiLevel": "1", "supportedAiLevel": ["1"]}, {}) is False
|
||||
|
||||
def test_hidden_when_supported_level_is_non_list_scalar(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'aiLevel': '1', 'supportedAiLevel': '12'}, {}) is False
|
||||
assert desc.exists_fn({"aiLevel": "1", "supportedAiLevel": "12"}, {}) is False
|
||||
|
||||
def test_hidden_when_supported_level_missing(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'aiLevel': '1'}, {}) is False
|
||||
assert desc.exists_fn({"aiLevel": "1"}, {}) is False
|
||||
|
||||
def test_hidden_when_supported_level_empty_list(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'aiLevel': '0', 'supportedAiLevel': []}, {}) is False
|
||||
assert desc.exists_fn({"aiLevel": "0", "supportedAiLevel": []}, {}) is False
|
||||
|
||||
def test_no_translation_key(self):
|
||||
"""aiLevel's values are plain digits that render fine untranslated
|
||||
@@ -438,18 +487,18 @@ class TestAiEnergyLevelSelect:
|
||||
"""'0' is never in supportedAiLevel but is a real, observed aiLevel
|
||||
value -- synthesized back in as the explicit off option."""
|
||||
desc = self._desc()
|
||||
resources = {'/energy/ailevel/vs/0': {'supportedAiLevel': ['1', '2']}}
|
||||
assert desc.options(resources) == ['0', '1', '2']
|
||||
resources = {"/energy/ailevel/vs/0": {"supportedAiLevel": ["1", "2"]}}
|
||||
assert desc.options(resources) == ["0", "1", "2"]
|
||||
|
||||
def test_options_empty_when_resource_missing(self):
|
||||
desc = self._desc()
|
||||
assert desc.options({}) == ['0']
|
||||
assert desc.options({}) == ["0"]
|
||||
|
||||
def test_write(self):
|
||||
desc = self._desc()
|
||||
path, body = desc.write_fn('2', {})
|
||||
assert path == ['energy', 'ailevel', 'vs', '0']
|
||||
assert body == {'aiLevel': '2'}
|
||||
path, body = desc.write_fn("2", {})
|
||||
assert path == ["energy", "ailevel", "vs", "0"]
|
||||
assert body == {"aiLevel": "2"}
|
||||
|
||||
|
||||
class TestAiEnergyLevelStubDoesNotDecideThePlatform:
|
||||
@@ -468,15 +517,15 @@ class TestAiEnergyLevelStubDoesNotDecideThePlatform:
|
||||
on first-poll timing, instead of appearing as the wrong widget type."""
|
||||
|
||||
def test_neither_widget_exists_on_true_stub_rep(self):
|
||||
switch = _ai_energy_level_desc('SwitchDesc')
|
||||
select = _ai_energy_level_desc('SelectDesc')
|
||||
stub = {'href': '/energy/ailevel/vs/0'}
|
||||
switch = _ai_energy_level_desc("SwitchDesc")
|
||||
select = _ai_energy_level_desc("SelectDesc")
|
||||
stub = {"href": "/energy/ailevel/vs/0"}
|
||||
assert switch.exists_fn(stub, {}) is False
|
||||
assert select.exists_fn(stub, {}) is False
|
||||
|
||||
def test_neither_widget_exists_on_genuinely_empty_rep(self):
|
||||
switch = _ai_energy_level_desc('SwitchDesc')
|
||||
select = _ai_energy_level_desc('SelectDesc')
|
||||
switch = _ai_energy_level_desc("SwitchDesc")
|
||||
select = _ai_energy_level_desc("SelectDesc")
|
||||
assert switch.exists_fn({}, {}) is False
|
||||
assert select.exists_fn({}, {}) is False
|
||||
|
||||
@@ -486,21 +535,21 @@ class TestSelfCheckError:
|
||||
x.com.samsung.da.error, joined into a single display string."""
|
||||
|
||||
def _desc(self):
|
||||
return next(e for e in common.SELF_CHECK.entities if e.key == 'selfcheck_error')
|
||||
return next(e for e in common.SELF_CHECK.entities if e.key == "selfcheck_error")
|
||||
|
||||
def test_exists_when_field_present(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'x.com.samsung.da.error': ['DA_ERROR_NONE']}, {}) is True
|
||||
assert desc.exists_fn({"x.com.samsung.da.error": ["DA_ERROR_NONE"]}, {}) is True
|
||||
|
||||
def test_does_not_exist_when_field_absent(self):
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'x.com.samsung.da.status': 'Ready'}, {}) is False
|
||||
assert desc.exists_fn({"x.com.samsung.da.status": "Ready"}, {}) is False
|
||||
|
||||
def test_exists_for_true_stub_rep(self):
|
||||
"""A true stub ({"href": "..."}) is /device/0's not-yet-fetched
|
||||
marker -- must be included-for-now, same as ENERGY_METER's fields."""
|
||||
desc = self._desc()
|
||||
assert desc.exists_fn({'href': '/selfcheck/vs/0'}, {}) is True
|
||||
assert desc.exists_fn({"href": "/selfcheck/vs/0"}, {}) is True
|
||||
|
||||
def test_hidden_for_genuinely_empty_rep(self):
|
||||
"""A real {} rep is the device's confirmed empty answer, not a stub --
|
||||
@@ -510,11 +559,11 @@ class TestSelfCheckError:
|
||||
|
||||
def test_value_joins_list(self):
|
||||
desc = self._desc()
|
||||
assert desc.value_fn(['E1', 'E2']) == 'E1, E2'
|
||||
assert desc.value_fn(["E1", "E2"]) == "E1, E2"
|
||||
|
||||
def test_value_passes_through_scalar(self):
|
||||
desc = self._desc()
|
||||
assert desc.value_fn('DA_ERROR_NONE') == 'DA_ERROR_NONE'
|
||||
assert desc.value_fn("DA_ERROR_NONE") == "DA_ERROR_NONE"
|
||||
|
||||
def test_value_none_for_empty_list(self):
|
||||
"""An empty error list means no value to show -- None (unknown),
|
||||
@@ -533,10 +582,15 @@ class TestSelfCheckError:
|
||||
class TestUniversalAndPowerBundles:
|
||||
def test_universal_contains_the_no_conflict_capabilities(self):
|
||||
assert set(common.UNIVERSAL) == {
|
||||
common.ALARMS, common.ENERGY_METER, common.FIRMWARE_UPDATE,
|
||||
common.SELF_CHECK, common.AI_ENERGY_LEVEL,
|
||||
common.KIDS_LOCK_GENERIC, common.KIDS_LOCK_VS_FALLBACK,
|
||||
common.REMOTE_CONTROL_GENERIC, common.REMOTE_CONTROL_VS_FALLBACK,
|
||||
common.ALARMS,
|
||||
common.ENERGY_METER,
|
||||
common.FIRMWARE_UPDATE,
|
||||
common.SELF_CHECK,
|
||||
common.AI_ENERGY_LEVEL,
|
||||
common.KIDS_LOCK_GENERIC,
|
||||
common.KIDS_LOCK_VS_FALLBACK,
|
||||
common.REMOTE_CONTROL_GENERIC,
|
||||
common.REMOTE_CONTROL_VS_FALLBACK,
|
||||
}
|
||||
|
||||
def test_power_kept_separate_for_airconditioners_sake(self):
|
||||
@@ -548,6 +602,7 @@ class TestUniversalAndPowerBundles:
|
||||
|
||||
def test_airconditioner_registry_does_not_include_power(self):
|
||||
from custom_components.localthings.registry.by_type import airconditioner
|
||||
|
||||
bound_caps = {c for caps in airconditioner.REGISTRY.capabilities.values() for c in caps}
|
||||
assert common.POWER_GENERIC not in bound_caps
|
||||
assert common.POWER_VS_FALLBACK not in bound_caps
|
||||
@@ -19,30 +19,30 @@ def _state(resources):
|
||||
|
||||
|
||||
def test_real_cooktop_fixture_has_expected_idle_state():
|
||||
state = _state(_load_device('cooktop'))
|
||||
state = _state(_load_device("cooktop"))
|
||||
|
||||
assert state['power_state'] is True
|
||||
assert state['any_burner_active'] is False
|
||||
assert state['burner_0_state'] == 'Ready'
|
||||
assert state['burner_5_state'] == 'Ready'
|
||||
assert state['main_timer_state'] == 'Ready'
|
||||
assert state['main_timer_current'] == 0
|
||||
assert state['cloud_connected'] is True
|
||||
assert state['paired_hood_connected'] is False
|
||||
assert state['paired_hood_power'] is False
|
||||
assert state['paired_hood_fan_speed'] == 0
|
||||
assert state['paired_hood_light'] is False
|
||||
assert state["power_state"] is True
|
||||
assert state["any_burner_active"] is False
|
||||
assert state["burner_0_state"] == "Ready"
|
||||
assert state["burner_5_state"] == "Ready"
|
||||
assert state["main_timer_state"] == "Ready"
|
||||
assert state["main_timer_current"] == 0
|
||||
assert state["cloud_connected"] is True
|
||||
assert state["paired_hood_connected"] is False
|
||||
assert state["paired_hood_power"] is False
|
||||
assert state["paired_hood_fan_speed"] == 0
|
||||
assert state["paired_hood_light"] is False
|
||||
|
||||
|
||||
def test_run_operation_marks_any_burner_active():
|
||||
resources = _load_device('cooktop')
|
||||
options = resources['/mode/vs/0']['x.com.samsung.da.options']
|
||||
options[options.index('OperationState3_Ready')] = 'OperationState3_Run'
|
||||
resources = _load_device("cooktop")
|
||||
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
|
||||
options[options.index("OperationState3_Ready")] = "OperationState3_Run"
|
||||
|
||||
state = _state(resources)
|
||||
|
||||
assert state['burner_3_state'] == 'Run'
|
||||
assert state['any_burner_active'] is True
|
||||
assert state["burner_3_state"] == "Run"
|
||||
assert state["any_burner_active"] is True
|
||||
|
||||
|
||||
def test_cooktop_profile_has_no_write_functions():
|
||||
@@ -55,23 +55,22 @@ def test_cooktop_profile_has_no_write_functions():
|
||||
]
|
||||
|
||||
assert descriptions
|
||||
assert all(not hasattr(desc, 'write_fn') or desc.write_fn is None
|
||||
for desc in descriptions)
|
||||
assert all(not hasattr(desc, "write_fn") or desc.write_fn is None for desc in descriptions)
|
||||
|
||||
|
||||
def test_static_slot_superset_has_headroom_for_other_layouts():
|
||||
keys = {desc.key for desc in COOKTOP_MODE.entities}
|
||||
|
||||
assert {f'burner_{slot}_state' for slot in range(8)} <= keys
|
||||
assert {f"burner_{slot}_state" for slot in range(8)} <= keys
|
||||
|
||||
|
||||
def test_variant_slot_outside_na9300k_layout_is_discovered():
|
||||
resources = _load_device('cooktop')
|
||||
resources['/mode/vs/0']['x.com.samsung.da.options'].append(
|
||||
'OperationState7_Ready',
|
||||
resources = _load_device("cooktop")
|
||||
resources["/mode/vs/0"]["x.com.samsung.da.options"].append(
|
||||
"OperationState7_Ready",
|
||||
)
|
||||
|
||||
state = _state(resources)
|
||||
|
||||
assert state['burner_7_state'] == 'Ready'
|
||||
assert 'burner_2_state' not in state
|
||||
assert state["burner_7_state"] == "Ready"
|
||||
assert "burner_2_state" not in state
|
||||
@@ -5,6 +5,7 @@ write_fn/validate_fn, so this only exercises the primitive itself: it
|
||||
POSTs exactly the caller's body, reads the href back, and validates its
|
||||
inputs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
@@ -16,15 +17,19 @@ from homeassistant.exceptions import ServiceValidationError
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.localthings.const import (
|
||||
CONF_HOST, CONF_LEAF_CERT_PEM, CONF_LEAF_KEY_PEM, CONF_PORT, DOMAIN,
|
||||
CONF_HOST,
|
||||
CONF_LEAF_CERT_PEM,
|
||||
CONF_LEAF_KEY_PEM,
|
||||
CONF_PORT,
|
||||
DOMAIN,
|
||||
)
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
|
||||
ENTRY_DATA = {
|
||||
CONF_HOST: '10.0.0.199',
|
||||
CONF_HOST: "10.0.0.199",
|
||||
CONF_PORT: 49154,
|
||||
CONF_LEAF_CERT_PEM: '-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----',
|
||||
CONF_LEAF_KEY_PEM: '-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----',
|
||||
CONF_LEAF_CERT_PEM: "-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----",
|
||||
CONF_LEAF_KEY_PEM: "-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----",
|
||||
}
|
||||
|
||||
|
||||
@@ -41,7 +46,7 @@ class _FakeRawWriteSession:
|
||||
|
||||
def post(self, path_segs, payload, timeout=None):
|
||||
self.post_calls.append((list(path_segs), payload))
|
||||
return self._post_code, b''
|
||||
return self._post_code, b""
|
||||
|
||||
def get(self, path_segs, timeout=None):
|
||||
self.get_calls.append(list(path_segs))
|
||||
@@ -54,7 +59,9 @@ class _FakeRawWriteSession:
|
||||
@pytest.fixture
|
||||
def coordinator(hass: HomeAssistant) -> LocalThingsCoordinator:
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data=ENTRY_DATA, unique_id='localthings_RAWWRITE-TEST',
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_DATA,
|
||||
unique_id="localthings_RAWWRITE-TEST",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
coord = LocalThingsCoordinator(hass, entry)
|
||||
@@ -66,63 +73,63 @@ def coordinator(hass: HomeAssistant) -> LocalThingsCoordinator:
|
||||
|
||||
|
||||
async def test_raw_write_splits_href_and_posts_exact_body(coordinator) -> None:
|
||||
fake = _FakeRawWriteSession(post_code=0x44, get_rep={'x.field': 'after'})
|
||||
fake = _FakeRawWriteSession(post_code=0x44, get_rep={"x.field": "after"})
|
||||
coordinator._session = fake
|
||||
|
||||
body = {'x.com.samsung.da.field': 'value', 'n': 1}
|
||||
code, new_rep = await coordinator.async_raw_write('/course/vs/0', body)
|
||||
body = {"x.com.samsung.da.field": "value", "n": 1}
|
||||
code, new_rep = await coordinator.async_raw_write("/course/vs/0", body)
|
||||
|
||||
assert len(fake.post_calls) == 1
|
||||
posted_path, posted_bytes = fake.post_calls[0]
|
||||
assert posted_path == ['course', 'vs', '0']
|
||||
assert posted_path == ["course", "vs", "0"]
|
||||
assert cbor2.loads(posted_bytes) == body
|
||||
|
||||
assert code == 0x44
|
||||
assert new_rep == {'x.field': 'after'}
|
||||
assert new_rep == {"x.field": "after"}
|
||||
coordinator.async_request_refresh.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_raw_write_reads_href_back_for_ground_truth(coordinator) -> None:
|
||||
fake = _FakeRawWriteSession(post_code=0x45, get_rep={'value': 'confirmed'})
|
||||
fake = _FakeRawWriteSession(post_code=0x45, get_rep={"value": "confirmed"})
|
||||
coordinator._session = fake
|
||||
|
||||
code, new_rep = await coordinator.async_raw_write('/washer/vs/0', {'a': 1})
|
||||
code, new_rep = await coordinator.async_raw_write("/washer/vs/0", {"a": 1})
|
||||
|
||||
assert fake.get_calls == [['washer', 'vs', '0']]
|
||||
assert fake.get_calls == [["washer", "vs", "0"]]
|
||||
assert code == 0x45
|
||||
assert new_rep == {'value': 'confirmed'}
|
||||
assert new_rep == {"value": "confirmed"}
|
||||
|
||||
|
||||
async def test_raw_write_returns_coap_code_from_post_not_get(coordinator) -> None:
|
||||
"""The returned code reflects the write's own response, even though a
|
||||
follow-up GET (which could carry a different code in principle) runs
|
||||
right after it."""
|
||||
fake = _FakeRawWriteSession(post_code=0x80, get_rep={'value': 1})
|
||||
fake = _FakeRawWriteSession(post_code=0x80, get_rep={"value": 1})
|
||||
coordinator._session = fake
|
||||
|
||||
code, _ = await coordinator.async_raw_write('/test/vs/0', {'a': 1})
|
||||
code, _ = await coordinator.async_raw_write("/test/vs/0", {"a": 1})
|
||||
|
||||
assert code == 0x80
|
||||
|
||||
|
||||
async def test_raw_write_rejects_empty_dict(coordinator) -> None:
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await coordinator.async_raw_write('/washer/vs/0', {})
|
||||
await coordinator.async_raw_write("/washer/vs/0", {})
|
||||
|
||||
|
||||
async def test_raw_write_rejects_non_dict_payload(coordinator) -> None:
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await coordinator.async_raw_write('/washer/vs/0', ['not', 'a', 'dict']) # type: ignore[arg-type]
|
||||
await coordinator.async_raw_write("/washer/vs/0", ["not", "a", "dict"]) # type: ignore[arg-type]
|
||||
|
||||
|
||||
async def test_raw_write_rejects_empty_href(coordinator) -> None:
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await coordinator.async_raw_write('', {'a': 1})
|
||||
await coordinator.async_raw_write("", {"a": 1})
|
||||
|
||||
|
||||
async def test_raw_write_rejects_root_href(coordinator) -> None:
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await coordinator.async_raw_write('/', {'a': 1})
|
||||
await coordinator.async_raw_write("/", {"a": 1})
|
||||
|
||||
|
||||
async def test_raw_write_validation_errors_do_not_touch_the_session(coordinator) -> None:
|
||||
@@ -131,7 +138,7 @@ async def test_raw_write_validation_errors_do_not_touch_the_session(coordinator)
|
||||
assert coordinator._session is None
|
||||
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await coordinator.async_raw_write('/washer/vs/0', {})
|
||||
await coordinator.async_raw_write("/washer/vs/0", {})
|
||||
|
||||
assert coordinator._session is None
|
||||
coordinator.async_request_refresh.assert_not_awaited()
|
||||
@@ -11,6 +11,7 @@ real poll lands. async_send_command must pre-merge the token into the
|
||||
cached array itself before applying it optimistically, while still POSTing
|
||||
only the minimal body over the wire.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
@@ -21,7 +22,11 @@ from homeassistant.core import HomeAssistant
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.localthings.const import (
|
||||
CONF_HOST, CONF_LEAF_CERT_PEM, CONF_LEAF_KEY_PEM, CONF_PORT, DOMAIN,
|
||||
CONF_HOST,
|
||||
CONF_LEAF_CERT_PEM,
|
||||
CONF_LEAF_KEY_PEM,
|
||||
CONF_PORT,
|
||||
DOMAIN,
|
||||
)
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
from custom_components.localthings.registry.capabilities import laundry
|
||||
@@ -31,10 +36,10 @@ from custom_components.localthings.registry.entities import ClimateDesc
|
||||
from custom_components.localthings.registry.subdevices import Subdevice
|
||||
|
||||
ENTRY_DATA = {
|
||||
CONF_HOST: '10.0.0.199',
|
||||
CONF_HOST: "10.0.0.199",
|
||||
CONF_PORT: 49154,
|
||||
CONF_LEAF_CERT_PEM: '-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----',
|
||||
CONF_LEAF_KEY_PEM: '-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----',
|
||||
CONF_LEAF_CERT_PEM: "-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----",
|
||||
CONF_LEAF_KEY_PEM: "-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----",
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +49,7 @@ class _FakeSendSession:
|
||||
|
||||
def post(self, path_segs, payload, timeout=None):
|
||||
self.post_calls.append((list(path_segs), payload))
|
||||
return 0x44, b''
|
||||
return 0x44, b""
|
||||
|
||||
def pace(self):
|
||||
pass
|
||||
@@ -53,7 +58,9 @@ class _FakeSendSession:
|
||||
@pytest.fixture
|
||||
def coordinator(hass: HomeAssistant) -> LocalThingsCoordinator:
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data=ENTRY_DATA, unique_id='localthings_SENDCMD-TEST',
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_DATA,
|
||||
unique_id="localthings_SENDCMD-TEST",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
coord = LocalThingsCoordinator(hass, entry)
|
||||
@@ -63,37 +70,47 @@ def coordinator(hass: HomeAssistant) -> LocalThingsCoordinator:
|
||||
|
||||
|
||||
async def test_options_write_posts_only_the_changed_token(coordinator) -> None:
|
||||
href = '/course/vs/0'
|
||||
coordinator._observe.apply(href, {
|
||||
'x.com.samsung.da.options': ['DeviceType_0167', 'Course_16', 'GMT_04'],
|
||||
}, source='poll')
|
||||
href = "/course/vs/0"
|
||||
coordinator._observe.apply(
|
||||
href,
|
||||
{
|
||||
"x.com.samsung.da.options": ["DeviceType_0167", "Course_16", "GMT_04"],
|
||||
},
|
||||
source="poll",
|
||||
)
|
||||
|
||||
desc = laundry.cycle_select(translation_key='dryer_cycle', icon='x')
|
||||
desc = laundry.cycle_select(translation_key="dryer_cycle", icon="x")
|
||||
bound = BoundEntity(href=href, capability=None, desc=desc)
|
||||
|
||||
await coordinator.async_send_command(bound, '1D')
|
||||
await coordinator.async_send_command(bound, "1D")
|
||||
|
||||
posted_path, posted_bytes = coordinator._session.post_calls[0]
|
||||
assert posted_path == ['course', 'vs', '0']
|
||||
assert cbor2.loads(posted_bytes) == {'x.com.samsung.da.options': ['Course_1D']}
|
||||
assert posted_path == ["course", "vs", "0"]
|
||||
assert cbor2.loads(posted_bytes) == {"x.com.samsung.da.options": ["Course_1D"]}
|
||||
|
||||
|
||||
async def test_options_write_optimistic_cache_keeps_sibling_tokens(coordinator) -> None:
|
||||
"""The regression this guards: applying the minimal wire body straight
|
||||
to the cache would wipe DeviceType_0167/GMT_04 until the next poll."""
|
||||
href = '/course/vs/0'
|
||||
coordinator._observe.apply(href, {
|
||||
'x.com.samsung.da.options': ['DeviceType_0167', 'Course_16', 'GMT_04'],
|
||||
}, source='poll')
|
||||
href = "/course/vs/0"
|
||||
coordinator._observe.apply(
|
||||
href,
|
||||
{
|
||||
"x.com.samsung.da.options": ["DeviceType_0167", "Course_16", "GMT_04"],
|
||||
},
|
||||
source="poll",
|
||||
)
|
||||
|
||||
desc = laundry.cycle_select(translation_key='dryer_cycle', icon='x')
|
||||
desc = laundry.cycle_select(translation_key="dryer_cycle", icon="x")
|
||||
bound = BoundEntity(href=href, capability=None, desc=desc)
|
||||
|
||||
await coordinator.async_send_command(bound, '1D')
|
||||
await coordinator.async_send_command(bound, "1D")
|
||||
|
||||
cached = coordinator._cache.get(href)
|
||||
assert cached['x.com.samsung.da.options'] == [
|
||||
'DeviceType_0167', 'Course_1D', 'GMT_04',
|
||||
assert cached["x.com.samsung.da.options"] == [
|
||||
"DeviceType_0167",
|
||||
"Course_1D",
|
||||
"GMT_04",
|
||||
]
|
||||
|
||||
|
||||
@@ -107,63 +124,65 @@ async def test_options_write_optimistic_cache_keeps_sibling_tokens(coordinator)
|
||||
# its own.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _climate_bound(href: str, subdevice: Subdevice) -> BoundEntity:
|
||||
desc = ClimateDesc(key='climate', translation_key='airconditioner',
|
||||
write_fn=_climate_write)
|
||||
desc = ClimateDesc(key="climate", translation_key="airconditioner", write_fn=_climate_write)
|
||||
return BoundEntity(href=href, capability=None, desc=desc, subdevice=subdevice)
|
||||
|
||||
|
||||
async def test_indexed_subdevice_write_posts_to_translated_path(coordinator) -> None:
|
||||
"""A power write from the bedroom subdevice's (indexed '1') climate entity
|
||||
must POST to /power/vs/1, not the master's /power/vs/0."""
|
||||
sub1 = Subdevice(kind='indexed', key='1', seed_path=('device', '1'))
|
||||
bound = _climate_bound('/mode/vs/1', sub1)
|
||||
sub1 = Subdevice(kind="indexed", key="1", seed_path=("device", "1"))
|
||||
bound = _climate_bound("/mode/vs/1", sub1)
|
||||
|
||||
await coordinator.async_send_command(bound, ('power', True))
|
||||
await coordinator.async_send_command(bound, ("power", True))
|
||||
|
||||
posted_path, posted_bytes = coordinator._session.post_calls[0]
|
||||
assert posted_path == ['power', 'vs', '1']
|
||||
assert cbor2.loads(posted_bytes) == {'x.com.samsung.da.power': 'On'}
|
||||
assert posted_path == ["power", "vs", "1"]
|
||||
assert cbor2.loads(posted_bytes) == {"x.com.samsung.da.power": "On"}
|
||||
|
||||
|
||||
async def test_indexed_subdevice_write_applies_optimistic_value_to_translated_href(
|
||||
coordinator,
|
||||
) -> None:
|
||||
sub1 = Subdevice(kind='indexed', key='1', seed_path=('device', '1'))
|
||||
bound = _climate_bound('/mode/vs/1', sub1)
|
||||
sub1 = Subdevice(kind="indexed", key="1", seed_path=("device", "1"))
|
||||
bound = _climate_bound("/mode/vs/1", sub1)
|
||||
|
||||
await coordinator.async_send_command(bound, ('power', True))
|
||||
await coordinator.async_send_command(bound, ("power", True))
|
||||
|
||||
# The optimistic apply + settle guard must land on /power/vs/1 -- the
|
||||
# translated href a real device confirms this write against -- not on
|
||||
# /mode/vs/1 (bound_entity.href) or /power/vs/0 (the master's resource).
|
||||
assert coordinator._cache.get('/power/vs/1') == {'x.com.samsung.da.power': 'On'}
|
||||
assert coordinator._cache.get('/power/vs/0') is None
|
||||
assert coordinator._cache.get("/power/vs/1") == {"x.com.samsung.da.power": "On"}
|
||||
assert coordinator._cache.get("/power/vs/0") is None
|
||||
# The settle guard is armed on that same translated href: a stale poll
|
||||
# reporting the pre-write value must be dropped, not allowed to revert
|
||||
# the optimistic 'On' (issue #27's regression, translated to a
|
||||
# subdevice's own resource).
|
||||
applied = coordinator._observe.apply(
|
||||
'/power/vs/1', {'x.com.samsung.da.power': 'Off'}, source='poll',
|
||||
"/power/vs/1",
|
||||
{"x.com.samsung.da.power": "Off"},
|
||||
source="poll",
|
||||
)
|
||||
assert applied is False
|
||||
assert coordinator._cache.get('/power/vs/1') == {'x.com.samsung.da.power': 'On'}
|
||||
assert coordinator._cache.get("/power/vs/1") == {"x.com.samsung.da.power": "On"}
|
||||
|
||||
|
||||
async def test_prefixed_subdevice_write_posts_to_translated_path(coordinator) -> None:
|
||||
"""A power write from a UUID-prefixed subdevice's climate entity must POST
|
||||
to /<uuid>/power/vs/0, not the bare canonical href."""
|
||||
sub_id = '6c2dff6d-ee5c-dad1-6a5e-000000000001'
|
||||
subdevice = Subdevice(kind='prefixed', key=sub_id, seed_path=(sub_id, 'device', '0'))
|
||||
bound = _climate_bound(f'/{sub_id}/mode/vs/0', subdevice)
|
||||
sub_id = "6c2dff6d-ee5c-dad1-6a5e-000000000001"
|
||||
subdevice = Subdevice(kind="prefixed", key=sub_id, seed_path=(sub_id, "device", "0"))
|
||||
bound = _climate_bound(f"/{sub_id}/mode/vs/0", subdevice)
|
||||
|
||||
await coordinator.async_send_command(bound, ('power', True))
|
||||
await coordinator.async_send_command(bound, ("power", True))
|
||||
|
||||
posted_path, posted_bytes = coordinator._session.post_calls[0]
|
||||
assert posted_path == [sub_id, 'power', 'vs', '0']
|
||||
assert cbor2.loads(posted_bytes) == {'x.com.samsung.da.power': 'On'}
|
||||
assert coordinator._cache.get(f'/{sub_id}/power/vs/0') == {
|
||||
'x.com.samsung.da.power': 'On',
|
||||
assert posted_path == [sub_id, "power", "vs", "0"]
|
||||
assert cbor2.loads(posted_bytes) == {"x.com.samsung.da.power": "On"}
|
||||
assert coordinator._cache.get(f"/{sub_id}/power/vs/0") == {
|
||||
"x.com.samsung.da.power": "On",
|
||||
}
|
||||
|
||||
|
||||
@@ -172,9 +191,10 @@ async def test_main_climate_write_unaffected_by_subdevice_translation(coordinato
|
||||
subdevices must keep posting to the exact same path as before this
|
||||
translation step existed."""
|
||||
from custom_components.localthings.registry.subdevices import MAIN
|
||||
bound = _climate_bound('/mode/vs/0', MAIN)
|
||||
|
||||
await coordinator.async_send_command(bound, ('power', True))
|
||||
bound = _climate_bound("/mode/vs/0", MAIN)
|
||||
|
||||
await coordinator.async_send_command(bound, ("power", True))
|
||||
|
||||
posted_path, _ = coordinator._session.post_calls[0]
|
||||
assert posted_path == ['power', 'vs', '0']
|
||||
assert posted_path == ["power", "vs", "0"]
|
||||
@@ -3,19 +3,20 @@
|
||||
HA-free like the rest of the suite: exercises the registry, discovery/
|
||||
flatten, and the target-humidity/operating-mode write contracts.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.entities import NumberDesc, SelectDesc
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _dehumidifier():
|
||||
resources = _load_device('dehumidifier')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("dehumidifier")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -37,7 +38,7 @@ def _desc(key):
|
||||
|
||||
def test_model_resolves_to_dehumidifier_registry():
|
||||
reg, _ = _dehumidifier()
|
||||
assert reg is not None and reg.name == 'dehumidifier'
|
||||
assert reg is not None and reg.name == "dehumidifier"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -51,36 +52,43 @@ def test_no_unbound_hrefs():
|
||||
|
||||
def test_expected_state_keys_present():
|
||||
state = _state()
|
||||
for key in ('humidity', 'target_humidity', 'operating_mode', 'power_switch',
|
||||
'auto_clean', 'air_filter_status', 'mute_once'):
|
||||
for key in (
|
||||
"humidity",
|
||||
"target_humidity",
|
||||
"operating_mode",
|
||||
"power_switch",
|
||||
"auto_clean",
|
||||
"air_filter_status",
|
||||
"mute_once",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
|
||||
def test_humidity_sensor_reads_current_value():
|
||||
state = _state()
|
||||
assert state['humidity'] == 47
|
||||
assert state["humidity"] == 47
|
||||
|
||||
|
||||
def test_target_humidity_number_reads_desired_value():
|
||||
state = _state()
|
||||
assert state['target_humidity'] == 50
|
||||
assert state["target_humidity"] == 50
|
||||
|
||||
|
||||
def test_target_humidity_write_contract():
|
||||
desc = _desc('target_humidity')
|
||||
desc = _desc("target_humidity")
|
||||
assert isinstance(desc, NumberDesc)
|
||||
path, body = desc.write_fn('55', {})
|
||||
assert path == ['humidity', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.desiredHumidity': '55'}
|
||||
path, body = desc.write_fn("55", {})
|
||||
assert path == ["humidity", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.desiredHumidity": "55"}
|
||||
|
||||
|
||||
def test_target_humidity_step_reads_live_increment():
|
||||
"""Step comes from the device's own `increment` field rather than a
|
||||
hardcoded constant -- see the adding-device-support skill's 'never
|
||||
hard-code the one dump's values' section."""
|
||||
desc = _desc('target_humidity')
|
||||
assert desc.step_fn({'increment': '5'}) == 5
|
||||
assert desc.step_fn({'increment': '10'}) == 10
|
||||
desc = _desc("target_humidity")
|
||||
assert desc.step_fn({"increment": "5"}) == 5
|
||||
assert desc.step_fn({"increment": "10"}) == 10
|
||||
# No live field: falls back to a sane default rather than raising.
|
||||
assert desc.step_fn({}) == 1
|
||||
|
||||
@@ -89,7 +97,7 @@ def test_target_humidity_has_no_hardcoded_bounds():
|
||||
"""No range field is present in any dump seen so far -- native_min/max
|
||||
are deliberately left unset (falls back to HA's own 0-100 default for a
|
||||
percentage field) rather than a bound guessed from a spec sheet."""
|
||||
desc = _desc('target_humidity')
|
||||
desc = _desc("target_humidity")
|
||||
assert desc.native_min is None
|
||||
assert desc.native_max is None
|
||||
assert desc.native_min_fn is None
|
||||
@@ -100,19 +108,19 @@ def test_operating_mode_select_options_come_from_live_supported_modes():
|
||||
"""Options are read live from x.com.samsung.da.supportedModes, not a
|
||||
hardcoded tuple -- so a future device with a different mode set is
|
||||
handled automatically."""
|
||||
desc = _desc('operating_mode')
|
||||
desc = _desc("operating_mode")
|
||||
assert isinstance(desc, SelectDesc)
|
||||
assert desc.options_field == 'x.com.samsung.da.supportedModes'
|
||||
assert desc.options_field == "x.com.samsung.da.supportedModes"
|
||||
assert desc.options == ()
|
||||
|
||||
|
||||
def test_operating_mode_write_contract():
|
||||
desc = _desc('operating_mode')
|
||||
path, body = desc.write_fn('Quiet', {})
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.modes': ['Quiet']}
|
||||
desc = _desc("operating_mode")
|
||||
path, body = desc.write_fn("Quiet", {})
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.modes": ["Quiet"]}
|
||||
|
||||
|
||||
def test_operating_mode_reads_first_mode():
|
||||
state = _state()
|
||||
assert state['operating_mode'] == 'Smart'
|
||||
assert state["operating_mode"] == "Smart"
|
||||
@@ -3,6 +3,7 @@ subdevices_skipped, subdevice_probes) against a real composite-device
|
||||
discovery run -- makes sure the new blocks are actually reachable/shaped
|
||||
right, not just that the coordinator's own attributes look correct in
|
||||
isolation (test_subdevice_discovery.py covers that)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -11,36 +12,37 @@ from custom_components.localthings.const import DOMAIN
|
||||
from custom_components.localthings.diagnostics import (
|
||||
async_get_config_entry_diagnostics,
|
||||
)
|
||||
|
||||
from tests.test_subdevice_discovery import _coordinator, _discover
|
||||
|
||||
|
||||
async def test_diagnostics_reports_materialized_and_skipped_subdevices(
|
||||
hass: HomeAssistant, enable_custom_integrations,
|
||||
hass: HomeAssistant,
|
||||
enable_custom_integrations,
|
||||
) -> None:
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_dongle_fac_18k')
|
||||
await _discover(coordinator, "airconditioner_artik051_dongle_fac_18k")
|
||||
hass.data.setdefault(DOMAIN, {})[coordinator._entry.entry_id] = coordinator
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, coordinator._entry)
|
||||
|
||||
subdevice_keys = {su['key'] for su in diag['subdevices']}
|
||||
skipped_keys = {su['key'] for su in diag['subdevices_skipped']}
|
||||
assert subdevice_keys == {'1'}
|
||||
assert skipped_keys == {'2'}
|
||||
assert diag['subdevices'][0]['bound_entity_count'] > 0
|
||||
assert diag['subdevices_skipped'][0]['hrefs']
|
||||
assert '/multidevice/vs/0' in diag['subdevice_probes']
|
||||
subdevice_keys = {su["key"] for su in diag["subdevices"]}
|
||||
skipped_keys = {su["key"] for su in diag["subdevices_skipped"]}
|
||||
assert subdevice_keys == {"1"}
|
||||
assert skipped_keys == {"2"}
|
||||
assert diag["subdevices"][0]["bound_entity_count"] > 0
|
||||
assert diag["subdevices_skipped"][0]["hrefs"]
|
||||
assert "/multidevice/vs/0" in diag["subdevice_probes"]
|
||||
# The reporter's hand-read value, carried in the fixture's `probes` map
|
||||
# (it belongs to no batch -- see that fixture's seeds_note). Two real
|
||||
# subdevices, master + bedroom, independently corroborating the gate's
|
||||
# decision to skip /device/2. Reported on its own, never as a resource.
|
||||
assert diag['multidevice'] == {'x.com.samsung.da.numofsubdevice': '2'}
|
||||
assert '/multidevice/vs/0' not in diag['resources']
|
||||
assert diag["multidevice"] == {"x.com.samsung.da.numofsubdevice": "2"}
|
||||
assert "/multidevice/vs/0" not in diag["resources"]
|
||||
|
||||
|
||||
async def test_top_level_resources_is_the_master_subdevice_only(
|
||||
hass: HomeAssistant, enable_custom_integrations,
|
||||
hass: HomeAssistant,
|
||||
enable_custom_integrations,
|
||||
) -> None:
|
||||
"""`resources` reports this subdevice's own hrefs and nothing else.
|
||||
|
||||
@@ -51,23 +53,24 @@ async def test_top_level_resources_is_the_master_subdevice_only(
|
||||
snapshot"). Each sibling carries its own canonicalized block instead.
|
||||
"""
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_dongle_fac_18k')
|
||||
await _discover(coordinator, "airconditioner_artik051_dongle_fac_18k")
|
||||
hass.data.setdefault(DOMAIN, {})[coordinator._entry.entry_id] = coordinator
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, coordinator._entry)
|
||||
|
||||
assert not [h for h in diag['resources'] if h.endswith('/1')]
|
||||
assert '/mode/vs/0' in diag['resources']
|
||||
assert not [h for h in diag["resources"] if h.endswith("/1")]
|
||||
assert "/mode/vs/0" in diag["resources"]
|
||||
# The sibling's own block carries its state, canonicalized -- '/mode/vs/0',
|
||||
# not the '/mode/vs/1' it actually answers on.
|
||||
sub1 = diag["subdevices"][0]
|
||||
assert '/mode/vs/0' in sub1["resources"]
|
||||
assert not [h for h in sub1['resources'] if h.endswith('/1')]
|
||||
assert sub1["resources"]["/power/vs/0"]['x.com.samsung.da.power'] == 'On'
|
||||
assert "/mode/vs/0" in sub1["resources"]
|
||||
assert not [h for h in sub1["resources"] if h.endswith("/1")]
|
||||
assert sub1["resources"]["/power/vs/0"]["x.com.samsung.da.power"] == "On"
|
||||
|
||||
|
||||
async def test_rejected_candidate_reps_reach_diagnostics_but_not_the_cache(
|
||||
hass: HomeAssistant, enable_custom_integrations,
|
||||
hass: HomeAssistant,
|
||||
enable_custom_integrations,
|
||||
) -> None:
|
||||
"""A gate-rejected slot is never polled again, so anything applied to the
|
||||
state cache for it would sit frozen at its first-discovery value while
|
||||
@@ -75,40 +78,42 @@ async def test_rejected_candidate_reps_reach_diagnostics_but_not_the_cache(
|
||||
and reported only under its own subdevices_skipped entry -- which is also
|
||||
the only place a reader can go to second-guess the gate."""
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_dongle_fac_18k')
|
||||
await _discover(coordinator, "airconditioner_artik051_dongle_fac_18k")
|
||||
hass.data.setdefault(DOMAIN, {})[coordinator._entry.entry_id] = coordinator
|
||||
|
||||
assert not [h for h in coordinator.last_resources if h.endswith('/2')]
|
||||
assert not [h for h in coordinator.last_resources if h.endswith("/2")]
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, coordinator._entry)
|
||||
skipped = diag['subdevices_skipped'][0]
|
||||
skipped = diag["subdevices_skipped"][0]
|
||||
# Present, canonicalized, and visibly the empty state the gate rejected.
|
||||
assert skipped['resources']['/power/vs/0'] == {}
|
||||
assert skipped['resources']['/mode/vs/0'] == {}
|
||||
assert skipped['resources']['/information/vs/0']
|
||||
assert skipped["resources"]["/power/vs/0"] == {}
|
||||
assert skipped["resources"]["/mode/vs/0"] == {}
|
||||
assert skipped["resources"]["/information/vs/0"]
|
||||
|
||||
|
||||
async def test_diagnostics_reports_prefixed_subdevice(
|
||||
hass: HomeAssistant, enable_custom_integrations,
|
||||
hass: HomeAssistant,
|
||||
enable_custom_integrations,
|
||||
) -> None:
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_fac_bora_2in1')
|
||||
await _discover(coordinator, "airconditioner_fac_bora_2in1")
|
||||
hass.data.setdefault(DOMAIN, {})[coordinator._entry.entry_id] = coordinator
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, coordinator._entry)
|
||||
|
||||
assert len(diag['subdevices']) == 1
|
||||
assert diag['subdevices'][0]['kind'] == 'prefixed'
|
||||
assert len(diag["subdevices"]) == 1
|
||||
assert diag["subdevices"][0]["kind"] == "prefixed"
|
||||
# diagnostics reports the raw modelNum field verbatim (board revision/
|
||||
# capability-bitmap suffix included), unlike device_info_for's model
|
||||
# (split at '|') -- confirms it's still the wall subdevice's own identity,
|
||||
# not the master's TP2X_FAC_BORA_21K.
|
||||
assert diag['subdevices'][0]['model'].startswith('TP2X_FAC_BORA_RAC_21K')
|
||||
assert diag['subdevices_skipped'] == []
|
||||
assert diag["subdevices"][0]["model"].startswith("TP2X_FAC_BORA_RAC_21K")
|
||||
assert diag["subdevices_skipped"] == []
|
||||
|
||||
|
||||
async def test_diagnostics_reports_flat_hrefs_for_skipped_prefixed_candidate(
|
||||
hass: HomeAssistant, enable_custom_integrations,
|
||||
hass: HomeAssistant,
|
||||
enable_custom_integrations,
|
||||
) -> None:
|
||||
"""issue #205: a prefixed candidate found through the per-href flat
|
||||
fallback (no working /<uuid>/device/0 Collection) has no meaningful
|
||||
@@ -116,14 +121,14 @@ async def test_diagnostics_reports_flat_hrefs_for_skipped_prefixed_candidate(
|
||||
bare "/" an empty tuple would otherwise join to, and lists the actual
|
||||
hrefs the fallback confirmed instead."""
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_fac_bora_205_flat')
|
||||
await _discover(coordinator, "airconditioner_fac_bora_205_flat")
|
||||
hass.data.setdefault(DOMAIN, {})[coordinator._entry.entry_id] = coordinator
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, coordinator._entry)
|
||||
|
||||
assert diag['subdevices'] == []
|
||||
assert len(diag['subdevices_skipped']) == 1
|
||||
skipped = diag['subdevices_skipped'][0]
|
||||
assert skipped['kind'] == 'prefixed'
|
||||
assert skipped['seed_path'] is None
|
||||
assert skipped['flat_hrefs'] == ['/information/vs/0']
|
||||
assert diag["subdevices"] == []
|
||||
assert len(diag["subdevices_skipped"]) == 1
|
||||
skipped = diag["subdevices_skipped"][0]
|
||||
assert skipped["kind"] == "prefixed"
|
||||
assert skipped["seed_path"] is None
|
||||
assert skipped["flat_hrefs"] == ["/information/vs/0"]
|
||||
+85
-84
@@ -1,111 +1,118 @@
|
||||
from custom_components.localthings.registry.capability import Capability
|
||||
from custom_components.localthings.registry.discovery import (
|
||||
BoundEntity, discover, instance_suffix,
|
||||
discover,
|
||||
instance_suffix,
|
||||
)
|
||||
from custom_components.localthings.registry.entities import BinarySensorDesc
|
||||
|
||||
LOCK = Capability(
|
||||
href='/kidslock/vs/0',
|
||||
entities=(BinarySensorDesc(key='child_lock', field='x.com.samsung.da.kidsLock'),),
|
||||
href="/kidslock/vs/0",
|
||||
entities=(BinarySensorDesc(key="child_lock", field="x.com.samsung.da.kidsLock"),),
|
||||
)
|
||||
assert LOCK.href is not None
|
||||
REG = {LOCK.href: [LOCK]}
|
||||
|
||||
|
||||
def test_instance_suffix():
|
||||
assert instance_suffix('/kidslock/vs/0') == ''
|
||||
assert instance_suffix('/door/vs/1') == '_1'
|
||||
assert instance_suffix('/icemaker/vs/2') == '_2'
|
||||
assert instance_suffix("/kidslock/vs/0") == ""
|
||||
assert instance_suffix("/door/vs/1") == "_1"
|
||||
assert instance_suffix("/icemaker/vs/2") == "_2"
|
||||
|
||||
|
||||
def test_discover_binds_present_capability():
|
||||
resources = {'/kidslock/vs/0': {'x.com.samsung.da.kidsLock': 'On'}}
|
||||
resources = {"/kidslock/vs/0": {"x.com.samsung.da.kidsLock": "On"}}
|
||||
bound = discover(resources, REG)
|
||||
assert len(bound) == 1
|
||||
assert bound[0].href == '/kidslock/vs/0'
|
||||
assert bound[0].desc.key == 'child_lock'
|
||||
assert bound[0].instance == ''
|
||||
assert bound[0].href == "/kidslock/vs/0"
|
||||
assert bound[0].desc.key == "child_lock"
|
||||
assert bound[0].instance == ""
|
||||
|
||||
|
||||
def test_discover_skips_unknown_href():
|
||||
seen = []
|
||||
resources = {'/mystery/vs/0': {'x.com.samsung.da.mystery': 'x'}}
|
||||
resources = {"/mystery/vs/0": {"x.com.samsung.da.mystery": "x"}}
|
||||
bound = discover(resources, REG, log=seen.append)
|
||||
assert bound == []
|
||||
assert any('mystery' in m for m in seen)
|
||||
assert any("mystery" in m for m in seen)
|
||||
|
||||
|
||||
def test_discover_multi_instance_suffixes():
|
||||
cap = Capability(href='/door/vs/0',
|
||||
entities=(BinarySensorDesc(key='door', field='x.com.samsung.da.doorState'),))
|
||||
cap = Capability(
|
||||
href="/door/vs/0",
|
||||
entities=(BinarySensorDesc(key="door", field="x.com.samsung.da.doorState"),),
|
||||
)
|
||||
resources = {
|
||||
'/door/vs/0': {'x.com.samsung.da.doorState': 'Open'},
|
||||
'/door/vs/1': {'x.com.samsung.da.doorState': 'Closed'},
|
||||
"/door/vs/0": {"x.com.samsung.da.doorState": "Open"},
|
||||
"/door/vs/1": {"x.com.samsung.da.doorState": "Closed"},
|
||||
}
|
||||
reg = {'/door/vs/0': [cap], '/door/vs/1': [cap]}
|
||||
reg = {"/door/vs/0": [cap], "/door/vs/1": [cap]}
|
||||
bound = discover(resources, reg)
|
||||
insts = sorted(b.instance for b in bound)
|
||||
assert insts == ['', '_1']
|
||||
assert insts == ["", "_1"]
|
||||
|
||||
|
||||
def test_discover_logs_unregistered_href():
|
||||
seen = []
|
||||
cap = Capability(href='/kidslock/vs/0',
|
||||
entities=(BinarySensorDesc(key='child_lock', field='x.com.samsung.da.kidsLock'),))
|
||||
cap = Capability(
|
||||
href="/kidslock/vs/0",
|
||||
entities=(BinarySensorDesc(key="child_lock", field="x.com.samsung.da.kidsLock"),),
|
||||
)
|
||||
resources = {
|
||||
'/kidslock/vs/0': {'x.com.samsung.da.kidsLock': 'On'},
|
||||
'/mystery/vs/0': {'x.com.samsung.da.mystery': 'x'},
|
||||
"/kidslock/vs/0": {"x.com.samsung.da.kidsLock": "On"},
|
||||
"/mystery/vs/0": {"x.com.samsung.da.mystery": "x"},
|
||||
}
|
||||
bound = discover(resources, {'/kidslock/vs/0': [cap]}, log=seen.append)
|
||||
bound = discover(resources, {"/kidslock/vs/0": [cap]}, log=seen.append)
|
||||
assert len(bound) == 1
|
||||
assert any('mystery' in m for m in seen)
|
||||
assert any("mystery" in m for m in seen)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# New tests for Task 2: pattern caps, rt_filter, match_fn
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_discover_pattern_cap_binds_unmatched_href():
|
||||
"""Pattern cap with rt_filter binds unmatched hrefs; exact-href cap does not
|
||||
steal unmatched hrefs."""
|
||||
cooler_cap = Capability(
|
||||
href='/door/cooler/0',
|
||||
entities=(BinarySensorDesc(key='cooler_door', field='x.com.samsung.da.doorState'),),
|
||||
href="/door/cooler/0",
|
||||
entities=(BinarySensorDesc(key="cooler_door", field="x.com.samsung.da.doorState"),),
|
||||
)
|
||||
door_pattern = Capability(
|
||||
href=None,
|
||||
rt_filter='oic.r.door',
|
||||
entities=(BinarySensorDesc(key='door', field='x.com.samsung.da.doorState'),),
|
||||
rt_filter="oic.r.door",
|
||||
entities=(BinarySensorDesc(key="door", field="x.com.samsung.da.doorState"),),
|
||||
)
|
||||
resources = {
|
||||
'/door/cooler/0': {'x.com.samsung.da.doorState': 'Closed', 'rt': ['oic.r.door']},
|
||||
'/door/wine/0': {'x.com.samsung.da.doorState': 'Open', 'rt': ['oic.r.door']},
|
||||
"/door/cooler/0": {"x.com.samsung.da.doorState": "Closed", "rt": ["oic.r.door"]},
|
||||
"/door/wine/0": {"x.com.samsung.da.doorState": "Open", "rt": ["oic.r.door"]},
|
||||
}
|
||||
reg = {'/door/cooler/0': [cooler_cap]}
|
||||
reg = {"/door/cooler/0": [cooler_cap]}
|
||||
bound = discover(resources, reg, pattern_caps=[door_pattern])
|
||||
|
||||
hrefs = [b.href for b in bound]
|
||||
# exact cap claims /door/cooler/0
|
||||
assert '/door/cooler/0' in hrefs
|
||||
assert "/door/cooler/0" in hrefs
|
||||
# pattern cap claims /door/wine/0 (unmatched by registry)
|
||||
assert '/door/wine/0' in hrefs
|
||||
assert "/door/wine/0" in hrefs
|
||||
# /door/cooler/0 is not also claimed by the pattern cap
|
||||
cooler_bindings = [b for b in bound if b.href == '/door/cooler/0']
|
||||
cooler_bindings = [b for b in bound if b.href == "/door/cooler/0"]
|
||||
assert all(b.capability is cooler_cap for b in cooler_bindings)
|
||||
|
||||
|
||||
def test_discover_pattern_cap_skips_already_bound_href():
|
||||
"""Pattern cap must not bind an href already claimed by an exact-href cap."""
|
||||
exact_cap = Capability(
|
||||
href='/door/cooler/0',
|
||||
entities=(BinarySensorDesc(key='cooler_door', field='x.com.samsung.da.doorState'),),
|
||||
href="/door/cooler/0",
|
||||
entities=(BinarySensorDesc(key="cooler_door", field="x.com.samsung.da.doorState"),),
|
||||
)
|
||||
pattern = Capability(
|
||||
href=None,
|
||||
rt_filter='oic.r.door',
|
||||
entities=(BinarySensorDesc(key='generic_door', field='x.com.samsung.da.doorState'),),
|
||||
rt_filter="oic.r.door",
|
||||
entities=(BinarySensorDesc(key="generic_door", field="x.com.samsung.da.doorState"),),
|
||||
)
|
||||
resources = {'/door/cooler/0': {'x.com.samsung.da.doorState': 'Closed', 'rt': ['oic.r.door']}}
|
||||
reg = {'/door/cooler/0': [exact_cap]}
|
||||
resources = {"/door/cooler/0": {"x.com.samsung.da.doorState": "Closed", "rt": ["oic.r.door"]}}
|
||||
reg = {"/door/cooler/0": [exact_cap]}
|
||||
bound = discover(resources, reg, pattern_caps=[pattern])
|
||||
|
||||
# exactly one binding for /door/cooler/0 — the exact cap, not the pattern
|
||||
@@ -115,25 +122,15 @@ def test_discover_pattern_cap_skips_already_bound_href():
|
||||
|
||||
def test_discover_match_fn_filters_wrong_device():
|
||||
"""A cap with match_fn must not bind when its condition is not met."""
|
||||
oven_cap = Capability(
|
||||
href='/oven/vs/0',
|
||||
match_fn=lambda r, rs: '/oven/vs/0' in rs,
|
||||
entities=(BinarySensorDesc(key='oven_status', field='x.com.samsung.da.state'),),
|
||||
)
|
||||
# resources does NOT include /oven/vs/0 — match_fn should fail
|
||||
resources = {'/oven/vs/0': {'x.com.samsung.da.state': 'Ready'}}
|
||||
reg = {'/oven/vs/0': [oven_cap]}
|
||||
|
||||
# Without /oven/vs/0 present as a key in resources, match_fn should be False
|
||||
resources_no_oven = {'/other/vs/0': {'x.com.samsung.da.state': 'Ready'}}
|
||||
reg_no_oven = {}
|
||||
resources_no_oven = {"/other/vs/0": {"x.com.samsung.da.state": "Ready"}}
|
||||
# Put oven cap on a different href to test match_fn rejection
|
||||
oven_cap2 = Capability(
|
||||
href='/other/vs/0',
|
||||
match_fn=lambda r, rs: '/oven/vs/0' in rs,
|
||||
entities=(BinarySensorDesc(key='oven_status', field='x.com.samsung.da.state'),),
|
||||
href="/other/vs/0",
|
||||
match_fn=lambda r, rs: "/oven/vs/0" in rs,
|
||||
entities=(BinarySensorDesc(key="oven_status", field="x.com.samsung.da.state"),),
|
||||
)
|
||||
bound = discover(resources_no_oven, {'/other/vs/0': [oven_cap2]})
|
||||
bound = discover(resources_no_oven, {"/other/vs/0": [oven_cap2]})
|
||||
# match_fn returns False → no bindings
|
||||
assert bound == []
|
||||
|
||||
@@ -148,12 +145,12 @@ def test_discover_match_fn_decline_is_not_logged_as_gap():
|
||||
"""
|
||||
seen = []
|
||||
cap = Capability(
|
||||
href='/filter/vs/0',
|
||||
href="/filter/vs/0",
|
||||
match_fn=lambda rep, resources: False,
|
||||
entities=(BinarySensorDesc(key='filter', field='x.com.samsung.da.filterStatus'),),
|
||||
entities=(BinarySensorDesc(key="filter", field="x.com.samsung.da.filterStatus"),),
|
||||
)
|
||||
resources = {'/filter/vs/0': {'x.com.samsung.da.filterStatus': 'notused'}}
|
||||
bound = discover(resources, {'/filter/vs/0': [cap]}, log=seen.append)
|
||||
resources = {"/filter/vs/0": {"x.com.samsung.da.filterStatus": "notused"}}
|
||||
bound = discover(resources, {"/filter/vs/0": [cap]}, log=seen.append)
|
||||
assert bound == []
|
||||
assert seen == []
|
||||
|
||||
@@ -164,36 +161,36 @@ def test_discover_pattern_cap_reads_name_field():
|
||||
independent of the href-derived key (issue #27)."""
|
||||
cap = Capability(
|
||||
href=None,
|
||||
href_prefix='/icemaker/',
|
||||
name_field='x.com.samsung.da.iceMaker.name',
|
||||
entities=(BinarySensorDesc(key='enabled', field='x.com.samsung.da.iceMaker.state'),),
|
||||
href_prefix="/icemaker/",
|
||||
name_field="x.com.samsung.da.iceMaker.name",
|
||||
entities=(BinarySensorDesc(key="enabled", field="x.com.samsung.da.iceMaker.state"),),
|
||||
)
|
||||
resources = {
|
||||
'/icemaker/one/vs/0': {
|
||||
'x.com.samsung.da.iceMaker.state': 'On',
|
||||
'x.com.samsung.da.iceMaker.name': 'CUBED_ICE',
|
||||
"/icemaker/one/vs/0": {
|
||||
"x.com.samsung.da.iceMaker.state": "On",
|
||||
"x.com.samsung.da.iceMaker.name": "CUBED_ICE",
|
||||
},
|
||||
'/icemaker/two/vs/0': {
|
||||
'x.com.samsung.da.iceMaker.state': 'On',
|
||||
'x.com.samsung.da.iceMaker.name': 'ICE_BITES',
|
||||
"/icemaker/two/vs/0": {
|
||||
"x.com.samsung.da.iceMaker.state": "On",
|
||||
"x.com.samsung.da.iceMaker.name": "ICE_BITES",
|
||||
},
|
||||
}
|
||||
bound = discover(resources, {}, pattern_caps=[cap])
|
||||
names = {b.href: b.instance_name for b in bound}
|
||||
assert names == {
|
||||
'/icemaker/one/vs/0': 'Cubed Ice',
|
||||
'/icemaker/two/vs/0': 'Ice Bites',
|
||||
"/icemaker/one/vs/0": "Cubed Ice",
|
||||
"/icemaker/two/vs/0": "Ice Bites",
|
||||
}
|
||||
|
||||
|
||||
def test_discover_pattern_cap_name_field_absent_leaves_instance_name_none():
|
||||
cap = Capability(
|
||||
href=None,
|
||||
href_prefix='/icemaker/',
|
||||
name_field='x.com.samsung.da.iceMaker.name',
|
||||
entities=(BinarySensorDesc(key='enabled', field='x.com.samsung.da.iceMaker.state'),),
|
||||
href_prefix="/icemaker/",
|
||||
name_field="x.com.samsung.da.iceMaker.name",
|
||||
entities=(BinarySensorDesc(key="enabled", field="x.com.samsung.da.iceMaker.state"),),
|
||||
)
|
||||
resources = {'/icemaker/one/vs/0': {'x.com.samsung.da.iceMaker.state': 'On'}}
|
||||
resources = {"/icemaker/one/vs/0": {"x.com.samsung.da.iceMaker.state": "On"}}
|
||||
bound = discover(resources, {}, pattern_caps=[cap])
|
||||
assert bound[0].instance_name is None
|
||||
|
||||
@@ -201,13 +198,13 @@ def test_discover_pattern_cap_name_field_absent_leaves_instance_name_none():
|
||||
def test_discover_rt_filter_gates_binding():
|
||||
"""Cap with rt_filter must not bind a rep whose rt list does not match."""
|
||||
oven_mode_cap = Capability(
|
||||
href='/mode/vs/0',
|
||||
rt_filter='x.com.samsung.da.ovenMode',
|
||||
entities=(BinarySensorDesc(key='oven_mode', field='x.com.samsung.da.mode'),),
|
||||
href="/mode/vs/0",
|
||||
rt_filter="x.com.samsung.da.ovenMode",
|
||||
entities=(BinarySensorDesc(key="oven_mode", field="x.com.samsung.da.mode"),),
|
||||
)
|
||||
# rep has a different rt → should not bind
|
||||
resources = {'/mode/vs/0': {'rt': ['x.com.samsung.da.mode'], 'x.com.samsung.da.mode': 'Bake'}}
|
||||
bound = discover(resources, {'/mode/vs/0': [oven_mode_cap]})
|
||||
resources = {"/mode/vs/0": {"rt": ["x.com.samsung.da.mode"], "x.com.samsung.da.mode": "Bake"}}
|
||||
bound = discover(resources, {"/mode/vs/0": [oven_mode_cap]})
|
||||
assert bound == []
|
||||
|
||||
|
||||
@@ -218,10 +215,14 @@ def test_discover_tier_log_fires_for_no_entity_coverage_cap():
|
||||
caller its poll_tier. tier_log must still report it, or a consumer
|
||||
(the coordinator's hot/warm href lists) silently treats it as 'cold'
|
||||
regardless of what poll_tier the capability actually declares."""
|
||||
coverage_cap = Capability(href='/wind/strength/vs/0', poll_tier='warm')
|
||||
resources = {'/wind/strength/vs/0': {'x.com.samsung.da.modes': '0'}}
|
||||
coverage_cap = Capability(href="/wind/strength/vs/0", poll_tier="warm")
|
||||
resources = {"/wind/strength/vs/0": {"x.com.samsung.da.modes": "0"}}
|
||||
seen = []
|
||||
bound = discover(resources, {coverage_cap.href: [coverage_cap]},
|
||||
tier_log=lambda href, tier: seen.append((href, tier)))
|
||||
assert coverage_cap.href is not None
|
||||
bound = discover(
|
||||
resources,
|
||||
{coverage_cap.href: [coverage_cap]},
|
||||
tier_log=lambda href, tier: seen.append((href, tier)),
|
||||
)
|
||||
assert bound == []
|
||||
assert seen == [('/wind/strength/vs/0', 'warm')]
|
||||
assert seen == [("/wind/strength/vs/0", "warm")]
|
||||
@@ -4,44 +4,44 @@ The shared /course/vs/0 cycle-select machinery (parse_edit_course_list,
|
||||
cycle_options, cycle_write) is tested in test_laundry_capabilities.py; here we
|
||||
check the dishwasher wiring and its device-specific options.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.capabilities import dishwasher, laundry
|
||||
|
||||
|
||||
class TestCycleOptions:
|
||||
def _cycle(self):
|
||||
return next(e for e in dishwasher.CYCLE_OPTIONS.entities if e.key == 'cycle')
|
||||
return next(e for e in dishwasher.CYCLE_OPTIONS.entities if e.key == "cycle")
|
||||
|
||||
def test_cycle_desc_uses_shared_cycle_options(self):
|
||||
desc = self._cycle()
|
||||
assert desc.options is laundry.cycle_options
|
||||
assert desc.translation_key == 'dishwasher_cycle'
|
||||
assert desc.translation_key == "dishwasher_cycle"
|
||||
|
||||
def test_exists_only_when_edit_course_list_is_live(self):
|
||||
desc = self._cycle()
|
||||
assert desc.exists_fn({}, {}) is False
|
||||
assert desc.exists_fn({}, {'/wm/editcourse/vs/0': {}}) is False
|
||||
live = {'/wm/editcourse/vs/0': {'x.com.samsung.da.editCourseList': 'EditCourseList_0E'}}
|
||||
assert desc.exists_fn({}, {"/wm/editcourse/vs/0": {}}) is False
|
||||
live = {"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_0E"}}
|
||||
assert desc.exists_fn({}, live) is True
|
||||
|
||||
def test_cycle_write_uses_raw_code_directly(self):
|
||||
desc = self._cycle()
|
||||
rep = {'x.com.samsung.da.options': ['DeviceType_0001', 'Course_0E', 'GMT_04']}
|
||||
path, body = desc.write_fn('90', rep)
|
||||
assert path == ['course', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['Course_90']}
|
||||
rep = {"x.com.samsung.da.options": ["DeviceType_0001", "Course_0E", "GMT_04"]}
|
||||
path, body = desc.write_fn("90", rep)
|
||||
assert path == ["course", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["Course_90"]}
|
||||
|
||||
|
||||
class TestDishwasherOptions:
|
||||
def test_storm_wash_read_and_write(self):
|
||||
desc = next(e for e in dishwasher.CYCLE_OPTIONS.entities if e.key == 'storm_wash')
|
||||
assert desc.rep_fn({'x.com.samsung.da.options': ['StormWashZone_On']}) is True
|
||||
assert desc.rep_fn({'x.com.samsung.da.options': ['StormWashZone_Off']}) is False
|
||||
path, body = desc.write_fn('Off', {'x.com.samsung.da.options': ['StormWashZone_On']})
|
||||
assert path == ['course', 'vs', '0']
|
||||
assert 'StormWashZone_Off' in body['x.com.samsung.da.options']
|
||||
desc = next(e for e in dishwasher.CYCLE_OPTIONS.entities if e.key == "storm_wash")
|
||||
assert desc.rep_fn({"x.com.samsung.da.options": ["StormWashZone_On"]}) is True
|
||||
assert desc.rep_fn({"x.com.samsung.da.options": ["StormWashZone_Off"]}) is False
|
||||
path, body = desc.write_fn("Off", {"x.com.samsung.da.options": ["StormWashZone_On"]})
|
||||
assert path == ["course", "vs", "0"]
|
||||
assert "StormWashZone_Off" in body["x.com.samsung.da.options"]
|
||||
|
||||
def test_auto_release_exists_only_when_field_present(self):
|
||||
desc = next(e for e in dishwasher.CYCLE_OPTIONS.entities if e.key == 'auto_release_dry')
|
||||
assert desc.exists_fn({'x.com.samsung.da.options': []}, {}) is False
|
||||
assert desc.exists_fn(
|
||||
{'x.com.samsung.da.options': ['AutoDoorRelease_On']}, {}) is True
|
||||
desc = next(e for e in dishwasher.CYCLE_OPTIONS.entities if e.key == "auto_release_dry")
|
||||
assert desc.exists_fn({"x.com.samsung.da.options": []}, {}) is False
|
||||
assert desc.exists_fn({"x.com.samsung.da.options": ["AutoDoorRelease_On"]}, {}) is True
|
||||
@@ -1,17 +1,18 @@
|
||||
"""Tests for dryer support and washer/dryer consistency (issue #14)."""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.capabilities import dryer, ignored, laundry
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _dryer():
|
||||
resources = _load_device('dryer')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("dryer")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -24,7 +25,7 @@ def _state():
|
||||
|
||||
def test_dryer_model_resolves_to_dryer_registry():
|
||||
reg, _ = _dryer()
|
||||
assert reg is not None and reg.name == 'dryer'
|
||||
assert reg is not None and reg.name == "dryer"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -38,8 +39,16 @@ def test_no_unbound_hrefs():
|
||||
|
||||
def test_expected_entities_present():
|
||||
state = _state()
|
||||
for key in ('buzzer_sound', 'cycle', 'power_switch', 'child_lock',
|
||||
'remote_control', 'dry_level', 'wrinkle_prevent', 'energy_kwh'):
|
||||
for key in (
|
||||
"buzzer_sound",
|
||||
"cycle",
|
||||
"power_switch",
|
||||
"child_lock",
|
||||
"remote_control",
|
||||
"dry_level",
|
||||
"wrinkle_prevent",
|
||||
"energy_kwh",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
|
||||
@@ -47,15 +56,15 @@ def test_job_beginning_status_reads_current_status():
|
||||
"""The dump carries x.com.samsung.da.currentStatus (not the old
|
||||
jobBeginingStatus field the dryer descriptor used to read), so the sensor
|
||||
is populated instead of blank."""
|
||||
assert _state()['job_beginning_status'] == 'None' # the dump's currentStatus value
|
||||
assert _state()["job_beginning_status"] == "None" # the dump's currentStatus value
|
||||
|
||||
|
||||
def test_power_watts_gated_for_dead_sentinel():
|
||||
"""instantaneousPower is the dead '-500' sentinel on this dryer, so the
|
||||
misleading 0 W power sensor is suppressed; cumulative energy still shows."""
|
||||
state = _state()
|
||||
assert 'power_watts' not in state
|
||||
assert 'energy_kwh' in state
|
||||
assert "power_watts" not in state
|
||||
assert "energy_kwh" in state
|
||||
|
||||
|
||||
def test_course_bound_to_shared_course_vs_0():
|
||||
@@ -64,20 +73,20 @@ def test_course_bound_to_shared_course_vs_0():
|
||||
laundry.cycle_select) -- confirmed dryers report Table_03, matching
|
||||
the shipped dryer_cycle_table_03 translations, consistent with
|
||||
washer/dishwasher."""
|
||||
assert dryer.DRYER_COURSE.href == '/course/vs/0'
|
||||
desc = next(e for e in dryer.DRYER_COURSE.entities if e.key == 'cycle')
|
||||
assert dryer.DRYER_COURSE.href == "/course/vs/0"
|
||||
desc = next(e for e in dryer.DRYER_COURSE.entities if e.key == "cycle")
|
||||
assert callable(desc.translation_key)
|
||||
table_03 = {'/st/dryercourse/vs/0': {'x.com.samsung.da.st.courseTable': 'Table_03'}}
|
||||
assert desc.translation_key(table_03) == 'dryer_cycle_table_03'
|
||||
assert desc.translation_key({}) == 'cycle'
|
||||
table_03 = {"/st/dryercourse/vs/0": {"x.com.samsung.da.st.courseTable": "Table_03"}}
|
||||
assert desc.translation_key(table_03) == "dryer_cycle_table_03"
|
||||
assert desc.translation_key({}) == "cycle"
|
||||
assert desc.options is laundry.cycle_options
|
||||
rep = {'x.com.samsung.da.options': ['Course_16', 'GMT_02']}
|
||||
assert desc.rep_fn(rep) == '16'
|
||||
rep = {"x.com.samsung.da.options": ["Course_16", "GMT_02"]}
|
||||
assert desc.rep_fn(rep) == "16"
|
||||
|
||||
|
||||
def test_st_dryercourse_is_ignored():
|
||||
"""/st/dryercourse/vs/0 re-encodes the course exposed via /course/vs/0 and
|
||||
is globally ignored -- the mirror of /st/washercourse/vs/0."""
|
||||
ignored_hrefs = {c.href for c in ignored.IGNORED}
|
||||
assert '/st/dryercourse/vs/0' in ignored_hrefs
|
||||
assert '/st/washercourse/vs/0' in ignored_hrefs
|
||||
assert "/st/dryercourse/vs/0" in ignored_hrefs
|
||||
assert "/st/washercourse/vs/0" in ignored_hrefs
|
||||
@@ -4,19 +4,20 @@
|
||||
HA-free like the rest of the suite: exercises the registry, discovery/
|
||||
flatten, and the zone/dhw mode and temperature write contracts.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.entities import NumberDesc, SelectDesc, WaterHeaterDesc
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _ehs():
|
||||
resources = _load_device('ehs')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("ehs")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -38,7 +39,7 @@ def _desc(key):
|
||||
|
||||
def test_model_resolves_to_ehs_registry():
|
||||
reg, _ = _ehs()
|
||||
assert reg is not None and reg.name == 'ehs'
|
||||
assert reg is not None and reg.name == "ehs"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -53,72 +54,81 @@ def test_no_unbound_hrefs():
|
||||
|
||||
def test_expected_state_keys_present():
|
||||
state = _state()
|
||||
for key in ('zone_power', 'zone_mode', 'zone_temperature', 'zone_target_temperature',
|
||||
'water_heater', 'away_mode', 'mute_once', 'alarm_code', 'energy_kwh'):
|
||||
for key in (
|
||||
"zone_power",
|
||||
"zone_mode",
|
||||
"zone_temperature",
|
||||
"zone_target_temperature",
|
||||
"water_heater",
|
||||
"away_mode",
|
||||
"mute_once",
|
||||
"alarm_code",
|
||||
"energy_kwh",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
|
||||
def test_zone_temperature_reads_current_value():
|
||||
state = _state()
|
||||
assert state['zone_temperature'] == 30.0
|
||||
assert state["zone_temperature"] == 30.0
|
||||
|
||||
|
||||
def test_zone_target_temperature_reads_desired_value():
|
||||
state = _state()
|
||||
assert state['zone_target_temperature'] == 5.0
|
||||
assert state["zone_target_temperature"] == 5.0
|
||||
|
||||
|
||||
def test_zone_mode_reads_first_mode():
|
||||
state = _state()
|
||||
assert state['zone_mode'] == 'Cool'
|
||||
assert state["zone_mode"] == "Cool"
|
||||
|
||||
|
||||
def test_zone_mode_select_options_come_from_live_supported_modes():
|
||||
"""Options are read live from x.com.samsung.da.supportedModes, not a
|
||||
hardcoded tuple -- so a future firmware with a different mode set is
|
||||
handled automatically."""
|
||||
desc = _desc('zone_mode')
|
||||
desc = _desc("zone_mode")
|
||||
assert isinstance(desc, SelectDesc)
|
||||
assert desc.options_field == 'x.com.samsung.da.supportedModes'
|
||||
assert desc.options_field == "x.com.samsung.da.supportedModes"
|
||||
assert desc.options == ()
|
||||
|
||||
|
||||
def test_zone_mode_write_contract():
|
||||
desc = _desc('zone_mode')
|
||||
path, body = desc.write_fn('Heat', {})
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.modes': ['Heat']}
|
||||
desc = _desc("zone_mode")
|
||||
path, body = desc.write_fn("Heat", {})
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.modes": ["Heat"]}
|
||||
|
||||
|
||||
def test_zone_power_reads_off():
|
||||
state = _state()
|
||||
assert state['zone_power'] is False
|
||||
assert state["zone_power"] is False
|
||||
|
||||
|
||||
def test_zone_power_write_contract():
|
||||
desc = _desc('zone_power')
|
||||
path, body = desc.write_fn('On', {})
|
||||
assert path == ['power', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.power': 'On'}
|
||||
desc = _desc("zone_power")
|
||||
path, body = desc.write_fn("On", {})
|
||||
assert path == ["power", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.power": "On"}
|
||||
|
||||
|
||||
def test_zone_target_temperature_write_contract():
|
||||
desc = _desc('zone_target_temperature')
|
||||
desc = _desc("zone_target_temperature")
|
||||
assert isinstance(desc, NumberDesc)
|
||||
path, body = desc.write_fn('21.5', {})
|
||||
assert path == ['temperatures', 'indoor', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.desired': '21.5'}
|
||||
path, body = desc.write_fn("21.5", {})
|
||||
assert path == ["temperatures", "indoor", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.desired": "21.5"}
|
||||
|
||||
|
||||
def test_zone_target_temperature_bounds_read_live():
|
||||
"""min/max/step come from the device's own resource fields rather than
|
||||
a hardcoded constant -- see the adding-device-support skill's 'never
|
||||
hard-code the one dump's values' section."""
|
||||
desc = _desc('zone_target_temperature')
|
||||
rep = {'x.com.samsung.da.minimum': '5.0', 'x.com.samsung.da.maximum': '25.0'}
|
||||
desc = _desc("zone_target_temperature")
|
||||
rep = {"x.com.samsung.da.minimum": "5.0", "x.com.samsung.da.maximum": "25.0"}
|
||||
assert desc.native_min_fn(rep) == 5.0
|
||||
assert desc.native_max_fn(rep) == 25.0
|
||||
assert desc.step_fn({'x.com.samsung.da.increment': '0.5'}) == 0.5
|
||||
assert desc.step_fn({"x.com.samsung.da.increment": "0.5"}) == 0.5
|
||||
# No live field: falls back to a sane default rather than raising.
|
||||
assert desc.native_min_fn({}) == 5.0
|
||||
assert desc.native_max_fn({}) == 30.0
|
||||
@@ -129,16 +139,16 @@ def test_zone_target_temperature_bounds_fall_back_together():
|
||||
"""One end without the other is not a usable range: pairing a real
|
||||
device minimum with an invented default maximum looks plausible and is
|
||||
silently wrong, so a half-reported range falls back whole."""
|
||||
desc = _desc('zone_target_temperature')
|
||||
half = {'x.com.samsung.da.minimum': '10.0'}
|
||||
desc = _desc("zone_target_temperature")
|
||||
half = {"x.com.samsung.da.minimum": "10.0"}
|
||||
assert desc.native_min_fn(half) == 5.0
|
||||
assert desc.native_max_fn(half) == 30.0
|
||||
|
||||
|
||||
def test_zone_target_temperature_zero_increment_is_not_collapsed():
|
||||
"""`or` would turn a genuine 0 into the 0.5 default (issue #160)."""
|
||||
desc = _desc('zone_target_temperature')
|
||||
assert desc.step_fn({'x.com.samsung.da.increment': '0'}) == 0.0
|
||||
desc = _desc("zone_target_temperature")
|
||||
assert desc.step_fn({"x.com.samsung.da.increment": "0"}) == 0.0
|
||||
|
||||
|
||||
def test_water_heater_entity_is_bound():
|
||||
@@ -148,7 +158,7 @@ def test_water_heater_entity_is_bound():
|
||||
bound, _ = _bound()
|
||||
water_heaters = [b for b in bound if isinstance(b.desc, WaterHeaterDesc)]
|
||||
assert len(water_heaters) == 1
|
||||
assert water_heaters[0].href == '/mode/dhw/vs/0'
|
||||
assert water_heaters[0].href == "/mode/dhw/vs/0"
|
||||
|
||||
|
||||
def test_water_heater_reads_first_mode():
|
||||
@@ -156,23 +166,31 @@ def test_water_heater_reads_first_mode():
|
||||
the entity's current_operation is derived from -- see climate.py's
|
||||
_first_mode for the identical pattern on the AC side."""
|
||||
state = _state()
|
||||
assert state['water_heater'] == 'Eco'
|
||||
assert state["water_heater"] == "Eco"
|
||||
|
||||
|
||||
def test_water_heater_write_targets():
|
||||
"""DHW.entities[0].write_fn maps each (kind, value) command to the right
|
||||
vendor POST target and body -- power, mode and temperature only, no fan/
|
||||
swing/preset (the AC's climate.py has those; the DHW loop doesn't)."""
|
||||
write = _desc('water_heater').write_fn
|
||||
assert write(('power', True), {}) == (
|
||||
['power', 'dhw', 'vs', '0'], {'x.com.samsung.da.power': 'On'})
|
||||
assert write(('power', False), {}) == (
|
||||
['power', 'dhw', 'vs', '0'], {'x.com.samsung.da.power': 'Off'})
|
||||
assert write(('mode', 'Force'), {}) == (
|
||||
['mode', 'dhw', 'vs', '0'], {'x.com.samsung.da.modes': ['Force']})
|
||||
assert write(('temperature', 45.0), {}) == (
|
||||
['temperatures', 'dhw', 'vs', '0'], {'x.com.samsung.da.desired': '45.0'})
|
||||
assert write(('bogus', 1), {}) is None
|
||||
write = _desc("water_heater").write_fn
|
||||
assert write(("power", True), {}) == (
|
||||
["power", "dhw", "vs", "0"],
|
||||
{"x.com.samsung.da.power": "On"},
|
||||
)
|
||||
assert write(("power", False), {}) == (
|
||||
["power", "dhw", "vs", "0"],
|
||||
{"x.com.samsung.da.power": "Off"},
|
||||
)
|
||||
assert write(("mode", "Force"), {}) == (
|
||||
["mode", "dhw", "vs", "0"],
|
||||
{"x.com.samsung.da.modes": ["Force"]},
|
||||
)
|
||||
assert write(("temperature", 45.0), {}) == (
|
||||
["temperatures", "dhw", "vs", "0"],
|
||||
{"x.com.samsung.da.desired": "45.0"},
|
||||
)
|
||||
assert write(("bogus", 1), {}) is None
|
||||
|
||||
|
||||
def test_dhw_power_and_temperature_declared_as_coverage():
|
||||
@@ -181,7 +199,7 @@ def test_dhw_power_and_temperature_declared_as_coverage():
|
||||
their own entities -- declared as no-entity coverage caps so discover()
|
||||
reports no gap, same pattern as the AC's CLIMATE_CONSUMED_HREFS."""
|
||||
reg, _ = _ehs()
|
||||
for href in ('/power/dhw/vs/0', '/temperatures/dhw/vs/0'):
|
||||
for href in ("/power/dhw/vs/0", "/temperatures/dhw/vs/0"):
|
||||
caps = reg.capabilities.get(href)
|
||||
assert caps, href
|
||||
assert all(c.entities == () for c in caps), href
|
||||
@@ -189,11 +207,11 @@ def test_dhw_power_and_temperature_declared_as_coverage():
|
||||
|
||||
def test_away_mode_reads_off():
|
||||
state = _state()
|
||||
assert state['away_mode'] is False
|
||||
assert state["away_mode"] is False
|
||||
|
||||
|
||||
def test_away_mode_write_contract():
|
||||
desc = _desc('away_mode')
|
||||
path, body = desc.write_fn('On', {})
|
||||
assert path == ['option', 'outgoing', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.away': 'On'}
|
||||
desc = _desc("away_mode")
|
||||
path, body = desc.write_fn("On", {})
|
||||
assert path == ["option", "outgoing", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.away": "On"}
|
||||
@@ -1,20 +1,25 @@
|
||||
import pytest
|
||||
from tests.conftest import _load_device
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name,expected_type', [
|
||||
('dishwasher', 'dishwasher'),
|
||||
('refrigerator', 'refrigerator'),
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"name,expected_type",
|
||||
[
|
||||
("dishwasher", "dishwasher"),
|
||||
("refrigerator", "refrigerator"),
|
||||
],
|
||||
)
|
||||
def test_full_pipeline_v2(name, expected_type):
|
||||
resources = _load_device(name)
|
||||
|
||||
info = resources['/information/vs/0']
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
assert reg is not None
|
||||
assert reg.name == expected_type
|
||||
|
||||
+30
-18
@@ -1,37 +1,49 @@
|
||||
from custom_components.localthings.registry.entities import (
|
||||
SensorDesc, BinarySensorDesc, SelectDesc, SwitchDesc, ButtonDesc,
|
||||
NumberDesc, TimeDesc, ClimateDesc, FanDesc, PLATFORM_OF,
|
||||
PLATFORM_OF,
|
||||
BinarySensorDesc,
|
||||
ButtonDesc,
|
||||
ClimateDesc,
|
||||
FanDesc,
|
||||
NumberDesc,
|
||||
SelectDesc,
|
||||
SensorDesc,
|
||||
SwitchDesc,
|
||||
TimeDesc,
|
||||
)
|
||||
|
||||
|
||||
def test_value_fn_defaults_to_identity():
|
||||
d = SensorDesc(key='power', field='x.com.samsung.da.instantaneousPower')
|
||||
d = SensorDesc(key="power", field="x.com.samsung.da.instantaneousPower")
|
||||
assert d.value_fn(42) == 42
|
||||
|
||||
|
||||
def test_descriptions_are_frozen():
|
||||
d = SensorDesc(key='power', field='f')
|
||||
d = SensorDesc(key="power", field="f")
|
||||
try:
|
||||
d.key = 'other'
|
||||
d.key = "other"
|
||||
except Exception as e:
|
||||
assert 'frozen' in str(type(e)).lower() or 'cannot' in str(e).lower()
|
||||
assert "frozen" in str(type(e)).lower() or "cannot" in str(e).lower()
|
||||
else:
|
||||
raise AssertionError("expected frozen dataclass")
|
||||
|
||||
|
||||
def test_platform_mapping_covers_all_subclasses():
|
||||
assert PLATFORM_OF[SensorDesc] == 'sensor'
|
||||
assert PLATFORM_OF[BinarySensorDesc] == 'binary_sensor'
|
||||
assert PLATFORM_OF[SelectDesc] == 'select'
|
||||
assert PLATFORM_OF[SwitchDesc] == 'switch'
|
||||
assert PLATFORM_OF[ButtonDesc] == 'button'
|
||||
assert PLATFORM_OF[NumberDesc] == 'number'
|
||||
assert PLATFORM_OF[TimeDesc] == 'time'
|
||||
assert PLATFORM_OF[ClimateDesc] == 'climate'
|
||||
assert PLATFORM_OF[FanDesc] == 'fan'
|
||||
assert PLATFORM_OF[SensorDesc] == "sensor"
|
||||
assert PLATFORM_OF[BinarySensorDesc] == "binary_sensor"
|
||||
assert PLATFORM_OF[SelectDesc] == "select"
|
||||
assert PLATFORM_OF[SwitchDesc] == "switch"
|
||||
assert PLATFORM_OF[ButtonDesc] == "button"
|
||||
assert PLATFORM_OF[NumberDesc] == "number"
|
||||
assert PLATFORM_OF[TimeDesc] == "time"
|
||||
assert PLATFORM_OF[ClimateDesc] == "climate"
|
||||
assert PLATFORM_OF[FanDesc] == "fan"
|
||||
|
||||
|
||||
def test_select_carries_options_and_write_fn():
|
||||
d = SelectDesc(key='sound', field='mode', options=('voice', 'tone', 'mute'),
|
||||
write_fn=lambda p, rep: (['settings', 'sound', 'mode', 'vs', '0'], {'mode': p}))
|
||||
assert d.write_fn('tone', {}) == (['settings', 'sound', 'mode', 'vs', '0'], {'mode': 'tone'})
|
||||
d = SelectDesc(
|
||||
key="sound",
|
||||
field="mode",
|
||||
options=("voice", "tone", "mute"),
|
||||
write_fn=lambda p, rep: (["settings", "sound", "mode", "vs", "0"], {"mode": p}),
|
||||
)
|
||||
assert d.write_fn("tone", {}) == (["settings", "sound", "mode", "vs", "0"], {"mode": "tone"})
|
||||
+17
-13
@@ -7,6 +7,7 @@ normal, no-alarm state (fridge._active_alarm_codes), so excluding the
|
||||
entity there would silently drop working sensors on first-poll timing,
|
||||
not just fix phantom ones.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.entity import _is_included
|
||||
from custom_components.localthings.registry.capability import Capability
|
||||
from custom_components.localthings.registry.discovery import BoundEntity
|
||||
@@ -35,21 +36,21 @@ class TestDefaultFieldGate:
|
||||
"""No explicit exists_fn -- the field-presence default in entity.py."""
|
||||
|
||||
def _bound(self):
|
||||
return _bound(SensorDesc(key='x', field='x.com.samsung.da.value'), '/x/vs/0')
|
||||
return _bound(SensorDesc(key="x", field="x.com.samsung.da.value"), "/x/vs/0")
|
||||
|
||||
def test_included_when_field_present(self):
|
||||
bound = self._bound()
|
||||
coord = _FakeCoordinator({'/x/vs/0': {'x.com.samsung.da.value': '1'}})
|
||||
coord = _FakeCoordinator({"/x/vs/0": {"x.com.samsung.da.value": "1"}})
|
||||
assert _is_included(bound, coord) is True
|
||||
|
||||
def test_excluded_when_field_absent_from_populated_rep(self):
|
||||
bound = self._bound()
|
||||
coord = _FakeCoordinator({'/x/vs/0': {'x.com.samsung.da.other': '1'}})
|
||||
coord = _FakeCoordinator({"/x/vs/0": {"x.com.samsung.da.other": "1"}})
|
||||
assert _is_included(bound, coord) is False
|
||||
|
||||
def test_included_on_true_stub(self):
|
||||
bound = self._bound()
|
||||
coord = _FakeCoordinator({'/x/vs/0': {'href': '/x/vs/0'}})
|
||||
coord = _FakeCoordinator({"/x/vs/0": {"href": "/x/vs/0"}})
|
||||
assert _is_included(bound, coord) is True
|
||||
|
||||
def test_included_on_genuinely_empty_rep(self):
|
||||
@@ -59,7 +60,7 @@ class TestDefaultFieldGate:
|
||||
exists_fn (e.g. common.ENERGY_METER) opts into excluding on
|
||||
confirmed-empty, after verifying that's actually safe for its field."""
|
||||
bound = self._bound()
|
||||
coord = _FakeCoordinator({'/x/vs/0': {}})
|
||||
coord = _FakeCoordinator({"/x/vs/0": {}})
|
||||
assert _is_included(bound, coord) is True
|
||||
|
||||
def test_excluded_when_href_missing_from_resources(self):
|
||||
@@ -70,18 +71,21 @@ class TestDefaultFieldGate:
|
||||
|
||||
class TestExplicitExistsFnGate:
|
||||
def test_explicit_exists_fn_overrides_default_field_gate(self):
|
||||
desc = SensorDesc(key='x', field='x.com.samsung.da.value',
|
||||
exists_fn=lambda rep, resources: rep.get('flag') is True)
|
||||
bound = _bound(desc, '/x/vs/0')
|
||||
coord = _FakeCoordinator({'/x/vs/0': {'flag': True}})
|
||||
desc = SensorDesc(
|
||||
key="x",
|
||||
field="x.com.samsung.da.value",
|
||||
exists_fn=lambda rep, resources: rep.get("flag") is True,
|
||||
)
|
||||
bound = _bound(desc, "/x/vs/0")
|
||||
coord = _FakeCoordinator({"/x/vs/0": {"flag": True}})
|
||||
assert _is_included(bound, coord) is True
|
||||
coord = _FakeCoordinator({'/x/vs/0': {'flag': False, 'x.com.samsung.da.value': '1'}})
|
||||
coord = _FakeCoordinator({"/x/vs/0": {"flag": False, "x.com.samsung.da.value": "1"}})
|
||||
assert _is_included(bound, coord) is False
|
||||
|
||||
|
||||
class TestNoFieldEntities:
|
||||
def test_rep_fn_entity_always_included(self):
|
||||
desc = SensorDesc(key='x', rep_fn=lambda rep: rep.get('x.com.samsung.da.value'))
|
||||
bound = _bound(desc, '/x/vs/0')
|
||||
coord = _FakeCoordinator({'/x/vs/0': {}})
|
||||
desc = SensorDesc(key="x", rep_fn=lambda rep: rep.get("x.com.samsung.da.value"))
|
||||
bound = _bound(desc, "/x/vs/0")
|
||||
coord = _FakeCoordinator({"/x/vs/0": {}})
|
||||
assert _is_included(bound, coord) is True
|
||||
+23
-18
@@ -1,4 +1,5 @@
|
||||
"""Tests for translated entity naming and dynamic instance placeholders."""
|
||||
|
||||
from custom_components.localthings.entity import LocalThingsEntity
|
||||
from custom_components.localthings.registry.capability import Capability
|
||||
from custom_components.localthings.registry.discovery import BoundEntity
|
||||
@@ -6,17 +7,22 @@ from custom_components.localthings.registry.entities import BinarySensorDesc
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-SERIAL'
|
||||
device_serial = "TEST-SERIAL"
|
||||
|
||||
def __init__(self, last_resources=None):
|
||||
self.last_resources = last_resources or {}
|
||||
|
||||
|
||||
def _make_entity(desc, href='/x/vs/0', key_override=None, instance='', instance_name=None):
|
||||
def _make_entity(desc, href="/x/vs/0", key_override=None, instance="", instance_name=None):
|
||||
capability = Capability(href=href, entities=(desc,))
|
||||
bound = BoundEntity(href=href, capability=capability, desc=desc,
|
||||
instance=instance, key_override=key_override,
|
||||
instance_name=instance_name)
|
||||
bound = BoundEntity(
|
||||
href=href,
|
||||
capability=capability,
|
||||
desc=desc,
|
||||
instance=instance,
|
||||
key_override=key_override,
|
||||
instance_name=instance_name,
|
||||
)
|
||||
return LocalThingsEntity(_FakeCoordinator(), bound)
|
||||
|
||||
|
||||
@@ -26,26 +32,25 @@ def test_descriptor_key_is_the_default_translation_key():
|
||||
Nothing sets _attr_name: that would take precedence over HA's
|
||||
translation catalog and make the entity untranslatable.
|
||||
"""
|
||||
desc = BinarySensorDesc(key='enabled')
|
||||
entity = _make_entity(desc, instance_name='Cubed Ice')
|
||||
assert entity.translation_key == 'enabled'
|
||||
assert not hasattr(entity, '_attr_name')
|
||||
desc = BinarySensorDesc(key="enabled")
|
||||
entity = _make_entity(desc, instance_name="Cubed Ice")
|
||||
assert entity.translation_key == "enabled"
|
||||
assert not hasattr(entity, "_attr_name")
|
||||
|
||||
|
||||
def test_device_instance_name_becomes_translation_placeholder():
|
||||
desc = BinarySensorDesc(
|
||||
key='enabled', translation_key='instance_enabled', use_instance_name=True
|
||||
key="enabled", translation_key="instance_enabled", use_instance_name=True
|
||||
)
|
||||
entity = _make_entity(desc, key_override='icemaker_one_enabled',
|
||||
instance_name='Cubed Ice')
|
||||
assert entity.translation_key == 'instance_enabled'
|
||||
assert entity.translation_placeholders == {'instance_name': 'Cubed Ice'}
|
||||
assert not hasattr(entity, '_attr_name')
|
||||
entity = _make_entity(desc, key_override="icemaker_one_enabled", instance_name="Cubed Ice")
|
||||
assert entity.translation_key == "instance_enabled"
|
||||
assert entity.translation_placeholders == {"instance_name": "Cubed Ice"}
|
||||
assert not hasattr(entity, "_attr_name")
|
||||
|
||||
|
||||
def test_href_instance_name_becomes_translation_placeholder():
|
||||
desc = BinarySensorDesc(
|
||||
key='enabled', translation_key='instance_enabled', use_instance_name=True
|
||||
key="enabled", translation_key="instance_enabled", use_instance_name=True
|
||||
)
|
||||
entity = _make_entity(desc, key_override='icemaker_one_enabled')
|
||||
assert entity.translation_placeholders == {'instance_name': 'Icemaker One'}
|
||||
entity = _make_entity(desc, key_override="icemaker_one_enabled")
|
||||
assert entity.translation_placeholders == {"instance_name": "Icemaker One"}
|
||||
@@ -4,12 +4,11 @@ def test_dishwasher_resources_loaded(dishwasher_resources):
|
||||
# batch responses (OCF carries rt at the collection-entry level only).
|
||||
# Verify the fixture contains dict values (including empty reps which are
|
||||
# valid batch entries for resources that temporarily have no state).
|
||||
non_dicts = [h for h, rep in dishwasher_resources.items()
|
||||
if not isinstance(rep, dict)]
|
||||
non_dicts = [h for h, rep in dishwasher_resources.items() if not isinstance(rep, dict)]
|
||||
assert not non_dicts, f"resources with non-dict rep: {non_dicts}"
|
||||
|
||||
|
||||
def test_fridge_has_autofill(fridge_resources):
|
||||
assert '/autofill/vs/0' in fridge_resources
|
||||
assert "/autofill/vs/0" in fridge_resources
|
||||
# Batch reps do not carry 'rt'; check for the actual autofill field.
|
||||
assert 'x.com.samsung.da.autofill' in fridge_resources['/autofill/vs/0']
|
||||
assert "x.com.samsung.da.autofill" in fridge_resources["/autofill/vs/0"]
|
||||
+194
-156
@@ -1,4 +1,7 @@
|
||||
"""Tests for fridge-specific capabilities."""
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from custom_components.localthings.registry.capabilities import fridge
|
||||
|
||||
|
||||
@@ -9,15 +12,15 @@ class TestTempCurrentGeneric:
|
||||
|
||||
def test_unit_reads_celsius(self):
|
||||
desc = fridge.TEMP_CURRENT_GENERIC.entities[0]
|
||||
assert desc.unit_fn({'temperature': 3.0, 'units': 'C'}) == '°C'
|
||||
assert desc.unit_fn({"temperature": 3.0, "units": "C"}) == "°C"
|
||||
|
||||
def test_unit_reads_fahrenheit(self):
|
||||
desc = fridge.TEMP_CURRENT_GENERIC.entities[0]
|
||||
assert desc.unit_fn({'temperature': 5.0, 'units': 'F'}) == '°F'
|
||||
assert desc.unit_fn({"temperature": 5.0, "units": "F"}) == "°F"
|
||||
|
||||
def test_unit_defaults_to_fahrenheit_when_missing(self):
|
||||
desc = fridge.TEMP_CURRENT_GENERIC.entities[0]
|
||||
assert desc.unit_fn({'temperature': 5.0}) == '°F'
|
||||
assert desc.unit_fn({"temperature": 5.0}) == "°F"
|
||||
|
||||
|
||||
class TestDoorGeneric:
|
||||
@@ -29,24 +32,24 @@ class TestDoorGeneric:
|
||||
|
||||
def test_reads_bare_open_state(self):
|
||||
desc = fridge.DOOR_GENERIC.entities[0]
|
||||
assert desc.rep_fn({'openState': 'Open'}) is True
|
||||
assert desc.rep_fn({'openState': 'Close'}) is False
|
||||
assert desc.rep_fn({"openState": "Open"}) is True
|
||||
assert desc.rep_fn({"openState": "Close"}) is False
|
||||
|
||||
def test_reads_vendor_prefixed_open_state(self):
|
||||
desc = fridge.DOOR_GENERIC.entities[0]
|
||||
assert desc.rep_fn({'x.com.samsung.da.openState': 'Open'}) is True
|
||||
assert desc.rep_fn({'x.com.samsung.da.openState': 'Close'}) is False
|
||||
assert desc.rep_fn({"x.com.samsung.da.openState": "Open"}) is True
|
||||
assert desc.rep_fn({"x.com.samsung.da.openState": "Close"}) is False
|
||||
|
||||
def test_prefers_bare_field_when_both_present(self):
|
||||
desc = fridge.DOOR_GENERIC.entities[0]
|
||||
rep = {'openState': 'Open', 'x.com.samsung.da.openState': 'Close'}
|
||||
rep = {"openState": "Open", "x.com.samsung.da.openState": "Close"}
|
||||
assert desc.rep_fn(rep) is True
|
||||
|
||||
|
||||
class TestTempSetpointGeneric:
|
||||
def test_unit_reads_celsius(self):
|
||||
desc = fridge.TEMP_SETPOINT.entities[0]
|
||||
assert desc.unit_fn({'temperature': -19.0, 'units': 'C'}) == '°C'
|
||||
assert desc.unit_fn({"temperature": -19.0, "units": "C"}) == "°C"
|
||||
|
||||
|
||||
class TestTemperaturesFallback:
|
||||
@@ -54,30 +57,46 @@ class TestTemperaturesFallback:
|
||||
x.com.samsung.da.unit ('Celsius'/'Fahrenheit')."""
|
||||
|
||||
def test_freezer_unit_celsius(self):
|
||||
desc = next(e for e in fridge.TEMPERATURES_FALLBACK.entities
|
||||
if e.key == 'freezer_temperature')
|
||||
rep = {'x.com.samsung.da.items': [
|
||||
{'x.com.samsung.da.description': 'Freezer', 'x.com.samsung.da.current': '-19',
|
||||
'x.com.samsung.da.unit': 'Celsius'},
|
||||
{'x.com.samsung.da.description': 'Fridge', 'x.com.samsung.da.current': '3',
|
||||
'x.com.samsung.da.unit': 'Celsius'},
|
||||
]}
|
||||
assert desc.unit_fn(rep) == '°C'
|
||||
assert desc.value_fn(rep['x.com.samsung.da.items']) == -19
|
||||
desc = next(
|
||||
e for e in fridge.TEMPERATURES_FALLBACK.entities if e.key == "freezer_temperature"
|
||||
)
|
||||
rep = {
|
||||
"x.com.samsung.da.items": [
|
||||
{
|
||||
"x.com.samsung.da.description": "Freezer",
|
||||
"x.com.samsung.da.current": "-19",
|
||||
"x.com.samsung.da.unit": "Celsius",
|
||||
},
|
||||
{
|
||||
"x.com.samsung.da.description": "Fridge",
|
||||
"x.com.samsung.da.current": "3",
|
||||
"x.com.samsung.da.unit": "Celsius",
|
||||
},
|
||||
]
|
||||
}
|
||||
assert desc.unit_fn(rep) == "°C"
|
||||
assert desc.value_fn(rep["x.com.samsung.da.items"]) == -19
|
||||
|
||||
def test_fridge_unit_fahrenheit(self):
|
||||
desc = next(e for e in fridge.TEMPERATURES_FALLBACK.entities
|
||||
if e.key == 'fridge_temperature')
|
||||
rep = {'x.com.samsung.da.items': [
|
||||
{'x.com.samsung.da.description': 'Fridge', 'x.com.samsung.da.current': '37',
|
||||
'x.com.samsung.da.unit': 'Fahrenheit'},
|
||||
]}
|
||||
assert desc.unit_fn(rep) == '°F'
|
||||
desc = next(
|
||||
e for e in fridge.TEMPERATURES_FALLBACK.entities if e.key == "fridge_temperature"
|
||||
)
|
||||
rep = {
|
||||
"x.com.samsung.da.items": [
|
||||
{
|
||||
"x.com.samsung.da.description": "Fridge",
|
||||
"x.com.samsung.da.current": "37",
|
||||
"x.com.samsung.da.unit": "Fahrenheit",
|
||||
},
|
||||
]
|
||||
}
|
||||
assert desc.unit_fn(rep) == "°F"
|
||||
|
||||
def test_unit_defaults_to_fahrenheit_when_item_missing(self):
|
||||
desc = next(e for e in fridge.TEMPERATURES_FALLBACK.entities
|
||||
if e.key == 'freezer_temperature')
|
||||
assert desc.unit_fn({'x.com.samsung.da.items': []}) == '°F'
|
||||
desc = next(
|
||||
e for e in fridge.TEMPERATURES_FALLBACK.entities if e.key == "freezer_temperature"
|
||||
)
|
||||
assert desc.unit_fn({"x.com.samsung.da.items": []}) == "°F"
|
||||
|
||||
|
||||
class TestDefrostBlockStatus:
|
||||
@@ -87,12 +106,12 @@ class TestDefrostBlockStatus:
|
||||
|
||||
def test_key_and_name_reflect_active_defrosting(self):
|
||||
desc = fridge.DEFROST_BLOCK_STATUS.entities[0]
|
||||
assert desc.key == 'defrost_active'
|
||||
assert desc.key == "defrost_active"
|
||||
|
||||
def test_value_fn(self):
|
||||
desc = fridge.DEFROST_BLOCK_STATUS.entities[0]
|
||||
assert desc.value_fn(['DEFROST_BLOCK_ON']) is True
|
||||
assert desc.value_fn(['DEFROST_BLOCK_OFF']) is False
|
||||
assert desc.value_fn(["DEFROST_BLOCK_ON"]) is True
|
||||
assert desc.value_fn(["DEFROST_BLOCK_OFF"]) is False
|
||||
|
||||
|
||||
class TestRefrigerationFallback:
|
||||
@@ -102,29 +121,27 @@ class TestRefrigerationFallback:
|
||||
(defrost) that has no vs-href equivalent."""
|
||||
|
||||
def test_href(self):
|
||||
assert fridge.REFRIGERATION_FALLBACK.href == '/refrigeration/0'
|
||||
assert fridge.REFRIGERATION_FALLBACK.href == "/refrigeration/0"
|
||||
|
||||
def test_defrost_active_is_fallback_of_defrost_block_status(self):
|
||||
# Duplicates DEFROST_BLOCK_STATUS's defrost_active
|
||||
# (/defrost/block/vs/0) -- only a true fallback when that richer
|
||||
# href is absent (issue #7's device: /refrigeration/0 only).
|
||||
desc = next(e for e in fridge.REFRIGERATION_FALLBACK.entities
|
||||
if e.key == 'defrost_active')
|
||||
desc = next(e for e in fridge.REFRIGERATION_FALLBACK.entities if e.key == "defrost_active")
|
||||
assert desc.value_fn(True) is True
|
||||
assert desc.value_fn(False) is False
|
||||
assert desc.exists_fn({}, {'/refrigeration/0': {}}) is True
|
||||
assert desc.exists_fn(
|
||||
{}, {'/refrigeration/0': {}, '/defrost/block/vs/0': {}}) is False
|
||||
assert desc.exists_fn({}, {"/refrigeration/0": {}}) is True
|
||||
assert desc.exists_fn({}, {"/refrigeration/0": {}, "/defrost/block/vs/0": {}}) is False
|
||||
|
||||
def test_rapid_switches_hidden_when_vs_href_present(self):
|
||||
for key in ('rapid_fridge', 'rapid_freezing'):
|
||||
for key in ("rapid_fridge", "rapid_freezing"):
|
||||
desc = next(e for e in fridge.REFRIGERATION_FALLBACK.entities if e.key == key)
|
||||
assert desc.exists_fn({}, {'/refrigeration/vs/0': {}, '/refrigeration/0': {}}) is False
|
||||
assert desc.exists_fn({}, {"/refrigeration/vs/0": {}, "/refrigeration/0": {}}) is False
|
||||
|
||||
def test_rapid_switches_shown_when_vs_href_absent(self):
|
||||
for key in ('rapid_fridge', 'rapid_freezing'):
|
||||
for key in ("rapid_fridge", "rapid_freezing"):
|
||||
desc = next(e for e in fridge.REFRIGERATION_FALLBACK.entities if e.key == key)
|
||||
assert desc.exists_fn({}, {'/refrigeration/0': {}}) is True
|
||||
assert desc.exists_fn({}, {"/refrigeration/0": {}}) is True
|
||||
|
||||
|
||||
class TestFlexZone:
|
||||
@@ -136,32 +153,42 @@ class TestFlexZone:
|
||||
|
||||
def test_reads_rf9000_prefix(self):
|
||||
rep = {
|
||||
'x.com.samsung.da.modes': ['CV_TTYPE_RF9000A_BEVERAGE', 'WATERFILTER_DISABLE'],
|
||||
'x.com.samsung.da.supportedOptions': [
|
||||
'CV_TTYPE_RF9000A_FREEZE', 'CV_TTYPE_RF9000A_BEVERAGE'],
|
||||
"x.com.samsung.da.modes": ["CV_TTYPE_RF9000A_BEVERAGE", "WATERFILTER_DISABLE"],
|
||||
"x.com.samsung.da.supportedOptions": [
|
||||
"CV_TTYPE_RF9000A_FREEZE",
|
||||
"CV_TTYPE_RF9000A_BEVERAGE",
|
||||
],
|
||||
}
|
||||
assert fridge._flex_zone_current(rep) == 'CV_TTYPE_RF9000A_BEVERAGE'
|
||||
assert fridge._flex_zone_current(rep) == "CV_TTYPE_RF9000A_BEVERAGE"
|
||||
|
||||
def test_reads_cv_fdr_prefix(self):
|
||||
rep = {
|
||||
'x.com.samsung.da.modes': ['CVN_CONVERTIBLE_ZONE', 'CV_FDR_MEAT', 'WATERFILTER_ENABLE'],
|
||||
'x.com.samsung.da.supportedOptions': [
|
||||
'CV_FDR_WINE', 'CV_FDR_DELI', 'CV_FDR_BEVERAGE', 'CV_FDR_MEAT'],
|
||||
"x.com.samsung.da.modes": ["CVN_CONVERTIBLE_ZONE", "CV_FDR_MEAT", "WATERFILTER_ENABLE"],
|
||||
"x.com.samsung.da.supportedOptions": [
|
||||
"CV_FDR_WINE",
|
||||
"CV_FDR_DELI",
|
||||
"CV_FDR_BEVERAGE",
|
||||
"CV_FDR_MEAT",
|
||||
],
|
||||
}
|
||||
assert fridge._flex_zone_current(rep) == 'CV_FDR_MEAT'
|
||||
assert fridge._flex_zone_current(rep) == "CV_FDR_MEAT"
|
||||
|
||||
def test_write_replaces_rather_than_duplicates(self):
|
||||
rep = {
|
||||
'x.com.samsung.da.modes': ['CVN_CONVERTIBLE_ZONE', 'CV_FDR_MEAT', 'WATERFILTER_ENABLE'],
|
||||
'x.com.samsung.da.supportedOptions': [
|
||||
'CV_FDR_WINE', 'CV_FDR_DELI', 'CV_FDR_BEVERAGE', 'CV_FDR_MEAT'],
|
||||
"x.com.samsung.da.modes": ["CVN_CONVERTIBLE_ZONE", "CV_FDR_MEAT", "WATERFILTER_ENABLE"],
|
||||
"x.com.samsung.da.supportedOptions": [
|
||||
"CV_FDR_WINE",
|
||||
"CV_FDR_DELI",
|
||||
"CV_FDR_BEVERAGE",
|
||||
"CV_FDR_MEAT",
|
||||
],
|
||||
}
|
||||
path, payload = fridge._flex_zone_write('CV_FDR_WINE', rep)
|
||||
assert path == ['mode', 'vs', '0']
|
||||
modes = payload['x.com.samsung.da.modes']
|
||||
assert modes.count('CV_FDR_WINE') == 1
|
||||
assert 'CV_FDR_MEAT' not in modes
|
||||
assert 'CVN_CONVERTIBLE_ZONE' in modes and 'WATERFILTER_ENABLE' in modes
|
||||
path, payload = fridge._flex_zone_write("CV_FDR_WINE", rep)
|
||||
assert path == ["mode", "vs", "0"]
|
||||
modes = payload["x.com.samsung.da.modes"]
|
||||
assert modes.count("CV_FDR_WINE") == 1
|
||||
assert "CV_FDR_MEAT" not in modes
|
||||
assert "CVN_CONVERTIBLE_ZONE" in modes and "WATERFILTER_ENABLE" in modes
|
||||
|
||||
def test_exists_only_when_a_current_value_resolves(self):
|
||||
"""Issue #26's kimchi-refrigerator family also populates /mode/vs/0's
|
||||
@@ -170,16 +197,15 @@ class TestFlexZone:
|
||||
the entity used to bind anyway (supportedOptions is nonempty) and
|
||||
get stuck on "unknown" forever."""
|
||||
no_overlap_rep = {
|
||||
'x.com.samsung.da.modes': ['KIMCHIT_STORAGE_FREEZER_NORMAL'],
|
||||
'x.com.samsung.da.supportedOptions': [
|
||||
'KIMCHIT_STORAGE_FREEZER_NORMAL_[0]:[0]'],
|
||||
"x.com.samsung.da.modes": ["KIMCHIT_STORAGE_FREEZER_NORMAL"],
|
||||
"x.com.samsung.da.supportedOptions": ["KIMCHIT_STORAGE_FREEZER_NORMAL_[0]:[0]"],
|
||||
}
|
||||
desc = fridge.FLEX_ZONE.entities[0]
|
||||
assert desc.exists_fn(no_overlap_rep, {}) is False
|
||||
|
||||
overlap_rep = {
|
||||
'x.com.samsung.da.modes': ['CV_FDR_MEAT'],
|
||||
'x.com.samsung.da.supportedOptions': ['CV_FDR_WINE', 'CV_FDR_MEAT'],
|
||||
"x.com.samsung.da.modes": ["CV_FDR_MEAT"],
|
||||
"x.com.samsung.da.supportedOptions": ["CV_FDR_WINE", "CV_FDR_MEAT"],
|
||||
}
|
||||
assert desc.exists_fn(overlap_rep, {}) is True
|
||||
|
||||
@@ -199,7 +225,7 @@ class TestTp1xNativeDuplicateResources:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator_tp1x_ref_21k_us')
|
||||
resources = _load_device("refrigerator_tp1x_ref_21k_us")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -210,24 +236,24 @@ class TestTp1xNativeDuplicateResources:
|
||||
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['defrost_delay'] is False
|
||||
assert 'ice_maker_enabled' not in state
|
||||
assert state['icemaker_one_enabled'] is True
|
||||
assert state['icemaker_two_enabled'] is True
|
||||
assert state['selfcheck_error'] == 'DA_ERROR_NONE'
|
||||
assert state["defrost_delay"] is False
|
||||
assert "ice_maker_enabled" not in state
|
||||
assert state["icemaker_one_enabled"] is True
|
||||
assert state["icemaker_two_enabled"] is True
|
||||
assert state["selfcheck_error"] == "DA_ERROR_NONE"
|
||||
|
||||
|
||||
class TestPantryZone:
|
||||
"""Cool Select Zone pantry compartment on ARTIK051_REF_17K -- issue #20."""
|
||||
|
||||
def test_href(self):
|
||||
assert fridge.PANTRY_ZONE.href == '/status/pantry/one/vs/0'
|
||||
assert fridge.PANTRY_ZONE.href == "/status/pantry/one/vs/0"
|
||||
|
||||
def test_write(self):
|
||||
desc = fridge.PANTRY_ZONE.entities[0]
|
||||
path, body = desc.write_fn('FDR_WINE', {})
|
||||
assert path == ['status', 'pantry', 'one', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.mode': 'FDR_WINE'}
|
||||
path, body = desc.write_fn("FDR_WINE", {})
|
||||
assert path == ["status", "pantry", "one", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.mode": "FDR_WINE"}
|
||||
|
||||
|
||||
class TestDefiniteTemperatureCooler:
|
||||
@@ -237,13 +263,13 @@ class TestDefiniteTemperatureCooler:
|
||||
control was entirely unbound before this capability was added."""
|
||||
|
||||
def test_href(self):
|
||||
assert fridge.DEFINITE_TEMPERATURE_COOLER.href == '/temperature/definite/cooler/vs/0'
|
||||
assert fridge.DEFINITE_TEMPERATURE_COOLER.href == "/temperature/definite/cooler/vs/0"
|
||||
|
||||
def test_write(self):
|
||||
desc = fridge.DEFINITE_TEMPERATURE_COOLER.entities[0]
|
||||
path, body = desc.write_fn('3', {})
|
||||
assert path == ['temperature', 'definite', 'cooler', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.definite.desired': '3'}
|
||||
path, body = desc.write_fn("3", {})
|
||||
assert path == ["temperature", "definite", "cooler", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.definite.desired": "3"}
|
||||
|
||||
def test_no_unbound_hrefs_and_discrete_options(self):
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
@@ -251,7 +277,7 @@ class TestDefiniteTemperatureCooler:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator_definite_cooler')
|
||||
resources = _load_device("refrigerator_definite_cooler")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -262,10 +288,10 @@ class TestDefiniteTemperatureCooler:
|
||||
assert unbound == []
|
||||
|
||||
state = flatten(bound, resources)
|
||||
assert state['cooler_temperature_setpoint'] == '2'
|
||||
assert state["cooler_temperature_setpoint"] == "2"
|
||||
|
||||
rep = resources['/temperature/definite/cooler/vs/0']
|
||||
assert rep['x.com.samsung.da.definite.supportedList'] == ['1', '2', '3', '4', '7']
|
||||
rep = resources["/temperature/definite/cooler/vs/0"]
|
||||
assert rep["x.com.samsung.da.definite.supportedList"] == ["1", "2", "3", "4", "7"]
|
||||
|
||||
|
||||
class TestKimchiZone:
|
||||
@@ -274,21 +300,20 @@ class TestKimchiZone:
|
||||
supportMode resource under /status/kimchi/<slot>/vs/0."""
|
||||
|
||||
def test_href_prefix(self):
|
||||
assert fridge.KIMCHI_ZONE.href_prefix == '/status/kimchi/'
|
||||
assert fridge.KIMCHI_DOOR_GENERIC.href_prefix == '/kimchidoors/'
|
||||
assert fridge.KIMCHI_ZONE.href_prefix == "/status/kimchi/"
|
||||
assert fridge.KIMCHI_DOOR_GENERIC.href_prefix == "/kimchidoors/"
|
||||
|
||||
def test_write_derives_path_from_href(self):
|
||||
desc = fridge.KIMCHI_ZONE.entities[0]
|
||||
rep = {'x.com.samsung.da.supportMode': ['KIMCHI_STORAGE_COLD']}
|
||||
path, body = desc.write_fn(
|
||||
'KIMCHI_STORAGE_COLD', rep, href='/status/kimchi/middle/vs/0')
|
||||
assert path == ['status', 'kimchi', 'middle', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.currentMode': 'KIMCHI_STORAGE_COLD'}
|
||||
rep = {"x.com.samsung.da.supportMode": ["KIMCHI_STORAGE_COLD"]}
|
||||
path, body = desc.write_fn("KIMCHI_STORAGE_COLD", rep, href="/status/kimchi/middle/vs/0")
|
||||
assert path == ["status", "kimchi", "middle", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.currentMode": "KIMCHI_STORAGE_COLD"}
|
||||
|
||||
def test_write_without_href_is_rejected(self):
|
||||
desc = fridge.KIMCHI_ZONE.entities[0]
|
||||
rep = {'x.com.samsung.da.supportMode': ['KIMCHI_STORAGE_COLD']}
|
||||
assert desc.write_fn('KIMCHI_STORAGE_COLD', rep) is None
|
||||
rep = {"x.com.samsung.da.supportMode": ["KIMCHI_STORAGE_COLD"]}
|
||||
assert desc.write_fn("KIMCHI_STORAGE_COLD", rep) is None
|
||||
|
||||
def test_write_rejects_value_outside_supportmode(self):
|
||||
"""A value the compartment never advertised is rejected rather than
|
||||
@@ -296,22 +321,27 @@ class TestKimchiZone:
|
||||
hardware (module docstring above KIMCHI_ZONE), so a bad value here
|
||||
is a food-safety-adjacent outcome, not just a cosmetic one."""
|
||||
desc = fridge.KIMCHI_ZONE.entities[0]
|
||||
rep = {'x.com.samsung.da.supportMode': ['KIMCHI_STORAGE_COLD']}
|
||||
assert desc.write_fn(
|
||||
'KIMCHI_STORAGE_WARM', rep, href='/status/kimchi/middle/vs/0',
|
||||
) is None
|
||||
rep = {"x.com.samsung.da.supportMode": ["KIMCHI_STORAGE_COLD"]}
|
||||
assert (
|
||||
desc.write_fn(
|
||||
"KIMCHI_STORAGE_WARM",
|
||||
rep,
|
||||
href="/status/kimchi/middle/vs/0",
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
def test_ripening_status_passes_through_device_value(self):
|
||||
"""No device_class='enum' catalog entry exists for this sensor, so
|
||||
lowercasing it would only make the raw device token un-translatable
|
||||
by HA -- pass the device's own casing straight through instead."""
|
||||
desc = next(e for e in fridge.KIMCHI_ZONE.entities if e.key == 'ripening_status')
|
||||
assert desc.value_fn('Off') == 'Off'
|
||||
desc = next(e for e in fridge.KIMCHI_ZONE.entities if e.key == "ripening_status")
|
||||
assert desc.value_fn("Off") == "Off"
|
||||
|
||||
def test_door_reuses_open_state_helper(self):
|
||||
desc = fridge.KIMCHI_DOOR_GENERIC.entities[0]
|
||||
assert desc.rep_fn({'x.com.samsung.da.openState': 'Open'}) is True
|
||||
assert desc.rep_fn({'x.com.samsung.da.openState': 'Close'}) is False
|
||||
assert desc.rep_fn({"x.com.samsung.da.openState": "Open"}) is True
|
||||
assert desc.rep_fn({"x.com.samsung.da.openState": "Close"}) is False
|
||||
|
||||
async def test_zone_mode_select_round_trips_through_display_casing(self):
|
||||
"""kimchi_zone_mode's displayed value (lowercase, catalog-translated)
|
||||
@@ -327,18 +357,20 @@ class TestKimchiZone:
|
||||
from custom_components.localthings.select import LocalThingsSelect
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator_tp2x_ref_20k_kimchi')
|
||||
resources = _load_device("refrigerator_tp2x_ref_20k_kimchi")
|
||||
bound = discover(
|
||||
resources, refrigerator.REGISTRY.capabilities,
|
||||
resources,
|
||||
refrigerator.REGISTRY.capabilities,
|
||||
refrigerator.REGISTRY.pattern_capabilities,
|
||||
)
|
||||
mode_bound = next(
|
||||
b for b in bound
|
||||
if isinstance(b.desc, SelectDesc) and b.href == '/status/kimchi/middle/vs/0'
|
||||
b
|
||||
for b in bound
|
||||
if isinstance(b.desc, SelectDesc) and b.href == "/status/kimchi/middle/vs/0"
|
||||
)
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-SERIAL'
|
||||
device_serial = "TEST-SERIAL"
|
||||
|
||||
def __init__(self, resources, data):
|
||||
self.last_resources = resources
|
||||
@@ -351,12 +383,12 @@ class TestKimchiZone:
|
||||
coordinator = _FakeCoordinator(resources, flatten(bound, resources))
|
||||
entity = LocalThingsSelect(coordinator, mode_bound)
|
||||
|
||||
assert entity.current_option == 'kimchi_storage_normal'
|
||||
assert 'kimchi_storage_cold' in entity.options
|
||||
assert entity.current_option == "kimchi_storage_normal"
|
||||
assert "kimchi_storage_cold" in entity.options
|
||||
|
||||
await entity.async_select_option('kimchi_storage_cold')
|
||||
await entity.async_select_option("kimchi_storage_cold")
|
||||
|
||||
assert coordinator.commands == ['KIMCHI_STORAGE_COLD']
|
||||
assert coordinator.commands == ["KIMCHI_STORAGE_COLD"]
|
||||
|
||||
|
||||
class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
|
||||
@@ -372,7 +404,7 @@ class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator_artik051_ref_17k')
|
||||
resources = _load_device("refrigerator_artik051_ref_17k")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -382,7 +414,7 @@ class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
|
||||
)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['pantry_zone_mode'] == 'FDR_DRINKS'
|
||||
assert state["pantry_zone_mode"] == "FDR_DRINKS"
|
||||
|
||||
def test_tp2x_ref_20k(self):
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
@@ -390,7 +422,7 @@ class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator_tp2x_ref_20k')
|
||||
resources = _load_device("refrigerator_tp2x_ref_20k")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -400,7 +432,7 @@ class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
|
||||
)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['flex_zone_mode'] == 'CV_FDR_BEVERAGE'
|
||||
assert state["flex_zone_mode"] == "CV_FDR_BEVERAGE"
|
||||
|
||||
def test_tp2x_ref_20k_kimchi(self):
|
||||
"""A different physical unit sharing the same modelNum string (issue
|
||||
@@ -412,7 +444,7 @@ class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator_tp2x_ref_20k_kimchi')
|
||||
resources = _load_device("refrigerator_tp2x_ref_20k_kimchi")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -422,12 +454,12 @@ class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
|
||||
)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['top_mode'] == 'STORAGE_FREEZER_NORMAL'
|
||||
assert state['middle_mode'] == 'KIMCHI_STORAGE_NORMAL'
|
||||
assert state['bottom_mode'] == 'KIMCHI_STORAGE_NORMAL'
|
||||
assert state['top_open'] is False
|
||||
assert 'middle_open' not in state # no /kimchidoors/middle/vs/0 reported
|
||||
assert 'flex_zone_mode' not in state # no resolvable overlap on this family
|
||||
assert state["top_mode"] == "STORAGE_FREEZER_NORMAL"
|
||||
assert state["middle_mode"] == "KIMCHI_STORAGE_NORMAL"
|
||||
assert state["bottom_mode"] == "KIMCHI_STORAGE_NORMAL"
|
||||
assert state["top_open"] is False
|
||||
assert "middle_open" not in state # no /kimchidoors/middle/vs/0 reported
|
||||
assert "flex_zone_mode" not in state # no resolvable overlap on this family
|
||||
|
||||
|
||||
class TestArtik051DongleRefFixtureCoverage:
|
||||
@@ -440,27 +472,31 @@ class TestArtik051DongleRefFixtureCoverage:
|
||||
def test_no_unbound_hrefs_and_expected_entities(self):
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import (
|
||||
for_device_by_model, refrigerator,
|
||||
for_device_by_model,
|
||||
refrigerator,
|
||||
)
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator_artik051_dongle_ref')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("refrigerator_artik051_dongle_ref")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
assert reg is not None and reg.name == 'refrigerator'
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
assert reg is not None and reg.name == "refrigerator"
|
||||
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources, refrigerator.REGISTRY.capabilities,
|
||||
refrigerator.REGISTRY.pattern_capabilities, log=unbound.append,
|
||||
resources,
|
||||
refrigerator.REGISTRY.capabilities,
|
||||
refrigerator.REGISTRY.pattern_capabilities,
|
||||
log=unbound.append,
|
||||
)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['door_onedoorfreezer_open'] is False # rep reports 'Close'
|
||||
assert state['freezer_temperature'] == -20.0
|
||||
assert state['freezer_setpoint'] == -20.0
|
||||
assert state["door_onedoorfreezer_open"] is False # rep reports 'Close'
|
||||
assert state["freezer_temperature"] == -20.0
|
||||
assert state["freezer_setpoint"] == -20.0
|
||||
|
||||
|
||||
class TestArtik051DongleRefCoolerFixtureCoverage:
|
||||
@@ -475,28 +511,32 @@ class TestArtik051DongleRefCoolerFixtureCoverage:
|
||||
def test_no_unbound_hrefs_and_expected_entities(self):
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import (
|
||||
for_device_by_model, refrigerator,
|
||||
for_device_by_model,
|
||||
refrigerator,
|
||||
)
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator_artik051_dongle_ref_cooler')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("refrigerator_artik051_dongle_ref_cooler")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
assert reg is not None and reg.name == 'refrigerator'
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
assert reg is not None and reg.name == "refrigerator"
|
||||
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources, refrigerator.REGISTRY.capabilities,
|
||||
refrigerator.REGISTRY.pattern_capabilities, log=unbound.append,
|
||||
resources,
|
||||
refrigerator.REGISTRY.capabilities,
|
||||
refrigerator.REGISTRY.pattern_capabilities,
|
||||
log=unbound.append,
|
||||
)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['door_cooler_open'] is False
|
||||
assert state['door_onedoorfreezer_open'] is False
|
||||
assert state['cooler_temperature'] == 3.0
|
||||
assert state['cooler_setpoint'] == 3.0
|
||||
assert state["door_cooler_open"] is False
|
||||
assert state["door_onedoorfreezer_open"] is False
|
||||
assert state["cooler_temperature"] == 3.0
|
||||
assert state["cooler_setpoint"] == 3.0
|
||||
|
||||
|
||||
class TestRefrigeratorAiEnergyLevelFixtureCoverage:
|
||||
@@ -515,7 +555,7 @@ class TestRefrigeratorAiEnergyLevelFixtureCoverage:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('refrigerator')
|
||||
resources = _load_device("refrigerator")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -525,7 +565,7 @@ class TestRefrigeratorAiEnergyLevelFixtureCoverage:
|
||||
)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['ai_energy_level'] == '1'
|
||||
assert state["ai_energy_level"] == "1"
|
||||
|
||||
|
||||
class TestSwitchOffIsNotInverted:
|
||||
@@ -539,26 +579,24 @@ class TestSwitchOffIsNotInverted:
|
||||
"""
|
||||
|
||||
# (switch descriptor, payload key it writes)
|
||||
CASES = [
|
||||
(fridge.ICEMAKER_NIGHTTIME.entities[0], 'ice.night.status'),
|
||||
(fridge.STATUS_LOCK.entities[0], 'x.com.samsung.da.ado.devicecontrol'),
|
||||
(fridge.STATUS_LOCK.entities[1], 'x.com.samsung.da.device.sound'),
|
||||
(fridge.DEFROST_DELAY.entities[0], 'x.com.samsung.da.delayDefrost'),
|
||||
(fridge.WELCOME_LIGHTING.entities[0], 'status'),
|
||||
(fridge.CABINET_LIGHT.entities[1], 'light.dimming.status'),
|
||||
(fridge.ICEMAKER_STATUS_FALLBACK.entities[0], 'x.com.samsung.da.iceMaker'),
|
||||
CASES: ClassVar[list] = [
|
||||
(fridge.ICEMAKER_NIGHTTIME.entities[0], "ice.night.status"),
|
||||
(fridge.STATUS_LOCK.entities[0], "x.com.samsung.da.ado.devicecontrol"),
|
||||
(fridge.STATUS_LOCK.entities[1], "x.com.samsung.da.device.sound"),
|
||||
(fridge.DEFROST_DELAY.entities[0], "x.com.samsung.da.delayDefrost"),
|
||||
(fridge.WELCOME_LIGHTING.entities[0], "status"),
|
||||
(fridge.CABINET_LIGHT.entities[1], "light.dimming.status"),
|
||||
(fridge.ICEMAKER_STATUS_FALLBACK.entities[0], "x.com.samsung.da.iceMaker"),
|
||||
]
|
||||
|
||||
def test_turning_off_sends_off(self):
|
||||
for desc, key in self.CASES:
|
||||
_segs, payload = desc.write_fn('Off', {})
|
||||
assert payload[key] == 'Off', (
|
||||
_segs, payload = desc.write_fn("Off", {})
|
||||
assert payload[key] == "Off", (
|
||||
f"{desc.key}: OFF must send 'Off', got {payload[key]!r} (inverted)"
|
||||
)
|
||||
|
||||
def test_turning_on_sends_on(self):
|
||||
for desc, key in self.CASES:
|
||||
_segs, payload = desc.write_fn('On', {})
|
||||
assert payload[key] == 'On', (
|
||||
f"{desc.key}: ON must send 'On', got {payload[key]!r}"
|
||||
)
|
||||
_segs, payload = desc.write_fn("On", {})
|
||||
assert payload[key] == "On", f"{desc.key}: ON must send 'On', got {payload[key]!r}"
|
||||
@@ -5,31 +5,32 @@ ice-maker resources (/icemaker/one/vs/0, /icemaker/two/vs/0) use named path
|
||||
segments rather than numeric indices, so they are modelled via DOOR_GENERIC
|
||||
pattern capability that auto-derives distinct keys from the href segments.
|
||||
"""
|
||||
from tests.conftest import _load_resources
|
||||
|
||||
from custom_components.localthings.registry.adapter import _key
|
||||
from custom_components.localthings.registry.by_type import refrigerator
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_resources
|
||||
|
||||
|
||||
def test_two_doors_get_distinct_keys():
|
||||
resources = _load_resources('10.0.0.254')
|
||||
resources = _load_resources("10.0.0.254")
|
||||
reg = refrigerator.REGISTRY
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
door_keys = sorted(_key(b) for b in bound if _key(b).startswith('door'))
|
||||
door_keys = sorted(_key(b) for b in bound if _key(b).startswith("door"))
|
||||
# at least the two physical doors (cooler + freezer) produce distinct keys
|
||||
assert len(set(door_keys)) >= 2, f"Expected >= 2 distinct door keys, got: {door_keys}"
|
||||
|
||||
|
||||
def test_two_iceMakers_get_distinct_keys():
|
||||
resources = _load_resources('10.0.0.254')
|
||||
def test_two_ice_makers_get_distinct_keys():
|
||||
resources = _load_resources("10.0.0.254")
|
||||
reg = refrigerator.REGISTRY
|
||||
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
|
||||
ice_keys = sorted(_key(b) for b in bound if _key(b).startswith('icemaker_'))
|
||||
ice_keys = sorted(_key(b) for b in bound if _key(b).startswith("icemaker_"))
|
||||
# icemaker_one_* and icemaker_two_* are distinct
|
||||
ice_one_keys = [k for k in ice_keys if k.startswith('icemaker_one_')]
|
||||
ice_two_keys = [k for k in ice_keys if k.startswith('icemaker_two_')]
|
||||
ice_one_keys = [k for k in ice_keys if k.startswith("icemaker_one_")]
|
||||
ice_two_keys = [k for k in ice_keys if k.startswith("icemaker_two_")]
|
||||
assert ice_one_keys, "No icemaker_one_* keys found"
|
||||
assert ice_two_keys, "No icemaker_two_* keys found"
|
||||
assert set(ice_one_keys).isdisjoint(set(ice_two_keys)), \
|
||||
assert set(ice_one_keys).isdisjoint(set(ice_two_keys)), (
|
||||
f"icemaker_one and icemaker_two keys overlap: {ice_one_keys} vs {ice_two_keys}"
|
||||
)
|
||||
+333
-286
File diff suppressed because it is too large.
Load diff
+66
-54
@@ -1,74 +1,78 @@
|
||||
import cbor2
|
||||
|
||||
from custom_components.localthings.registry.identity import DeviceIdentity, read_identity
|
||||
from custom_components.localthings.registry.identity import read_identity
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self, table):
|
||||
self.table = table # tuple(path) -> rep dict
|
||||
self.table = table # tuple(path) -> rep dict
|
||||
|
||||
def get(self, path, timeout=10.0):
|
||||
rep = self.table.get(tuple(path))
|
||||
if rep is None:
|
||||
return 0x84, b'' # 4.04 not found
|
||||
return 0x84, b"" # 4.04 not found
|
||||
return 0x45, cbor2.dumps(rep)
|
||||
|
||||
|
||||
def test_read_identity_from_oic_p_and_d():
|
||||
sess = FakeSession({
|
||||
('oic', 'p'): {'mnmn': 'Samsung Electronics', 'mnmo': 'RF9000B'},
|
||||
('oic', 'd'): {'n': 'Family Hub'},
|
||||
})
|
||||
ident = read_identity(sess, serial='ABC123')
|
||||
assert ident.manufacturer == 'Samsung Electronics'
|
||||
assert ident.model == 'RF9000B'
|
||||
assert ident.name == 'Family Hub'
|
||||
assert ident.serial == 'ABC123'
|
||||
sess = FakeSession(
|
||||
{
|
||||
("oic", "p"): {"mnmn": "Samsung Electronics", "mnmo": "RF9000B"},
|
||||
("oic", "d"): {"n": "Family Hub"},
|
||||
}
|
||||
)
|
||||
ident = read_identity(sess, serial="ABC123")
|
||||
assert ident.manufacturer == "Samsung Electronics"
|
||||
assert ident.model == "RF9000B"
|
||||
assert ident.name == "Family Hub"
|
||||
assert ident.serial == "ABC123"
|
||||
|
||||
|
||||
def test_read_identity_tolerates_missing_resources():
|
||||
ident = read_identity(FakeSession({}), serial=None)
|
||||
assert ident.manufacturer == 'Samsung'
|
||||
assert ident.model == ''
|
||||
assert ident.manufacturer == "Samsung"
|
||||
assert ident.model == ""
|
||||
assert ident.serial is None
|
||||
assert ident.device_types == ()
|
||||
assert ident.raw == {'/oic/p': {}, '/oic/d': {}, '/oic/res': []}
|
||||
assert ident.raw == {"/oic/p": {}, "/oic/d": {}, "/oic/res": []}
|
||||
|
||||
|
||||
def test_read_identity_captures_oic_d_device_types():
|
||||
"""/oic/d's `rt` is OCF's own device-type declaration -- captured so
|
||||
diagnostics can show whether real hardware populates it usefully."""
|
||||
sess = FakeSession({
|
||||
('oic', 'd'): {
|
||||
'n': 'Living Room AC',
|
||||
'rt': ['oic.wk.d', 'oic.d.airconditioner'],
|
||||
},
|
||||
})
|
||||
sess = FakeSession(
|
||||
{
|
||||
("oic", "d"): {
|
||||
"n": "Living Room AC",
|
||||
"rt": ["oic.wk.d", "oic.d.airconditioner"],
|
||||
},
|
||||
}
|
||||
)
|
||||
ident = read_identity(sess, serial=None)
|
||||
assert ident.device_types == ('oic.wk.d', 'oic.d.airconditioner')
|
||||
assert ident.device_types == ("oic.wk.d", "oic.d.airconditioner")
|
||||
|
||||
|
||||
def test_read_identity_normalizes_scalar_and_malformed_rt():
|
||||
"""Firmware that reports a bare string, or a non-list, must not explode."""
|
||||
assert read_identity(
|
||||
FakeSession({('oic', 'd'): {'rt': 'oic.d.refrigerator'}}), None
|
||||
).device_types == ('oic.d.refrigerator',)
|
||||
FakeSession({("oic", "d"): {"rt": "oic.d.refrigerator"}}), None
|
||||
).device_types == ("oic.d.refrigerator",)
|
||||
assert read_identity(FakeSession({("oic", "d"): {"rt": 42}}), None).device_types == ()
|
||||
assert read_identity(
|
||||
FakeSession({('oic', 'd'): {'rt': 42}}), None
|
||||
).device_types == ()
|
||||
assert read_identity(
|
||||
FakeSession({('oic', 'd'): {'rt': ['oic.wk.d', 7, None]}}), None
|
||||
).device_types == ('oic.wk.d',)
|
||||
FakeSession({("oic", "d"): {"rt": ["oic.wk.d", 7, None]}}), None
|
||||
).device_types == ("oic.wk.d",)
|
||||
|
||||
|
||||
def test_read_identity_keeps_raw_payloads_for_diagnostics():
|
||||
sess = FakeSession({
|
||||
('oic', 'p'): {'mnmn': 'Samsung Electronics', 'mnmo': 'RF9000B'},
|
||||
('oic', 'd'): {'n': 'Family Hub', 'di': 'abc-123'},
|
||||
})
|
||||
sess = FakeSession(
|
||||
{
|
||||
("oic", "p"): {"mnmn": "Samsung Electronics", "mnmo": "RF9000B"},
|
||||
("oic", "d"): {"n": "Family Hub", "di": "abc-123"},
|
||||
}
|
||||
)
|
||||
ident = read_identity(sess, serial=None)
|
||||
assert ident.raw['/oic/p']['mnmo'] == 'RF9000B'
|
||||
assert ident.raw['/oic/d']['di'] == 'abc-123'
|
||||
assert ident.raw["/oic/p"]["mnmo"] == "RF9000B"
|
||||
assert ident.raw["/oic/d"]["di"] == "abc-123"
|
||||
|
||||
|
||||
def test_read_identity_captures_oic_res_links():
|
||||
@@ -81,22 +85,32 @@ def test_read_identity_captures_oic_res_links():
|
||||
all, meaning it's registered non-discoverable and simply invisible to
|
||||
this endpoint -- see _SPECULATIVE_DEVICE_INDICES' docstring for why that
|
||||
motivated probing /device/1 and /device/2 directly instead."""
|
||||
sess = FakeSession({
|
||||
('oic', 'res'): [
|
||||
{'di': 'aaaa', 'links': [
|
||||
{'href': '/oic/d', 'rt': ['oic.wk.d', 'oic.d.refrigerator'],
|
||||
'p': {'bm': 1}},
|
||||
{'href': '/oic/sec/doxm', 'rt': ['oic.r.doxm'], 'p': {'bm': 1}},
|
||||
]},
|
||||
],
|
||||
})
|
||||
sess = FakeSession(
|
||||
{
|
||||
("oic", "res"): [
|
||||
{
|
||||
"di": "aaaa",
|
||||
"links": [
|
||||
{
|
||||
"href": "/oic/d",
|
||||
"rt": ["oic.wk.d", "oic.d.refrigerator"],
|
||||
"p": {"bm": 1},
|
||||
},
|
||||
{"href": "/oic/sec/doxm", "rt": ["oic.r.doxm"], "p": {"bm": 1}},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
ident = read_identity(sess, serial=None)
|
||||
assert ident.raw['/oic/res'] == [
|
||||
{'di': 'aaaa', 'links': [
|
||||
{'href': '/oic/d', 'rt': ['oic.wk.d', 'oic.d.refrigerator'],
|
||||
'p': {'bm': 1}},
|
||||
{'href': '/oic/sec/doxm', 'rt': ['oic.r.doxm'], 'p': {'bm': 1}},
|
||||
]},
|
||||
assert ident.raw["/oic/res"] == [
|
||||
{
|
||||
"di": "aaaa",
|
||||
"links": [
|
||||
{"href": "/oic/d", "rt": ["oic.wk.d", "oic.d.refrigerator"], "p": {"bm": 1}},
|
||||
{"href": "/oic/sec/doxm", "rt": ["oic.r.doxm"], "p": {"bm": 1}},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -104,7 +118,5 @@ def test_read_identity_tolerates_malformed_oic_res():
|
||||
"""A single Property map instead of an array (or anything else
|
||||
non-list-shaped) must not explode -- same defensive posture as
|
||||
_device_types' handling of a malformed /oic/d rt."""
|
||||
ident = read_identity(
|
||||
FakeSession({('oic', 'res'): {'not': 'a list'}}), serial=None
|
||||
)
|
||||
assert ident.raw['/oic/res'] == []
|
||||
ident = read_identity(FakeSession({("oic", "res"): {"not": "a list"}}), serial=None)
|
||||
assert ident.raw["/oic/res"] == []
|
||||
@@ -1,16 +1,17 @@
|
||||
"""Tests for the standalone induction-cooktop registry (issue #86)."""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model, induction_cooktop
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _cooktop():
|
||||
resources = _load_device('induction_cooktop')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("induction_cooktop")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -23,7 +24,7 @@ def _state():
|
||||
|
||||
def test_model_resolves_to_induction_cooktop_registry():
|
||||
reg, _ = _cooktop()
|
||||
assert reg is not None and reg.name == 'induction_cooktop'
|
||||
assert reg is not None and reg.name == "induction_cooktop"
|
||||
assert reg is induction_cooktop.REGISTRY
|
||||
|
||||
|
||||
@@ -39,11 +40,19 @@ def test_no_unbound_hrefs():
|
||||
def test_expected_entities_present():
|
||||
state = _state()
|
||||
for key in (
|
||||
'cooktop_state', 'cooktop_power', 'cooktop_child_lock',
|
||||
'burner_0_power_level', 'burner_0_state', 'burner_0_hot_surface',
|
||||
'burner_0_pan_detected', 'burner_2_pan_detected',
|
||||
'paired_hood_connected', 'probe_connected', 'probe_temperature',
|
||||
'energy_kwh', 'alarm_code',
|
||||
"cooktop_state",
|
||||
"cooktop_power",
|
||||
"cooktop_child_lock",
|
||||
"burner_0_power_level",
|
||||
"burner_0_state",
|
||||
"burner_0_hot_surface",
|
||||
"burner_0_pan_detected",
|
||||
"burner_2_pan_detected",
|
||||
"paired_hood_connected",
|
||||
"probe_connected",
|
||||
"probe_temperature",
|
||||
"energy_kwh",
|
||||
"alarm_code",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
@@ -52,7 +61,7 @@ def test_unreported_burners_gated_out():
|
||||
"""Dump reports numberOfBurners=3 (indices 0-2) -- burner slot 3+ of
|
||||
range.MAX_BURNERS must not appear as entities."""
|
||||
state = _state()
|
||||
assert 'burner_3_power_level' not in state
|
||||
assert "burner_3_power_level" not in state
|
||||
|
||||
|
||||
def test_recipe_status_href_is_ignored_not_unbound():
|
||||
@@ -60,6 +69,7 @@ def test_recipe_status_href_is_ignored_not_unbound():
|
||||
ignored.py, not modeled as an entity (same treatment as the microwave
|
||||
family's /recipe/cook/vs/0)."""
|
||||
reg, _ = _cooktop()
|
||||
ignored_hrefs = {cap.href for caps in reg.capabilities.values() for cap in caps
|
||||
if cap.entities == ()}
|
||||
assert '/cooktop/recipe/status/vs/0' in ignored_hrefs
|
||||
ignored_hrefs = {
|
||||
cap.href for caps in reg.capabilities.values() for cap in caps if cap.entities == ()
|
||||
}
|
||||
assert "/cooktop/recipe/status/vs/0" in ignored_hrefs
|
||||
@@ -1,39 +1,62 @@
|
||||
"""Tests for the shared laundry capabilities (washer/dryer/dishwasher)."""
|
||||
|
||||
from custom_components.localthings.registry.capabilities import laundry
|
||||
|
||||
|
||||
class TestCourseHelpers:
|
||||
def test_parses_edit_course_list(self):
|
||||
raw = 'EditCourseList_1C1D211B1E29243328262722202325322F2E30662D8F962B2A'
|
||||
raw = "EditCourseList_1C1D211B1E29243328262722202325322F2E30662D8F962B2A"
|
||||
assert laundry.parse_edit_course_list(raw) == [
|
||||
'1C', '1D', '21', '1B', '1E', '29', '24', '33', '28', '26', '27',
|
||||
'22', '20', '23', '25', '32', '2F', '2E', '30', '66', '2D', '8F', '96',
|
||||
'2B', '2A'
|
||||
"1C",
|
||||
"1D",
|
||||
"21",
|
||||
"1B",
|
||||
"1E",
|
||||
"29",
|
||||
"24",
|
||||
"33",
|
||||
"28",
|
||||
"26",
|
||||
"27",
|
||||
"22",
|
||||
"20",
|
||||
"23",
|
||||
"25",
|
||||
"32",
|
||||
"2F",
|
||||
"2E",
|
||||
"30",
|
||||
"66",
|
||||
"2D",
|
||||
"8F",
|
||||
"96",
|
||||
"2B",
|
||||
"2A",
|
||||
]
|
||||
|
||||
def test_parse_edit_course_list_handles_missing_or_malformed(self):
|
||||
assert laundry.parse_edit_course_list(None) == []
|
||||
assert laundry.parse_edit_course_list('') == []
|
||||
assert laundry.parse_edit_course_list('no underscore') == []
|
||||
assert laundry.parse_edit_course_list("") == []
|
||||
assert laundry.parse_edit_course_list("no underscore") == []
|
||||
|
||||
def test_cycle_options_reads_live_edit_course_list(self):
|
||||
"""The device's own course list -- including a code ('65') never seen
|
||||
on the primary dump -- is used as-is; there is no hardcoded table."""
|
||||
resources = {
|
||||
'/wm/editcourse/vs/0': {
|
||||
'x.com.samsung.da.editCourseList': 'EditCourseList_651C',
|
||||
"/wm/editcourse/vs/0": {
|
||||
"x.com.samsung.da.editCourseList": "EditCourseList_651C",
|
||||
},
|
||||
}
|
||||
assert laundry.cycle_options(resources) == ['65', '1C']
|
||||
assert laundry.cycle_options(resources) == ["65", "1C"]
|
||||
|
||||
def test_cycle_options_empty_when_resource_absent_or_empty(self):
|
||||
assert laundry.cycle_options({}) == []
|
||||
assert laundry.cycle_options({'/wm/editcourse/vs/0': {}}) == []
|
||||
assert laundry.cycle_options({"/wm/editcourse/vs/0": {}}) == []
|
||||
|
||||
def test_option_value(self):
|
||||
opts = ['DeviceType_0167', 'Course_1C', 'GMT_04']
|
||||
assert laundry.option_value(opts, 'Course') == '1C'
|
||||
assert laundry.option_value(opts, 'Missing') is None
|
||||
opts = ["DeviceType_0167", "Course_1C", "GMT_04"]
|
||||
assert laundry.option_value(opts, "Course") == "1C"
|
||||
assert laundry.option_value(opts, "Missing") is None
|
||||
|
||||
|
||||
class TestCourseCodesFromSupportedOptions:
|
||||
@@ -49,45 +72,57 @@ class TestCourseCodesFromSupportedOptions:
|
||||
# checked item, and by six other independent devices' already-shipped
|
||||
# translations agreeing on the same code -> name mapping.
|
||||
_REAL_SUPPORTED_OPTIONS = (
|
||||
'31C8410923FA67F1B847E923FA67F25843E933FA57F20857E943FA67F'
|
||||
'088000913FA67F7485209204A5208780009000A00006841E930FA30F'
|
||||
'7F841E920FA30F65841E943FA57F8F8102923FA57F96841E920FA37F'
|
||||
'34841E923FA67FA0811E933FA33F'
|
||||
"31C8410923FA67F1B847E923FA67F25843E933FA57F20857E943FA67F"
|
||||
"088000913FA67F7485209204A5208780009000A00006841E930FA30F"
|
||||
"7F841E920FA30F65841E943FA57F8F8102923FA57F96841E920FA37F"
|
||||
"34841E923FA67FA0811E933FA33F"
|
||||
)
|
||||
|
||||
def test_derives_codes_when_edit_course_list_is_empty(self):
|
||||
resources = {
|
||||
'/wm/editcourse/vs/0': {'x.com.samsung.da.editCourseList': ''},
|
||||
'/course/vs/0': {
|
||||
'x.com.samsung.da.options': ['Course_1C'],
|
||||
'x.com.samsung.da.supportedOptions': [self._REAL_SUPPORTED_OPTIONS],
|
||||
"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": ""},
|
||||
"/course/vs/0": {
|
||||
"x.com.samsung.da.options": ["Course_1C"],
|
||||
"x.com.samsung.da.supportedOptions": [self._REAL_SUPPORTED_OPTIONS],
|
||||
},
|
||||
}
|
||||
assert laundry.cycle_options(resources) == [
|
||||
'1C', '1B', '25', '20', '08', '74', '87', '06',
|
||||
'7F', '65', '8F', '96', '34', 'A0',
|
||||
"1C",
|
||||
"1B",
|
||||
"25",
|
||||
"20",
|
||||
"08",
|
||||
"74",
|
||||
"87",
|
||||
"06",
|
||||
"7F",
|
||||
"65",
|
||||
"8F",
|
||||
"96",
|
||||
"34",
|
||||
"A0",
|
||||
]
|
||||
|
||||
def test_edit_course_list_still_takes_priority(self):
|
||||
"""A live editCourseList wins even with supportedOptions present --
|
||||
no reason to prefer a derived list over the authoritative one."""
|
||||
resources = {
|
||||
'/wm/editcourse/vs/0': {'x.com.samsung.da.editCourseList': 'EditCourseList_651C'},
|
||||
'/course/vs/0': {
|
||||
'x.com.samsung.da.options': ['Course_1C'],
|
||||
'x.com.samsung.da.supportedOptions': [self._REAL_SUPPORTED_OPTIONS],
|
||||
"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_651C"},
|
||||
"/course/vs/0": {
|
||||
"x.com.samsung.da.options": ["Course_1C"],
|
||||
"x.com.samsung.da.supportedOptions": [self._REAL_SUPPORTED_OPTIONS],
|
||||
},
|
||||
}
|
||||
assert laundry.cycle_options(resources) == ['65', '1C']
|
||||
assert laundry.cycle_options(resources) == ["65", "1C"]
|
||||
|
||||
def test_rejects_a_table_missing_the_current_course(self):
|
||||
"""The device's own currently-selected course must be a member of
|
||||
its derived list -- a mismatch means the guess is wrong, not that
|
||||
the device selected something outside its own supported set."""
|
||||
resources = {
|
||||
'/course/vs/0': {
|
||||
'x.com.samsung.da.options': ['Course_FF'],
|
||||
'x.com.samsung.da.supportedOptions': [self._REAL_SUPPORTED_OPTIONS],
|
||||
"/course/vs/0": {
|
||||
"x.com.samsung.da.options": ["Course_FF"],
|
||||
"x.com.samsung.da.supportedOptions": [self._REAL_SUPPORTED_OPTIONS],
|
||||
},
|
||||
}
|
||||
assert laundry.cycle_options(resources) == []
|
||||
@@ -99,16 +134,16 @@ class TestCourseCodesFromSupportedOptions:
|
||||
current course" carry over for free) -- but K=1 is the real, most
|
||||
specific table and must be the one returned."""
|
||||
resources = {
|
||||
'/course/vs/0': {
|
||||
'x.com.samsung.da.options': ['Course_AA'],
|
||||
'x.com.samsung.da.supportedOptions': ['0AABBCCDD'],
|
||||
"/course/vs/0": {
|
||||
"x.com.samsung.da.options": ["Course_AA"],
|
||||
"x.com.samsung.da.supportedOptions": ["0AABBCCDD"],
|
||||
},
|
||||
}
|
||||
assert laundry.cycle_options(resources) == ['AA', 'BB', 'CC', 'DD']
|
||||
assert laundry.cycle_options(resources) == ["AA", "BB", "CC", "DD"]
|
||||
|
||||
def test_empty_without_supported_options_or_course_href(self):
|
||||
assert laundry.cycle_options({}) == []
|
||||
assert laundry.cycle_options({'/course/vs/0': {}}) == []
|
||||
assert laundry.cycle_options({"/course/vs/0": {}}) == []
|
||||
|
||||
def test_smallest_wins_even_when_a_larger_pass_is_not_a_multiple(self):
|
||||
"""Real dishwasher dump (K=7, 10 courses): K=10, 14, and 35 also
|
||||
@@ -119,54 +154,63 @@ class TestCourseCodesFromSupportedOptions:
|
||||
real dump checked so far, not a proven guarantee -- see
|
||||
_course_codes_from_supported_options's docstring."""
|
||||
resources = {
|
||||
'/course/vs/0': {
|
||||
'x.com.samsung.da.options': ['Course_0E'],
|
||||
'x.com.samsung.da.supportedOptions': [
|
||||
'30E5434B102D102835034B002D002845034B002D002805034B000D000'
|
||||
'865034B002D002075000B000D000905000B000D0008D5034B002D0028'
|
||||
'E5034B000D0008F5034B000D000'
|
||||
"/course/vs/0": {
|
||||
"x.com.samsung.da.options": ["Course_0E"],
|
||||
"x.com.samsung.da.supportedOptions": [
|
||||
"30E5434B102D102835034B002D002845034B002D002805034B000D000"
|
||||
"865034B002D002075000B000D000905000B000D0008D5034B002D0028"
|
||||
"E5034B000D0008F5034B000D000"
|
||||
],
|
||||
},
|
||||
}
|
||||
assert laundry.cycle_options(resources) == [
|
||||
'0E', '83', '84', '80', '86', '07', '90', '8D', '8E', '8F',
|
||||
"0E",
|
||||
"83",
|
||||
"84",
|
||||
"80",
|
||||
"86",
|
||||
"07",
|
||||
"90",
|
||||
"8D",
|
||||
"8E",
|
||||
"8F",
|
||||
]
|
||||
|
||||
|
||||
class TestCycleSelect:
|
||||
def test_builds_labelled_cycle_select(self):
|
||||
desc = laundry.cycle_select(translation_key='dryer_cycle', icon='mdi:tumble-dryer')
|
||||
assert desc.key == 'cycle'
|
||||
assert desc.translation_key == 'dryer_cycle'
|
||||
assert desc.icon == 'mdi:tumble-dryer'
|
||||
desc = laundry.cycle_select(translation_key="dryer_cycle", icon="mdi:tumble-dryer")
|
||||
assert desc.key == "cycle"
|
||||
assert desc.translation_key == "dryer_cycle"
|
||||
assert desc.icon == "mdi:tumble-dryer"
|
||||
assert desc.options is laundry.cycle_options
|
||||
|
||||
def test_reads_raw_course_code_from_options(self):
|
||||
desc = laundry.cycle_select(translation_key='dryer_cycle', icon='x')
|
||||
rep = {'x.com.samsung.da.options': ['DeviceType_0167', 'Course_16', 'GMT_04']}
|
||||
assert desc.rep_fn(rep) == '16'
|
||||
assert desc.rep_fn({'x.com.samsung.da.options': ['GMT_04']}) is None
|
||||
desc = laundry.cycle_select(translation_key="dryer_cycle", icon="x")
|
||||
rep = {"x.com.samsung.da.options": ["DeviceType_0167", "Course_16", "GMT_04"]}
|
||||
assert desc.rep_fn(rep) == "16"
|
||||
assert desc.rep_fn({"x.com.samsung.da.options": ["GMT_04"]}) is None
|
||||
|
||||
def test_exists_only_when_edit_course_list_is_live(self):
|
||||
desc = laundry.cycle_select(translation_key='dryer_cycle', icon='x')
|
||||
desc = laundry.cycle_select(translation_key="dryer_cycle", icon="x")
|
||||
assert desc.exists_fn({}, {}) is False
|
||||
assert desc.exists_fn({}, {'/wm/editcourse/vs/0': {}}) is False
|
||||
live = {'/wm/editcourse/vs/0': {'x.com.samsung.da.editCourseList': 'EditCourseList_16'}}
|
||||
assert desc.exists_fn({}, {"/wm/editcourse/vs/0": {}}) is False
|
||||
live = {"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_16"}}
|
||||
assert desc.exists_fn({}, live) is True
|
||||
|
||||
def test_cycle_write_is_single_token(self):
|
||||
"""Confirmed on real hardware (issue #54): the device merges a
|
||||
single-token options[] write by prefix itself, so the write only
|
||||
needs to carry the changed token, not the whole rewritten array."""
|
||||
desc = laundry.cycle_select(translation_key='dryer_cycle', icon='x')
|
||||
rep = {'x.com.samsung.da.options': ['DeviceType_0167', 'Course_16', 'GMT_04']}
|
||||
path, body = desc.write_fn('1D', rep)
|
||||
assert path == ['course', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['Course_1D']}
|
||||
desc = laundry.cycle_select(translation_key="dryer_cycle", icon="x")
|
||||
rep = {"x.com.samsung.da.options": ["DeviceType_0167", "Course_16", "GMT_04"]}
|
||||
path, body = desc.write_fn("1D", rep)
|
||||
assert path == ["course", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["Course_1D"]}
|
||||
|
||||
def test_cycle_write_noop_without_options(self):
|
||||
desc = laundry.cycle_select(translation_key='dryer_cycle', icon='x')
|
||||
assert desc.write_fn('1D', {}) is None
|
||||
desc = laundry.cycle_select(translation_key="dryer_cycle", icon="x")
|
||||
assert desc.write_fn("1D", {}) is None
|
||||
|
||||
|
||||
class TestCycleSelectTableGating:
|
||||
@@ -181,56 +225,57 @@ class TestCycleSelectTableGating:
|
||||
|
||||
def _desc(self):
|
||||
return laundry.cycle_select(
|
||||
translation_key='washer_cycle', icon='x',
|
||||
table_href='/st/washercourse/vs/0',
|
||||
translation_key="washer_cycle",
|
||||
icon="x",
|
||||
table_href="/st/washercourse/vs/0",
|
||||
)
|
||||
|
||||
def test_static_string_when_no_table_href_given(self):
|
||||
"""dishwasher's call site -- no equivalent table-id resource in any
|
||||
dump seen, no evidence of the same cross-board risk -- keeps the
|
||||
plain static key unconditionally."""
|
||||
desc = laundry.cycle_select(translation_key='dishwasher_cycle', icon='x')
|
||||
assert desc.translation_key == 'dishwasher_cycle'
|
||||
desc = laundry.cycle_select(translation_key="dishwasher_cycle", icon="x")
|
||||
assert desc.translation_key == "dishwasher_cycle"
|
||||
|
||||
def test_resolved_key_is_built_from_the_reported_table(self):
|
||||
desc = self._desc()
|
||||
resources = {'/st/washercourse/vs/0': {'x.com.samsung.da.st.courseTable': 'Table_02'}}
|
||||
resources = {"/st/washercourse/vs/0": {"x.com.samsung.da.st.courseTable": "Table_02"}}
|
||||
assert callable(desc.translation_key)
|
||||
assert desc.translation_key(resources) == 'washer_cycle_table_02'
|
||||
assert desc.translation_key(resources) == "washer_cycle_table_02"
|
||||
|
||||
def test_untranslated_table_uses_generic_cycle_key(self):
|
||||
"""An unknown table does not claim another board's state labels."""
|
||||
desc = self._desc()
|
||||
resources = {'/st/washercourse/vs/0': {'x.com.samsung.da.st.courseTable': 'Table_00'}}
|
||||
assert desc.translation_key(resources) == 'cycle'
|
||||
resources = {"/st/washercourse/vs/0": {"x.com.samsung.da.st.courseTable": "Table_00"}}
|
||||
assert desc.translation_key(resources) == "cycle"
|
||||
|
||||
def test_resolves_to_generic_cycle_when_table_id_is_unknown(self):
|
||||
"""An absent table id still gets a translated generic entity name."""
|
||||
desc = self._desc()
|
||||
assert desc.translation_key({}) == 'cycle'
|
||||
assert desc.translation_key({'/st/washercourse/vs/0': {}}) == 'cycle'
|
||||
assert desc.translation_key({}) == "cycle"
|
||||
assert desc.translation_key({"/st/washercourse/vs/0": {}}) == "cycle"
|
||||
|
||||
|
||||
class TestBuzzerSound:
|
||||
def test_href(self):
|
||||
assert laundry.BUZZER_SOUND.href == '/buzzersound/vs/0'
|
||||
assert laundry.BUZZER_SOUND.href == "/buzzersound/vs/0"
|
||||
|
||||
def test_buzzer_sound_write(self):
|
||||
desc = next(e for e in laundry.BUZZER_SOUND.entities if e.key == 'buzzer_sound')
|
||||
assert desc.options_field == 'supportedBuzzerSound'
|
||||
path, body = desc.write_fn('On', {})
|
||||
assert path == ['buzzersound', 'vs', '0']
|
||||
assert body == {'setBuzzerSound': 'On'}
|
||||
desc = next(e for e in laundry.BUZZER_SOUND.entities if e.key == "buzzer_sound")
|
||||
assert desc.options_field == "supportedBuzzerSound"
|
||||
path, body = desc.write_fn("On", {})
|
||||
assert path == ["buzzersound", "vs", "0"]
|
||||
assert body == {"setBuzzerSound": "On"}
|
||||
|
||||
def test_finish_sound_exists_only_when_supported(self):
|
||||
desc = next(e for e in laundry.BUZZER_SOUND.entities if e.key == 'finish_sound')
|
||||
assert desc.exists_fn({'setBuzzerSound': 'On'}, {}) is False
|
||||
assert desc.exists_fn({'supportedFinishSound': ['FinishSound_1']}, {}) is True
|
||||
desc = next(e for e in laundry.BUZZER_SOUND.entities if e.key == "finish_sound")
|
||||
assert desc.exists_fn({"setBuzzerSound": "On"}, {}) is False
|
||||
assert desc.exists_fn({"supportedFinishSound": ["FinishSound_1"]}, {}) is True
|
||||
|
||||
|
||||
class TestJobBeginningStatus:
|
||||
def test_href_and_field(self):
|
||||
assert laundry.JOB_BEGINNING_STATUS.href == '/wm/jobbeginingstatus/vs/0'
|
||||
assert laundry.JOB_BEGINNING_STATUS.href == "/wm/jobbeginingstatus/vs/0"
|
||||
desc = laundry.JOB_BEGINNING_STATUS.entities[0]
|
||||
assert desc.field == 'x.com.samsung.da.currentStatus'
|
||||
assert desc.entity_category == 'diagnostic'
|
||||
assert desc.field == "x.com.samsung.da.currentStatus"
|
||||
assert desc.entity_category == "diagnostic"
|
||||
@@ -1,58 +1,59 @@
|
||||
"""Write-handler unit tests for laundry-family capabilities."""
|
||||
|
||||
from custom_components.localthings.registry.capabilities import laundry
|
||||
from custom_components.localthings.registry.capabilities.operational import OPERATIONAL_STATE
|
||||
|
||||
|
||||
def test_start_button_writes_run():
|
||||
btn = next(e for e in OPERATIONAL_STATE.entities if e.key == 'start')
|
||||
assert btn.write_fn('Run', {}) == (
|
||||
['operational', 'state', 'vs', '0'],
|
||||
{'x.com.samsung.da.state': 'Run'},
|
||||
btn = next(e for e in OPERATIONAL_STATE.entities if e.key == "start")
|
||||
assert btn.write_fn("Run", {}) == (
|
||||
["operational", "state", "vs", "0"],
|
||||
{"x.com.samsung.da.state": "Run"},
|
||||
)
|
||||
|
||||
|
||||
def test_pause_button_writes_pause():
|
||||
btn = next(e for e in OPERATIONAL_STATE.entities if e.key == 'pause')
|
||||
assert btn.write_fn('Pause', {}) == (
|
||||
['operational', 'state', 'vs', '0'],
|
||||
{'x.com.samsung.da.state': 'Pause'},
|
||||
btn = next(e for e in OPERATIONAL_STATE.entities if e.key == "pause")
|
||||
assert btn.write_fn("Pause", {}) == (
|
||||
["operational", "state", "vs", "0"],
|
||||
{"x.com.samsung.da.state": "Pause"},
|
||||
)
|
||||
|
||||
|
||||
def test_stop_button_writes_ready():
|
||||
btn = next(e for e in OPERATIONAL_STATE.entities if e.key == 'stop')
|
||||
assert btn.write_fn('Ready', {}) == (
|
||||
['operational', 'state', 'vs', '0'],
|
||||
{'x.com.samsung.da.state': 'Ready'},
|
||||
btn = next(e for e in OPERATIONAL_STATE.entities if e.key == "stop")
|
||||
assert btn.write_fn("Ready", {}) == (
|
||||
["operational", "state", "vs", "0"],
|
||||
{"x.com.samsung.da.state": "Ready"},
|
||||
)
|
||||
|
||||
|
||||
def test_sound_mode_write_valid():
|
||||
desc = next(e for e in laundry.SOUND_MODE.entities if e.key == 'sound_mode')
|
||||
assert desc.write_fn('mute', {}) == (
|
||||
['settings', 'sound', 'mode', 'vs', '0'],
|
||||
{'mode': 'mute'},
|
||||
desc = next(e for e in laundry.SOUND_MODE.entities if e.key == "sound_mode")
|
||||
assert desc.write_fn("mute", {}) == (
|
||||
["settings", "sound", "mode", "vs", "0"],
|
||||
{"mode": "mute"},
|
||||
)
|
||||
assert desc.write_fn('invalid', {}) is None
|
||||
assert desc.write_fn("invalid", {}) is None
|
||||
|
||||
|
||||
def test_led_brightness_write_valid():
|
||||
desc = next(e for e in laundry.DOOR_LED.entities if e.key == 'led_brightness')
|
||||
assert desc.write_fn('Low', {}) == (
|
||||
['doorled', 'light', 'vs', '0'],
|
||||
{'setBrightness': 'Low'},
|
||||
desc = next(e for e in laundry.DOOR_LED.entities if e.key == "led_brightness")
|
||||
assert desc.write_fn("Low", {}) == (
|
||||
["doorled", "light", "vs", "0"],
|
||||
{"setBrightness": "Low"},
|
||||
)
|
||||
assert desc.write_fn('Medium', {}) is None
|
||||
assert desc.write_fn("Medium", {}) is None
|
||||
|
||||
|
||||
def test_led_night_light_write_valid():
|
||||
desc = next(e for e in laundry.DOOR_LED.entities if e.key == 'led_night_light')
|
||||
assert desc.write_fn('On', {}) == (
|
||||
['doorled', 'light', 'vs', '0'],
|
||||
{'setNightLight': 'On'},
|
||||
desc = next(e for e in laundry.DOOR_LED.entities if e.key == "led_night_light")
|
||||
assert desc.write_fn("On", {}) == (
|
||||
["doorled", "light", "vs", "0"],
|
||||
{"setNightLight": "On"},
|
||||
)
|
||||
assert desc.write_fn('Off', {}) == (
|
||||
['doorled', 'light', 'vs', '0'],
|
||||
{'setNightLight': 'Off'},
|
||||
assert desc.write_fn("Off", {}) == (
|
||||
["doorled", "light", "vs", "0"],
|
||||
{"setNightLight": "Off"},
|
||||
)
|
||||
assert desc.write_fn('invalid', {}) is None
|
||||
assert desc.write_fn("invalid", {}) is None
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Unit tests for the microwave-family capabilities (issue #121/#66 split
|
||||
into their own device type instead of being folded into oven.py)."""
|
||||
|
||||
from custom_components.localthings.registry.by_type import (
|
||||
for_device_by_model,
|
||||
resolve,
|
||||
@@ -7,19 +8,21 @@ from custom_components.localthings.registry.by_type import (
|
||||
from custom_components.localthings.registry.capabilities import microwave
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Device-type detection + full-dump coverage
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_microwave_fixture_resolves_and_has_no_unbound_hrefs():
|
||||
from tests.conftest import _load_device
|
||||
resources = _load_device('microwave_mw7300b')
|
||||
info = resources['/information/vs/0']
|
||||
|
||||
resources = _load_device("microwave_mw7300b")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
assert reg is not None
|
||||
assert reg.name == 'microwave'
|
||||
assert reg.name == "microwave"
|
||||
|
||||
unbound = []
|
||||
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
|
||||
@@ -30,12 +33,14 @@ def test_microwave_hood_fan_fixture_resolves_and_has_no_unbound_hrefs():
|
||||
"""Issues #137/#142: `/hood/fanspeed/vs/0` (the combi unit's built-in
|
||||
vent fan) was previously unbound on this family."""
|
||||
from tests.conftest import _load_device
|
||||
resources = _load_device('microwave_me7500d')
|
||||
info = resources['/information/vs/0']
|
||||
|
||||
resources = _load_device("microwave_me7500d")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
assert reg is not None
|
||||
assert reg.name == 'microwave'
|
||||
assert reg.name == "microwave"
|
||||
|
||||
unbound = []
|
||||
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
|
||||
@@ -46,59 +51,67 @@ def test_qooker_fixture_resolves_as_microwave_and_has_no_unbound_hrefs():
|
||||
"""Bespoke Qooker MW7500A is microwave-shaped despite both its OCF type
|
||||
and internal board token saying oven."""
|
||||
from tests.conftest import _load_device
|
||||
resources = _load_device('qooker_mw7500a')
|
||||
|
||||
reg = resolve(resources, device_types=('oic.wk.d', 'oic.d.oven'))
|
||||
resources = _load_device("qooker_mw7500a")
|
||||
|
||||
reg = resolve(resources, device_types=("oic.wk.d", "oic.d.oven"))
|
||||
|
||||
assert reg is not None
|
||||
assert reg.name == 'microwave'
|
||||
assert reg.name == "microwave"
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources, reg.capabilities, reg.pattern_capabilities,
|
||||
resources,
|
||||
reg.capabilities,
|
||||
reg.pattern_capabilities,
|
||||
log=unbound.append,
|
||||
)
|
||||
assert unbound == []
|
||||
keys = {entity.desc.key for entity in bound}
|
||||
assert {'cooking_mode', 'power_level', 'setpoint'} <= keys
|
||||
assert 'oven_mode' not in keys
|
||||
assert {"cooking_mode", "power_level", "setpoint"} <= keys
|
||||
assert "oven_mode" not in keys
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MICROWAVE_SETPOINT — NumberDesc with RMW write semantics
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_microwave_setpoint_write_is_read_modify_write():
|
||||
desc = microwave.MICROWAVE_SETPOINT.entities[0]
|
||||
rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.desired': '0'}]}
|
||||
rep = {"x.com.samsung.da.items": [{"x.com.samsung.da.desired": "0"}]}
|
||||
path, body = desc.write_fn(180, rep)
|
||||
assert path == ['temperatures', 'vs', '0']
|
||||
assert body['x.com.samsung.da.items'][0]['x.com.samsung.da.desired'] == '180'
|
||||
assert path == ["temperatures", "vs", "0"]
|
||||
assert body["x.com.samsung.da.items"][0]["x.com.samsung.da.desired"] == "180"
|
||||
|
||||
|
||||
def test_microwave_setpoint_rmw_preserves_other_item_fields():
|
||||
desc = microwave.MICROWAVE_SETPOINT.entities[0]
|
||||
rep = {'x.com.samsung.da.items': [{
|
||||
'x.com.samsung.da.current': '150',
|
||||
'x.com.samsung.da.desired': '150',
|
||||
}]}
|
||||
path, body = desc.write_fn(180, rep)
|
||||
item = body['x.com.samsung.da.items'][0]
|
||||
assert item['x.com.samsung.da.desired'] == '180'
|
||||
assert item['x.com.samsung.da.current'] == '150'
|
||||
rep = {
|
||||
"x.com.samsung.da.items": [
|
||||
{
|
||||
"x.com.samsung.da.current": "150",
|
||||
"x.com.samsung.da.desired": "150",
|
||||
}
|
||||
]
|
||||
}
|
||||
_path, body = desc.write_fn(180, rep)
|
||||
item = body["x.com.samsung.da.items"][0]
|
||||
assert item["x.com.samsung.da.desired"] == "180"
|
||||
assert item["x.com.samsung.da.current"] == "150"
|
||||
|
||||
|
||||
def test_microwave_setpoint_clamps_to_step():
|
||||
desc = microwave.MICROWAVE_SETPOINT.entities[0]
|
||||
rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.desired': '0'}]}
|
||||
_, body = desc.write_fn(182, rep) # nearest 5 = 180
|
||||
assert body['x.com.samsung.da.items'][0]['x.com.samsung.da.desired'] == '180'
|
||||
rep = {"x.com.samsung.da.items": [{"x.com.samsung.da.desired": "0"}]}
|
||||
_, body = desc.write_fn(182, rep) # nearest 5 = 180
|
||||
assert body["x.com.samsung.da.items"][0]["x.com.samsung.da.desired"] == "180"
|
||||
|
||||
|
||||
def test_microwave_setpoint_rejects_out_of_range():
|
||||
desc = microwave.MICROWAVE_SETPOINT.entities[0]
|
||||
rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.desired': '100'}]}
|
||||
assert desc.write_fn(20, rep) is None # below min (40)
|
||||
assert desc.write_fn(210, rep) is None # above max (200)
|
||||
rep = {"x.com.samsung.da.items": [{"x.com.samsung.da.desired": "100"}]}
|
||||
assert desc.write_fn(20, rep) is None # below min (40)
|
||||
assert desc.write_fn(210, rep) is None # above max (200)
|
||||
|
||||
|
||||
def test_microwave_setpoint_rejects_missing_items():
|
||||
@@ -111,8 +124,8 @@ def test_microwave_setpoint_exists_only_for_celsius():
|
||||
against issue #44) -- the writable setpoint stays hidden rather than
|
||||
showing unverified bounds under the wrong unit."""
|
||||
desc = microwave.MICROWAVE_SETPOINT.entities[0]
|
||||
celsius_rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.unit': 'Celsius'}]}
|
||||
fahrenheit_rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.unit': 'Fahrenheit'}]}
|
||||
celsius_rep = {"x.com.samsung.da.items": [{"x.com.samsung.da.unit": "Celsius"}]}
|
||||
fahrenheit_rep = {"x.com.samsung.da.items": [{"x.com.samsung.da.unit": "Fahrenheit"}]}
|
||||
assert desc.exists_fn(celsius_rep, {}) is True
|
||||
assert desc.exists_fn(fahrenheit_rep, {}) is False
|
||||
|
||||
@@ -121,20 +134,21 @@ def test_microwave_setpoint_exists_only_for_celsius():
|
||||
# MICROWAVE_CAVITY — power_level sensor
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_power_level_parses_watt_suffix():
|
||||
"""Issue #121's combi dump reports e.g. '0W'."""
|
||||
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == 'power_level')
|
||||
assert desc.value_fn('900W') == 900
|
||||
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == "power_level")
|
||||
assert desc.value_fn("900W") == 900
|
||||
|
||||
|
||||
def test_power_level_parses_bare_number():
|
||||
"""Issue #137's plain microwave reports the bare number, no 'W' suffix."""
|
||||
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == 'power_level')
|
||||
assert desc.value_fn('0') == 0
|
||||
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == "power_level")
|
||||
assert desc.value_fn("0") == 0
|
||||
|
||||
|
||||
def test_power_level_handles_missing_value():
|
||||
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == 'power_level')
|
||||
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == "power_level")
|
||||
assert desc.value_fn(None) is None
|
||||
|
||||
|
||||
@@ -142,13 +156,14 @@ def test_power_level_handles_missing_value():
|
||||
# MICROWAVE_MODE — SelectDesc with non-empty, family-specific options
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_microwave_mode_options_nonempty():
|
||||
desc = microwave.MICROWAVE_MODE.entities[0]
|
||||
assert callable(desc.options)
|
||||
options = desc.options({})
|
||||
assert len(options) > 0
|
||||
assert 'MicroWave' in options
|
||||
assert 'AirFryer' in options # distinct spelling from oven.py's 'AirFry'
|
||||
assert "MicroWave" in options
|
||||
assert "AirFryer" in options # distinct spelling from oven.py's 'AirFry'
|
||||
|
||||
|
||||
def test_microwave_mode_options_reads_live_supported_modes():
|
||||
@@ -157,22 +172,24 @@ def test_microwave_mode_options_reads_live_supported_modes():
|
||||
present, same live-first pattern as oven._oven_mode_options, instead of
|
||||
offering users modes their own unit doesn't have."""
|
||||
desc = microwave.MICROWAVE_MODE.entities[0]
|
||||
resources = {'/mode/vs/0': {
|
||||
'x.com.samsung.da.supportedModes': ['NoOperation', 'MicroWave', 'Autocook', 'KeepWarm'],
|
||||
}}
|
||||
assert desc.options(resources) == ['NoOperation', 'MicroWave', 'Autocook', 'KeepWarm']
|
||||
resources = {
|
||||
"/mode/vs/0": {
|
||||
"x.com.samsung.da.supportedModes": ["NoOperation", "MicroWave", "Autocook", "KeepWarm"],
|
||||
}
|
||||
}
|
||||
assert desc.options(resources) == ["NoOperation", "MicroWave", "Autocook", "KeepWarm"]
|
||||
|
||||
|
||||
def test_microwave_mode_write_round_trips():
|
||||
desc = microwave.MICROWAVE_MODE.entities[0]
|
||||
path, body = desc.write_fn('MicroWave', {})
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body['x.com.samsung.da.modes'] == ['MicroWave']
|
||||
path, body = desc.write_fn("MicroWave", {})
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body["x.com.samsung.da.modes"] == ["MicroWave"]
|
||||
|
||||
|
||||
def test_microwave_mode_rejects_unknown():
|
||||
desc = microwave.MICROWAVE_MODE.entities[0]
|
||||
assert desc.write_fn('SpaghettiMode', {}) is None
|
||||
assert desc.write_fn("SpaghettiMode", {}) is None
|
||||
|
||||
|
||||
def test_microwave_mode_write_validates_against_live_supported_modes():
|
||||
@@ -181,129 +198,131 @@ def test_microwave_mode_write_validates_against_live_supported_modes():
|
||||
valid _MICROWAVE_MODES entry but must still be rejected for a unit
|
||||
whose own supportedModes doesn't include it."""
|
||||
desc = microwave.MICROWAVE_MODE.entities[0]
|
||||
rep = {'x.com.samsung.da.supportedModes': ['NoOperation', 'MicroWave', 'Autocook', 'KeepWarm']}
|
||||
path, body = desc.write_fn('MicroWave', rep)
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body['x.com.samsung.da.modes'] == ['MicroWave']
|
||||
assert desc.write_fn('AirFryer', rep) is None
|
||||
rep = {"x.com.samsung.da.supportedModes": ["NoOperation", "MicroWave", "Autocook", "KeepWarm"]}
|
||||
path, body = desc.write_fn("MicroWave", rep)
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body["x.com.samsung.da.modes"] == ["MicroWave"]
|
||||
assert desc.write_fn("AirFryer", rep) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MICROWAVE_MODE — lamp/sound options-array writes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sound_write_is_single_token():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'sound')
|
||||
rep = {'x.com.samsung.da.options': ['Sound_On']}
|
||||
path, body = desc.write_fn('Off', rep)
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['Sound_Off']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "sound")
|
||||
rep = {"x.com.samsung.da.options": ["Sound_On"]}
|
||||
path, body = desc.write_fn("Off", rep)
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["Sound_Off"]}
|
||||
|
||||
|
||||
def test_lamp_gated_absent_when_no_lamp_option():
|
||||
"""Issue #121's combi dump has no 'Lamp_*' token at all -- unlike
|
||||
oven.py's lamp switch (assumed universal), this one self-gates off."""
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
|
||||
rep = {'x.com.samsung.da.options': ['DeviceType_MW7300B-/EU1', 'Sound_Off']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "lamp")
|
||||
rep = {"x.com.samsung.da.options": ["DeviceType_MW7300B-/EU1", "Sound_Off"]}
|
||||
assert desc.exists_fn(rep, {}) is False
|
||||
|
||||
|
||||
def test_lamp_gated_present_when_lamp_option_reported():
|
||||
"""Issue #137's plain microwave reports 'Lamp_Off'."""
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
|
||||
rep = {'x.com.samsung.da.options': ['Lamp_Off', 'Sound_On']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "lamp")
|
||||
rep = {"x.com.samsung.da.options": ["Lamp_Off", "Sound_On"]}
|
||||
assert desc.exists_fn(rep, {}) is True
|
||||
|
||||
|
||||
def test_lamp_write_is_single_token():
|
||||
"""issue #152: the device has never been observed accepting 'On' --
|
||||
only 'High'/'Off' -- so the switch's "on" write uses 'High'."""
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
|
||||
rep = {'x.com.samsung.da.options': ['Lamp_Off']}
|
||||
path, body = desc.write_fn('On', rep)
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['Lamp_High']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "lamp")
|
||||
rep = {"x.com.samsung.da.options": ["Lamp_Off"]}
|
||||
path, body = desc.write_fn("On", rep)
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["Lamp_High"]}
|
||||
|
||||
|
||||
def test_lamp_write_requires_existing_options():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
|
||||
assert desc.write_fn('On', {}) is None
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "lamp")
|
||||
assert desc.write_fn("On", {}) is None
|
||||
|
||||
|
||||
def test_lamp_reads_off_as_false():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
|
||||
assert desc.value_fn(['Lamp_Off']) is False
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "lamp")
|
||||
assert desc.value_fn(["Lamp_Off"]) is False
|
||||
|
||||
|
||||
def test_lamp_reads_any_non_off_level_as_true():
|
||||
"""issue #152's ME7500D reports 'Lamp_High', not the binary 'Lamp_On'
|
||||
#137's dump implied -- any non-Off/non-absent value must read as on, not
|
||||
just a literal 'On'."""
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
|
||||
assert desc.value_fn(['Lamp_High']) is True
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "lamp")
|
||||
assert desc.value_fn(["Lamp_High"]) is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MICROWAVE_MODE — filter_remind/remind_beep options-array writes (issue #181)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_filter_remind_gated_absent_when_no_option():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'filter_remind')
|
||||
rep = {'x.com.samsung.da.options': ['DeviceType_MW7300B-/EU1', 'Sound_Off']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "filter_remind")
|
||||
rep = {"x.com.samsung.da.options": ["DeviceType_MW7300B-/EU1", "Sound_Off"]}
|
||||
assert desc.exists_fn(rep, {}) is False
|
||||
|
||||
|
||||
def test_filter_remind_gated_present_when_option_reported():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'filter_remind')
|
||||
rep = {'x.com.samsung.da.options': ['FilterRemind_Off']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "filter_remind")
|
||||
rep = {"x.com.samsung.da.options": ["FilterRemind_Off"]}
|
||||
assert desc.exists_fn(rep, {}) is True
|
||||
|
||||
|
||||
def test_filter_remind_reads_on_off():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'filter_remind')
|
||||
assert desc.value_fn(['FilterRemind_On']) is True
|
||||
assert desc.value_fn(['FilterRemind_Off']) is False
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "filter_remind")
|
||||
assert desc.value_fn(["FilterRemind_On"]) is True
|
||||
assert desc.value_fn(["FilterRemind_Off"]) is False
|
||||
|
||||
|
||||
def test_filter_remind_write_is_single_token():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'filter_remind')
|
||||
rep = {'x.com.samsung.da.options': ['FilterRemind_Off']}
|
||||
path, body = desc.write_fn('On', rep)
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['FilterRemind_On']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "filter_remind")
|
||||
rep = {"x.com.samsung.da.options": ["FilterRemind_Off"]}
|
||||
path, body = desc.write_fn("On", rep)
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["FilterRemind_On"]}
|
||||
|
||||
|
||||
def test_filter_remind_write_requires_existing_options():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'filter_remind')
|
||||
assert desc.write_fn('On', {}) is None
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "filter_remind")
|
||||
assert desc.write_fn("On", {}) is None
|
||||
|
||||
|
||||
def test_remind_beep_gated_absent_when_no_option():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'remind_beep')
|
||||
rep = {'x.com.samsung.da.options': ['DeviceType_MW7300B-/EU1', 'Sound_Off']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "remind_beep")
|
||||
rep = {"x.com.samsung.da.options": ["DeviceType_MW7300B-/EU1", "Sound_Off"]}
|
||||
assert desc.exists_fn(rep, {}) is False
|
||||
|
||||
|
||||
def test_remind_beep_gated_present_when_option_reported():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'remind_beep')
|
||||
rep = {'x.com.samsung.da.options': ['RemindBeep_On']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "remind_beep")
|
||||
rep = {"x.com.samsung.da.options": ["RemindBeep_On"]}
|
||||
assert desc.exists_fn(rep, {}) is True
|
||||
|
||||
|
||||
def test_remind_beep_reads_on_off():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'remind_beep')
|
||||
assert desc.value_fn(['RemindBeep_On']) is True
|
||||
assert desc.value_fn(['RemindBeep_Off']) is False
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "remind_beep")
|
||||
assert desc.value_fn(["RemindBeep_On"]) is True
|
||||
assert desc.value_fn(["RemindBeep_Off"]) is False
|
||||
|
||||
|
||||
def test_remind_beep_write_is_single_token():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'remind_beep')
|
||||
rep = {'x.com.samsung.da.options': ['RemindBeep_On']}
|
||||
path, body = desc.write_fn('Off', rep)
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['RemindBeep_Off']}
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "remind_beep")
|
||||
rep = {"x.com.samsung.da.options": ["RemindBeep_On"]}
|
||||
path, body = desc.write_fn("Off", rep)
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["RemindBeep_Off"]}
|
||||
|
||||
|
||||
def test_remind_beep_write_requires_existing_options():
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'remind_beep')
|
||||
assert desc.write_fn('On', {}) is None
|
||||
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == "remind_beep")
|
||||
assert desc.write_fn("On", {}) is None
|
||||
@@ -8,10 +8,11 @@ The fixture is a live capture from the reporting board (see its
|
||||
`x.com.samsung.da.multidevice` link in `/oic/res` -- no `subdeviceIdList`
|
||||
(Pattern B's signal), no `/device/<n>` sibling (Pattern A's).
|
||||
"""
|
||||
|
||||
from tests.conftest import FakeCoapSession, _discover_full, _load_device_full
|
||||
|
||||
FIXTURE = 'washer_dryer_onebody_awm'
|
||||
WASHER_UUID = '58b7d338-15c5-97d3-b562-000000000001'
|
||||
FIXTURE = "washer_dryer_onebody_awm"
|
||||
WASHER_UUID = "58b7d338-15c5-97d3-b562-000000000001"
|
||||
|
||||
|
||||
def _discover():
|
||||
@@ -20,12 +21,12 @@ def _discover():
|
||||
|
||||
|
||||
def test_washer_subdevice_materializes_from_oic_res_uuid_link():
|
||||
bound, materialized, skipped, full_resources, device_type_name = _discover()
|
||||
_bound, materialized, _skipped, _full_resources, _device_type_name = _discover()
|
||||
|
||||
assert [s.key for s in materialized] == [WASHER_UUID]
|
||||
sub = materialized[0]
|
||||
assert sub.kind == 'prefixed'
|
||||
assert sub.seed_path == (WASHER_UUID, 'device', '0')
|
||||
assert sub.kind == "prefixed"
|
||||
assert sub.seed_path == (WASHER_UUID, "device", "0")
|
||||
# Collection mode, not the issue-#205 flat fallback.
|
||||
assert sub.flat_hrefs == ()
|
||||
|
||||
@@ -42,16 +43,19 @@ def test_washer_subdevice_probe_only_fires_for_the_advertised_uuid():
|
||||
probes: dict[str, bool] = {}
|
||||
sess = FakeCoapSession(seeds)
|
||||
candidates, _extra = enumerate_subdevices(
|
||||
sess, resources, oic_res, probe_log=probes.__setitem__,
|
||||
sess,
|
||||
resources,
|
||||
oic_res,
|
||||
probe_log=probes.__setitem__,
|
||||
)
|
||||
|
||||
assert probes[f'/{WASHER_UUID}/device/0'] is True
|
||||
assert probes['/device/1'] is False
|
||||
assert probes['/device/2'] is False
|
||||
assert probes[f"/{WASHER_UUID}/device/0"] is True
|
||||
assert probes["/device/1"] is False
|
||||
assert probes["/device/2"] is False
|
||||
# No flat-fallback flood: the seed Collection answered, so no per-href
|
||||
# probes under the prefix beyond the seed itself.
|
||||
prefixed_probes = [h for h in probes if h.startswith(f'/{WASHER_UUID}/')]
|
||||
assert prefixed_probes == [f'/{WASHER_UUID}/device/0']
|
||||
prefixed_probes = [h for h in probes if h.startswith(f"/{WASHER_UUID}/")]
|
||||
assert prefixed_probes == [f"/{WASHER_UUID}/device/0"]
|
||||
assert [c.key for c in candidates] == [WASHER_UUID]
|
||||
|
||||
|
||||
@@ -63,11 +67,11 @@ def test_washer_subdevice_binds_its_own_primary_entities():
|
||||
sub = materialized[0]
|
||||
|
||||
sub_keys = {b.desc.key for b in bound if b.subdevice.key == sub.key}
|
||||
assert sub_keys, 'washer subdevice bound no entities at all'
|
||||
assert sub_keys, "washer subdevice bound no entities at all"
|
||||
# Its own operational state and its own power switch/sensor -- the two
|
||||
# things SmartThings cloud splits this unit over.
|
||||
assert any('machine_state' in k for k in sub_keys), sub_keys
|
||||
assert any('power' in k for k in sub_keys), sub_keys
|
||||
assert any("machine_state" in k for k in sub_keys), sub_keys
|
||||
assert any("power" in k for k in sub_keys), sub_keys
|
||||
|
||||
|
||||
def test_master_dryer_entities_unchanged_by_washer_discovery():
|
||||
@@ -78,15 +82,15 @@ def test_master_dryer_entities_unchanged_by_washer_discovery():
|
||||
# Without any subdevices (oic_res withheld, seeds empty -> washer never
|
||||
# discovered).
|
||||
bound_solo, materialized_solo, _s, _f, _n = _discover_full(
|
||||
resources, [], {},
|
||||
resources,
|
||||
[],
|
||||
{},
|
||||
)
|
||||
assert materialized_solo == []
|
||||
solo_keys = {(b.href, b.desc.key) for b in bound_solo}
|
||||
|
||||
bound, materialized, _s2, _f2, _n2 = _discover()
|
||||
sub = materialized[0]
|
||||
main_keys = {
|
||||
(b.href, b.desc.key) for b in bound if b.subdevice.key != sub.key
|
||||
}
|
||||
main_keys = {(b.href, b.desc.key) for b in bound if b.subdevice.key != sub.key}
|
||||
|
||||
assert main_keys == solo_keys
|
||||
@@ -4,10 +4,10 @@ from custom_components.localthings.registry.capabilities.operational import OPER
|
||||
|
||||
|
||||
def test_machine_state_maps_samsung_to_ocf():
|
||||
ms = next(e for e in OPERATIONAL_STATE.entities if e.key == 'machine_state')
|
||||
assert ms.value_fn('Run') == 'active'
|
||||
assert ms.value_fn('Pause') == 'pause'
|
||||
assert ms.value_fn('Ready') == 'idle'
|
||||
ms = next(e for e in OPERATIONAL_STATE.entities if e.key == "machine_state")
|
||||
assert ms.value_fn("Run") == "active"
|
||||
assert ms.value_fn("Pause") == "pause"
|
||||
assert ms.value_fn("Ready") == "idle"
|
||||
|
||||
|
||||
class TestProgressPercentage:
|
||||
@@ -16,13 +16,13 @@ class TestProgressPercentage:
|
||||
active state the same way `progress`/`cycle_active`/`finish_time` are."""
|
||||
|
||||
def test_zeroed_when_not_active(self):
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'progress_percentage')
|
||||
rep = {'x.com.samsung.da.state': 'Ready', 'x.com.samsung.da.progressPercentage': '1'}
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "progress_percentage")
|
||||
rep = {"x.com.samsung.da.state": "Ready", "x.com.samsung.da.progressPercentage": "1"}
|
||||
assert desc.rep_fn(rep) == 0
|
||||
|
||||
def test_passes_through_when_active(self):
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'progress_percentage')
|
||||
rep = {'x.com.samsung.da.state': 'Run', 'x.com.samsung.da.progressPercentage': '42'}
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "progress_percentage")
|
||||
rep = {"x.com.samsung.da.state": "Run", "x.com.samsung.da.progressPercentage": "42"}
|
||||
assert desc.rep_fn(rep) == 42
|
||||
|
||||
|
||||
@@ -30,34 +30,34 @@ class TestCompletionMinutes:
|
||||
"""Unit tests for completion_minutes entity."""
|
||||
|
||||
def test_completion_minutes_parsing(self):
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'completion_minutes')
|
||||
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "completion_minutes")
|
||||
|
||||
# 1 hour 25 mins 30 secs -> 85 mins + 1 sec ceiling = 86 mins
|
||||
rep = {'x.com.samsung.da.remainingTime': '01:25:30'}
|
||||
rep = {"x.com.samsung.da.remainingTime": "01:25:30"}
|
||||
assert desc.rep_fn(rep) == 86
|
||||
|
||||
# Exact minutes: 1 hour 30 mins 00 secs -> 90 mins
|
||||
rep_exact = {'x.com.samsung.da.remainingTime': '01:30:00'}
|
||||
rep_exact = {"x.com.samsung.da.remainingTime": "01:30:00"}
|
||||
assert desc.rep_fn(rep_exact) == 90
|
||||
|
||||
def test_completion_minutes_fallback_key(self):
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'completion_minutes')
|
||||
rep = {'remainingTime': '00:45:00'}
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "completion_minutes")
|
||||
rep = {"remainingTime": "00:45:00"}
|
||||
assert desc.rep_fn(rep) == 45
|
||||
|
||||
def test_completion_minutes_stale_finish_gated(self):
|
||||
"""Firmware freezes remainingTime at '00:01:00' when progress reaches 'Finish'.
|
||||
Should return 0 to prevent stuck values."""
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'completion_minutes')
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "completion_minutes")
|
||||
rep = {
|
||||
'x.com.samsung.da.progress': 'Finish',
|
||||
'x.com.samsung.da.remainingTime': '00:01:00',
|
||||
"x.com.samsung.da.progress": "Finish",
|
||||
"x.com.samsung.da.remainingTime": "00:01:00",
|
||||
}
|
||||
assert desc.rep_fn(rep) == 0
|
||||
|
||||
def test_completion_minutes_missing_or_invalid(self):
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'completion_minutes')
|
||||
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "completion_minutes")
|
||||
|
||||
rep = {}
|
||||
assert desc.rep_fn(rep) is None
|
||||
|
||||
@@ -70,20 +70,20 @@ class TestFinishTime:
|
||||
the UI rounded them down to the minute for display."""
|
||||
|
||||
def test_seconds_and_microseconds_are_zeroed(self):
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'finish_time')
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "finish_time")
|
||||
rep = {
|
||||
'x.com.samsung.da.state': 'Run',
|
||||
'x.com.samsung.da.remainingTime': '00:29:00',
|
||||
"x.com.samsung.da.state": "Run",
|
||||
"x.com.samsung.da.remainingTime": "00:29:00",
|
||||
}
|
||||
result = desc.rep_fn(rep)
|
||||
assert result.second == 0
|
||||
assert result.microsecond == 0
|
||||
|
||||
def test_stable_across_polls_within_same_minute(self):
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'finish_time')
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "finish_time")
|
||||
rep = {
|
||||
'x.com.samsung.da.state': 'Run',
|
||||
'x.com.samsung.da.remainingTime': '00:29:00',
|
||||
"x.com.samsung.da.state": "Run",
|
||||
"x.com.samsung.da.remainingTime": "00:29:00",
|
||||
}
|
||||
first = desc.rep_fn(rep)
|
||||
second = desc.rep_fn(rep)
|
||||
@@ -92,31 +92,43 @@ class TestFinishTime:
|
||||
|
||||
class TestDelayFieldFallback:
|
||||
def test_reads_delay_end_time_when_delay_start_time_absent(self):
|
||||
from custom_components.localthings.registry.capabilities.operational import OPERATIONAL_STATE
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'delay_start_hours')
|
||||
rep = {'x.com.samsung.da.delayEndTime': '02:30:00'}
|
||||
from custom_components.localthings.registry.capabilities.operational import (
|
||||
OPERATIONAL_STATE,
|
||||
)
|
||||
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "delay_start_hours")
|
||||
rep = {"x.com.samsung.da.delayEndTime": "02:30:00"}
|
||||
assert desc.rep_fn(rep) == 2.5
|
||||
|
||||
def test_prefers_delay_start_time_when_both_present(self):
|
||||
from custom_components.localthings.registry.capabilities.operational import OPERATIONAL_STATE
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'delay_start_hours')
|
||||
from custom_components.localthings.registry.capabilities.operational import (
|
||||
OPERATIONAL_STATE,
|
||||
)
|
||||
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "delay_start_hours")
|
||||
rep = {
|
||||
'x.com.samsung.da.delayStartTime': '01:00:00',
|
||||
'x.com.samsung.da.delayEndTime': '02:00:00',
|
||||
"x.com.samsung.da.delayStartTime": "01:00:00",
|
||||
"x.com.samsung.da.delayEndTime": "02:00:00",
|
||||
}
|
||||
assert desc.rep_fn(rep) == 1.0
|
||||
|
||||
def test_write_targets_delay_end_time_when_that_is_what_device_reports(self):
|
||||
from custom_components.localthings.registry.capabilities.operational import OPERATIONAL_STATE
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'delay_start_hours')
|
||||
rep = {'x.com.samsung.da.delayEndTime': '00:00:00'}
|
||||
from custom_components.localthings.registry.capabilities.operational import (
|
||||
OPERATIONAL_STATE,
|
||||
)
|
||||
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "delay_start_hours")
|
||||
rep = {"x.com.samsung.da.delayEndTime": "00:00:00"}
|
||||
path, body = desc.write_fn(1.5, rep)
|
||||
assert path == ['operational', 'state', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.delayEndTime': '1:30:00'}
|
||||
assert path == ["operational", "state", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.delayEndTime": "1:30:00"}
|
||||
|
||||
def test_write_targets_delay_start_time_by_default(self):
|
||||
from custom_components.localthings.registry.capabilities.operational import OPERATIONAL_STATE
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == 'delay_start_hours')
|
||||
rep = {'x.com.samsung.da.delayStartTime': '00:00:00'}
|
||||
path, body = desc.write_fn(1.5, rep)
|
||||
assert body == {'x.com.samsung.da.delayStartTime': '1:30:00'}
|
||||
from custom_components.localthings.registry.capabilities.operational import (
|
||||
OPERATIONAL_STATE,
|
||||
)
|
||||
|
||||
desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "delay_start_hours")
|
||||
rep = {"x.com.samsung.da.delayStartTime": "00:00:00"}
|
||||
_path, body = desc.write_fn(1.5, rep)
|
||||
assert body == {"x.com.samsung.da.delayStartTime": "1:30:00"}
|
||||
@@ -1,24 +1,27 @@
|
||||
"""Unit tests for oven-family capabilities."""
|
||||
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.capabilities import oven
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Device-type detection + full-dump coverage (issue #55)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_oven_fixture_resolves_and_has_no_unbound_hrefs():
|
||||
"""The issue #55 dump previously came back device_type='unknown' with
|
||||
/connected/vs/0 unbound -- resolving via the '-OVEN-' modelNum token
|
||||
fallback must leave every href in the oven registry bound or ignored."""
|
||||
from tests.conftest import _load_device
|
||||
resources = _load_device('oven')
|
||||
info = resources['/information/vs/0']
|
||||
|
||||
resources = _load_device("oven")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'])
|
||||
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
|
||||
)
|
||||
assert reg is not None
|
||||
assert reg.name == 'oven'
|
||||
assert reg.name == "oven"
|
||||
|
||||
unbound = []
|
||||
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
|
||||
@@ -29,45 +32,53 @@ def test_oven_fixture_resolves_and_has_no_unbound_hrefs():
|
||||
# OVEN_SETPOINT — NumberDesc with RMW write semantics
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_oven_setpoint_write_is_read_modify_write():
|
||||
cap = oven.OVEN_SETPOINT
|
||||
desc = cap.entities[0]
|
||||
rep = {'x.com.samsung.da.items': [
|
||||
{'x.com.samsung.da.id': 'Target', 'x.com.samsung.da.temperature': 0}]}
|
||||
rep = {
|
||||
"x.com.samsung.da.items": [
|
||||
{"x.com.samsung.da.id": "Target", "x.com.samsung.da.temperature": 0}
|
||||
]
|
||||
}
|
||||
path, body = desc.write_fn(200, rep)
|
||||
assert path[-1] == '0' # writes back to the resource
|
||||
assert path[-1] == "0" # writes back to the resource
|
||||
# the produced body preserves the items-array shape the oven expects
|
||||
assert 'x.com.samsung.da.items' in body or 'x.com.samsung.da.temperature' in str(body)
|
||||
assert "x.com.samsung.da.items" in body or "x.com.samsung.da.temperature" in str(body)
|
||||
|
||||
|
||||
def test_oven_setpoint_rmw_preserves_other_item_fields():
|
||||
"""RMW must not drop sibling fields (e.g. x.com.samsung.da.current)."""
|
||||
desc = oven.OVEN_SETPOINT.entities[0]
|
||||
rep = {'x.com.samsung.da.items': [{
|
||||
'x.com.samsung.da.current': '180',
|
||||
'x.com.samsung.da.desired': '180',
|
||||
}]}
|
||||
path, body = desc.write_fn(200, rep)
|
||||
item = body['x.com.samsung.da.items'][0]
|
||||
assert item['x.com.samsung.da.desired'] == '200'
|
||||
rep = {
|
||||
"x.com.samsung.da.items": [
|
||||
{
|
||||
"x.com.samsung.da.current": "180",
|
||||
"x.com.samsung.da.desired": "180",
|
||||
}
|
||||
]
|
||||
}
|
||||
_path, body = desc.write_fn(200, rep)
|
||||
item = body["x.com.samsung.da.items"][0]
|
||||
assert item["x.com.samsung.da.desired"] == "200"
|
||||
# sibling field preserved
|
||||
assert item['x.com.samsung.da.current'] == '180'
|
||||
assert item["x.com.samsung.da.current"] == "180"
|
||||
|
||||
|
||||
def test_oven_setpoint_clamps_to_step():
|
||||
"""Setpoint must be a multiple of SETPOINT_STEP_C."""
|
||||
desc = oven.OVEN_SETPOINT.entities[0]
|
||||
rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.desired': '0'}]}
|
||||
rep = {"x.com.samsung.da.items": [{"x.com.samsung.da.desired": "0"}]}
|
||||
_, body = desc.write_fn(202, rep)
|
||||
# 202 → nearest 5 = 200
|
||||
assert body['x.com.samsung.da.items'][0]['x.com.samsung.da.desired'] == '200'
|
||||
assert body["x.com.samsung.da.items"][0]["x.com.samsung.da.desired"] == "200"
|
||||
|
||||
|
||||
def test_oven_setpoint_rejects_out_of_range():
|
||||
desc = oven.OVEN_SETPOINT.entities[0]
|
||||
rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.desired': '100'}]}
|
||||
assert desc.write_fn(10, rep) is None # below min (30)
|
||||
assert desc.write_fn(300, rep) is None # above max (270)
|
||||
rep = {"x.com.samsung.da.items": [{"x.com.samsung.da.desired": "100"}]}
|
||||
assert desc.write_fn(10, rep) is None # below min (30)
|
||||
assert desc.write_fn(300, rep) is None # above max (270)
|
||||
|
||||
|
||||
def test_oven_setpoint_rejects_missing_items():
|
||||
@@ -81,11 +92,16 @@ def test_oven_setpoint_rejects_missing_items():
|
||||
# to the Celsius defaults)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _fahrenheit_rep(desired='0'):
|
||||
return {'x.com.samsung.da.items': [{
|
||||
'x.com.samsung.da.desired': desired,
|
||||
'x.com.samsung.da.unit': 'Fahrenheit',
|
||||
}]}
|
||||
|
||||
def _fahrenheit_rep(desired="0"):
|
||||
return {
|
||||
"x.com.samsung.da.items": [
|
||||
{
|
||||
"x.com.samsung.da.desired": desired,
|
||||
"x.com.samsung.da.unit": "Fahrenheit",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_oven_setpoint_write_uses_fahrenheit_bounds():
|
||||
@@ -94,19 +110,19 @@ def test_oven_setpoint_write_uses_fahrenheit_bounds():
|
||||
# 350 is within F bounds (175-550) but above the C max (270) --
|
||||
# confirms the write path isn't silently still clamping to Celsius.
|
||||
_, body = desc.write_fn(350, rep)
|
||||
assert body['x.com.samsung.da.items'][0]['x.com.samsung.da.desired'] == '350'
|
||||
assert body["x.com.samsung.da.items"][0]["x.com.samsung.da.desired"] == "350"
|
||||
|
||||
|
||||
def test_oven_setpoint_rejects_out_of_range_fahrenheit():
|
||||
desc = oven.OVEN_SETPOINT.entities[0]
|
||||
rep = _fahrenheit_rep()
|
||||
assert desc.write_fn(100, rep) is None # below F min (175)
|
||||
assert desc.write_fn(600, rep) is None # above F max (550)
|
||||
assert desc.write_fn(100, rep) is None # below F min (175)
|
||||
assert desc.write_fn(600, rep) is None # above F max (550)
|
||||
|
||||
|
||||
def test_oven_setpoint_native_bounds_track_live_unit():
|
||||
desc = oven.OVEN_SETPOINT.entities[0]
|
||||
celsius_rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.unit': 'Celsius'}]}
|
||||
celsius_rep = {"x.com.samsung.da.items": [{"x.com.samsung.da.unit": "Celsius"}]}
|
||||
assert desc.native_min_fn(celsius_rep) == 30.0
|
||||
assert desc.native_max_fn(celsius_rep) == 270.0
|
||||
fahrenheit_rep = _fahrenheit_rep()
|
||||
@@ -119,6 +135,7 @@ def test_oven_setpoint_native_bounds_track_live_unit():
|
||||
# OVEN_MODE — SelectDesc with non-empty options
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_oven_mode_options_nonempty():
|
||||
desc = oven.OVEN_MODE.entities[0]
|
||||
assert callable(desc.options)
|
||||
@@ -134,23 +151,25 @@ def test_oven_mode_options_reads_live_supported_modes():
|
||||
"""issue #138: the device's own supportedModes list is used verbatim
|
||||
when present, instead of the static _OVEN_MODES guess."""
|
||||
desc = oven.OVEN_MODE.entities[0]
|
||||
resources = {'/mode/vs/0': {
|
||||
'x.com.samsung.da.supportedModes': ['Bake', 'AirFryer', 'SelfClean'],
|
||||
}}
|
||||
assert desc.options(resources) == ['Bake', 'AirFryer', 'SelfClean']
|
||||
resources = {
|
||||
"/mode/vs/0": {
|
||||
"x.com.samsung.da.supportedModes": ["Bake", "AirFryer", "SelfClean"],
|
||||
}
|
||||
}
|
||||
assert desc.options(resources) == ["Bake", "AirFryer", "SelfClean"]
|
||||
|
||||
|
||||
def test_oven_mode_write_round_trips():
|
||||
desc = oven.OVEN_MODE.entities[0]
|
||||
valid_mode = desc.options({})[1] # e.g. 'Bake'
|
||||
valid_mode = desc.options({})[1] # e.g. 'Bake'
|
||||
path, body = desc.write_fn(valid_mode, {})
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body['x.com.samsung.da.modes'] == [valid_mode]
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body["x.com.samsung.da.modes"] == [valid_mode]
|
||||
|
||||
|
||||
def test_oven_mode_rejects_unknown():
|
||||
desc = oven.OVEN_MODE.entities[0]
|
||||
assert desc.write_fn('SpaghettiMode', {}) is None
|
||||
assert desc.write_fn("SpaghettiMode", {}) is None
|
||||
|
||||
|
||||
def test_oven_mode_write_validates_against_live_supported_modes():
|
||||
@@ -159,11 +178,11 @@ def test_oven_mode_write_validates_against_live_supported_modes():
|
||||
are accepted, and a mode outside the device's own list is rejected even
|
||||
if some other model's static guess would have allowed it."""
|
||||
desc = oven.OVEN_MODE.entities[0]
|
||||
rep = {'x.com.samsung.da.supportedModes': ['Bake', 'AirFryer', 'SelfClean']}
|
||||
path, body = desc.write_fn('AirFryer', rep)
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body['x.com.samsung.da.modes'] == ['AirFryer']
|
||||
assert desc.write_fn('FrozenPizzaPlus', rep) is None
|
||||
rep = {"x.com.samsung.da.supportedModes": ["Bake", "AirFryer", "SelfClean"]}
|
||||
path, body = desc.write_fn("AirFryer", rep)
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body["x.com.samsung.da.modes"] == ["AirFryer"]
|
||||
assert desc.write_fn("FrozenPizzaPlus", rep) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -173,54 +192,59 @@ def test_oven_mode_write_validates_against_live_supported_modes():
|
||||
# merges the result into the array itself. No read-modify-write needed.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _mode_rep(*extra_opts):
|
||||
return {'x.com.samsung.da.options': [
|
||||
'UpperLamp_Off', 'Sound_On', 'fastpreheat_Off', *extra_opts,
|
||||
]}
|
||||
return {
|
||||
"x.com.samsung.da.options": [
|
||||
"UpperLamp_Off",
|
||||
"Sound_On",
|
||||
"fastpreheat_Off",
|
||||
*extra_opts,
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_lamp_write_is_single_token():
|
||||
desc = next(e for e in oven.OVEN_MODE.entities if e.key == 'lamp')
|
||||
path, body = desc.write_fn('On', _mode_rep())
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['UpperLamp_On']}
|
||||
desc = next(e for e in oven.OVEN_MODE.entities if e.key == "lamp")
|
||||
path, body = desc.write_fn("On", _mode_rep())
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["UpperLamp_On"]}
|
||||
|
||||
|
||||
def test_lamp_write_requires_existing_options():
|
||||
desc = next(e for e in oven.OVEN_MODE.entities if e.key == 'lamp')
|
||||
assert desc.write_fn('On', {}) is None
|
||||
desc = next(e for e in oven.OVEN_MODE.entities if e.key == "lamp")
|
||||
assert desc.write_fn("On", {}) is None
|
||||
|
||||
|
||||
def test_sound_write_is_single_token():
|
||||
desc = next(e for e in oven.OVEN_MODE.entities if e.key == 'sound')
|
||||
path, body = desc.write_fn('Off', _mode_rep())
|
||||
assert body == {'x.com.samsung.da.options': ['Sound_Off']}
|
||||
desc = next(e for e in oven.OVEN_MODE.entities if e.key == "sound")
|
||||
_path, body = desc.write_fn("Off", _mode_rep())
|
||||
assert body == {"x.com.samsung.da.options": ["Sound_Off"]}
|
||||
|
||||
|
||||
def test_natural_steam_write_is_single_token():
|
||||
"""NaturalSteam's slot may be absent from the live rep until first
|
||||
write -- the single-token write covers both the insert and replace case
|
||||
identically, since the device merges by prefix either way."""
|
||||
desc = next(e for e in oven.OVEN_MODE.entities if e.key == 'natural_steam')
|
||||
path, body = desc.write_fn('On', _mode_rep()) # no NaturalSteam_* in rep
|
||||
assert body == {'x.com.samsung.da.options': ['NaturalSteam_On']}
|
||||
desc = next(e for e in oven.OVEN_MODE.entities if e.key == "natural_steam")
|
||||
_path, body = desc.write_fn("On", _mode_rep()) # no NaturalSteam_* in rep
|
||||
assert body == {"x.com.samsung.da.options": ["NaturalSteam_On"]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OVEN_OPERATIONAL_STATE — cycle_active BinarySensorDesc
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_cycle_active_true_when_running():
|
||||
desc = next(e for e in oven.OVEN_OPERATIONAL_STATE.entities
|
||||
if e.key == 'cycle_active')
|
||||
assert desc.value_fn('Run') is True
|
||||
assert desc.value_fn('Running') is True
|
||||
desc = next(e for e in oven.OVEN_OPERATIONAL_STATE.entities if e.key == "cycle_active")
|
||||
assert desc.value_fn("Run") is True
|
||||
assert desc.value_fn("Running") is True
|
||||
|
||||
|
||||
def test_cycle_active_false_when_idle():
|
||||
desc = next(e for e in oven.OVEN_OPERATIONAL_STATE.entities
|
||||
if e.key == 'cycle_active')
|
||||
assert desc.value_fn('Ready') is False
|
||||
desc = next(e for e in oven.OVEN_OPERATIONAL_STATE.entities if e.key == "cycle_active")
|
||||
assert desc.value_fn("Ready") is False
|
||||
assert desc.value_fn(None) is False
|
||||
|
||||
|
||||
@@ -228,18 +252,16 @@ def test_cycle_active_false_when_idle():
|
||||
# OVEN_OPERATIONAL_STATE — cook_time NumberDesc
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_cook_time_write_produces_hms():
|
||||
desc = next(e for e in oven.OVEN_OPERATIONAL_STATE.entities
|
||||
if e.key == 'cook_time')
|
||||
desc = next(e for e in oven.OVEN_OPERATIONAL_STATE.entities if e.key == "cook_time")
|
||||
path, body = desc.write_fn(90, {})
|
||||
assert path == ['operational', 'state', 'vs', '0']
|
||||
assert body['x.com.samsung.da.operationTime'] == '01:30:00'
|
||||
assert body['x.com.samsung.da.remainingTime'] == '01:30:00'
|
||||
assert path == ["operational", "state", "vs", "0"]
|
||||
assert body["x.com.samsung.da.operationTime"] == "01:30:00"
|
||||
assert body["x.com.samsung.da.remainingTime"] == "01:30:00"
|
||||
|
||||
|
||||
def test_cook_time_rejects_out_of_range():
|
||||
desc = next(e for e in oven.OVEN_OPERATIONAL_STATE.entities
|
||||
if e.key == 'cook_time')
|
||||
desc = next(e for e in oven.OVEN_OPERATIONAL_STATE.entities if e.key == "cook_time")
|
||||
assert desc.write_fn(-1, {}) is None
|
||||
assert desc.write_fn(1440, {}) is None
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
"""Tests for range/cooktop-oven combo support (issue #44)."""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.capabilities import range as range_caps
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _range():
|
||||
resources = _load_device('range')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("range")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -24,7 +25,7 @@ def _state():
|
||||
|
||||
def test_range_model_resolves_to_range_registry():
|
||||
reg, _ = _range()
|
||||
assert reg is not None and reg.name == 'range'
|
||||
assert reg is not None and reg.name == "range"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -39,11 +40,21 @@ def test_no_unbound_hrefs():
|
||||
def test_expected_entities_present():
|
||||
state = _state()
|
||||
for key in (
|
||||
'power_switch', 'oven_setpoint', 'current_temp_c', 'oven_mode',
|
||||
'machine_state', 'door_open', 'cloud_connected', 'cooktop_state',
|
||||
'cooktop_safety_shutoff_enabled',
|
||||
'burner_0_power_level', 'burner_0_state', 'burner_0_hot_surface',
|
||||
'burner_3_power_level', 'burner_3_state', 'burner_3_hot_surface',
|
||||
"power_switch",
|
||||
"oven_setpoint",
|
||||
"current_temp_c",
|
||||
"oven_mode",
|
||||
"machine_state",
|
||||
"door_open",
|
||||
"cloud_connected",
|
||||
"cooktop_state",
|
||||
"cooktop_safety_shutoff_enabled",
|
||||
"burner_0_power_level",
|
||||
"burner_0_state",
|
||||
"burner_0_hot_surface",
|
||||
"burner_3_power_level",
|
||||
"burner_3_state",
|
||||
"burner_3_hot_surface",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
@@ -52,71 +63,69 @@ def test_unreported_burners_gated_out():
|
||||
"""Dump reports numberOfBurners=4 (indices 0-3) -- burner slots 4/5 of
|
||||
MAX_BURNERS must not appear as entities."""
|
||||
state = _state()
|
||||
for key in ('burner_4_power_level', 'burner_5_power_level'):
|
||||
for key in ("burner_4_power_level", "burner_5_power_level"):
|
||||
assert key not in state, key
|
||||
|
||||
|
||||
def test_burner_power_level_write_is_read_modify_write():
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities
|
||||
if e.key == 'burner_1_power_level')
|
||||
rep = {'burnerList': [
|
||||
{'burnerNumber': 0, 'powerLevel': '3'},
|
||||
{'burnerNumber': 1, 'powerLevel': '0'},
|
||||
]}
|
||||
path, body = desc.write_fn('boost', rep)
|
||||
assert path == ['cooktop', 'status', 'vs', '0']
|
||||
burners = {b['burnerNumber']: b['powerLevel'] for b in body['burnerList']}
|
||||
assert burners[1] == 'boost'
|
||||
assert burners[0] == '3' # sibling burner untouched
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities if e.key == "burner_1_power_level")
|
||||
rep = {
|
||||
"burnerList": [
|
||||
{"burnerNumber": 0, "powerLevel": "3"},
|
||||
{"burnerNumber": 1, "powerLevel": "0"},
|
||||
]
|
||||
}
|
||||
path, body = desc.write_fn("boost", rep)
|
||||
assert path == ["cooktop", "status", "vs", "0"]
|
||||
burners = {b["burnerNumber"]: b["powerLevel"] for b in body["burnerList"]}
|
||||
assert burners[1] == "boost"
|
||||
assert burners[0] == "3" # sibling burner untouched
|
||||
|
||||
|
||||
def test_burner_power_level_write_rejects_missing_burner():
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities
|
||||
if e.key == 'burner_2_power_level')
|
||||
rep = {'burnerList': [{'burnerNumber': 0, 'powerLevel': '0'}]}
|
||||
assert desc.write_fn('5', rep) is None
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities if e.key == "burner_2_power_level")
|
||||
rep = {"burnerList": [{"burnerNumber": 0, "powerLevel": "0"}]}
|
||||
assert desc.write_fn("5", rep) is None
|
||||
|
||||
|
||||
def test_burner_hot_surface_true_when_not_normal():
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities
|
||||
if e.key == 'burner_0_hot_surface')
|
||||
assert desc.value_fn([{'burnerNumber': 0, 'hotSurfaceState': 'hot'}]) is True
|
||||
assert desc.value_fn([{'burnerNumber': 0, 'hotSurfaceState': 'normal'}]) is False
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities if e.key == "burner_0_hot_surface")
|
||||
assert desc.value_fn([{"burnerNumber": 0, "hotSurfaceState": "hot"}]) is True
|
||||
assert desc.value_fn([{"burnerNumber": 0, "hotSurfaceState": "normal"}]) is False
|
||||
|
||||
|
||||
def test_burner_pan_detected(): # issue #86
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities
|
||||
if e.key == 'burner_0_pan_detected')
|
||||
assert desc.value_fn([{'burnerNumber': 0, 'panDetection': True}]) is True
|
||||
assert desc.value_fn([{'burnerNumber': 0, 'panDetection': False}]) is False
|
||||
assert desc.value_fn([{'burnerNumber': 1, 'panDetection': True}]) is False # different burner
|
||||
def test_burner_pan_detected(): # issue #86
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities if e.key == "burner_0_pan_detected")
|
||||
assert desc.value_fn([{"burnerNumber": 0, "panDetection": True}]) is True
|
||||
assert desc.value_fn([{"burnerNumber": 0, "panDetection": False}]) is False
|
||||
assert desc.value_fn([{"burnerNumber": 1, "panDetection": True}]) is False # different burner
|
||||
|
||||
|
||||
def test_cooktop_power_is_read_only(): # issue #86
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities if e.key == 'cooktop_power')
|
||||
assert desc.value_fn('On') is True
|
||||
assert desc.value_fn('Off') is False
|
||||
assert not hasattr(desc, 'write_fn') # BinarySensorDesc has no write path at all
|
||||
def test_cooktop_power_is_read_only(): # issue #86
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities if e.key == "cooktop_power")
|
||||
assert desc.value_fn("On") is True
|
||||
assert desc.value_fn("Off") is False
|
||||
assert not hasattr(desc, "write_fn") # BinarySensorDesc has no write path at all
|
||||
|
||||
|
||||
def test_cooktop_child_lock_write(): # issue #86
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities if e.key == 'cooktop_child_lock')
|
||||
assert desc.value_fn('on') is True
|
||||
assert desc.value_fn('off') is False
|
||||
path, body = desc.write_fn('On', {})
|
||||
assert path == ['cooktop', 'status', 'vs', '0']
|
||||
assert body == {'childLock': 'on'}
|
||||
assert desc.write_fn('Bogus', {}) is None
|
||||
def test_cooktop_child_lock_write(): # issue #86
|
||||
desc = next(e for e in range_caps.COOKTOP_STATUS.entities if e.key == "cooktop_child_lock")
|
||||
assert desc.value_fn("on") is True
|
||||
assert desc.value_fn("off") is False
|
||||
path, body = desc.write_fn("On", {})
|
||||
assert path == ["cooktop", "status", "vs", "0"]
|
||||
assert body == {"childLock": "on"}
|
||||
assert desc.write_fn("Bogus", {}) is None
|
||||
|
||||
|
||||
def test_probe_status_temperature_unit_reads_live_field(): # issue #86
|
||||
desc = next(e for e in range_caps.PROBE_STATUS.entities if e.key == 'probe_temperature')
|
||||
assert desc.unit_fn({'temperatureUnit': 'C'}) == '°C'
|
||||
assert desc.unit_fn({'temperatureUnit': 'F'}) == '°F'
|
||||
assert desc.unit_fn({}) == '°C'
|
||||
def test_probe_status_temperature_unit_reads_live_field(): # issue #86
|
||||
desc = next(e for e in range_caps.PROBE_STATUS.entities if e.key == "probe_temperature")
|
||||
assert desc.unit_fn({"temperatureUnit": "C"}) == "°C"
|
||||
assert desc.unit_fn({"temperatureUnit": "F"}) == "°F"
|
||||
assert desc.unit_fn({}) == "°C"
|
||||
|
||||
|
||||
def test_probe_status_connected_value_fn(): # issue #86
|
||||
desc = next(e for e in range_caps.PROBE_STATUS.entities if e.key == 'probe_connected')
|
||||
assert desc.value_fn('Connected') is True
|
||||
assert desc.value_fn('Disconnected') is False
|
||||
def test_probe_status_connected_value_fn(): # issue #86
|
||||
desc = next(e for e in range_caps.PROBE_STATUS.entities if e.key == "probe_connected")
|
||||
assert desc.value_fn("Connected") is True
|
||||
assert desc.value_fn("Disconnected") is False
|
||||
@@ -4,16 +4,22 @@ from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.capabilities import range_hood
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.entities import FanDesc
|
||||
from custom_components.localthings.registry.entities import (
|
||||
BinarySensorDesc,
|
||||
ButtonDesc,
|
||||
FanDesc,
|
||||
SelectDesc,
|
||||
SwitchDesc,
|
||||
)
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _hood():
|
||||
resources = _load_device('range_hood')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("range_hood")
|
||||
info = resources["/information/vs/0"]
|
||||
registry = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'],
|
||||
info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return registry, resources
|
||||
|
||||
@@ -21,7 +27,9 @@ def _hood():
|
||||
def _state():
|
||||
registry, resources = _hood()
|
||||
bound = discover(
|
||||
resources, registry.capabilities, registry.pattern_capabilities,
|
||||
resources,
|
||||
registry.capabilities,
|
||||
registry.pattern_capabilities,
|
||||
)
|
||||
return flatten(bound, resources)
|
||||
|
||||
@@ -29,7 +37,7 @@ def _state():
|
||||
def test_ahd_model_resolves_to_range_hood_registry():
|
||||
registry, _ = _hood()
|
||||
assert registry is not None
|
||||
assert registry.name == 'range_hood'
|
||||
assert registry.name == "range_hood"
|
||||
|
||||
|
||||
def test_range_hood_has_no_unbound_hrefs():
|
||||
@@ -46,99 +54,116 @@ def test_range_hood_has_no_unbound_hrefs():
|
||||
|
||||
def test_range_hood_fixture_values():
|
||||
state = _state()
|
||||
assert state['fan'] == '14'
|
||||
assert state['alarm_code'] == 'none'
|
||||
assert state['automatic_operation'] is False
|
||||
assert state['lamp'] is False
|
||||
assert state['lamp_brightness'] == '2'
|
||||
assert state['hood_filter_usage'] == 100
|
||||
assert state['hood_filter_status'] == 'wash'
|
||||
assert state['energy_kwh'] == 165.62
|
||||
assert state['clean_level'] == 2
|
||||
assert state['dust'] == 18
|
||||
assert state['fine_dust'] == 14
|
||||
assert state['super_fine_dust'] == 9
|
||||
assert state['periodic_air_sensing'] is False
|
||||
assert state['air_sensing_state'] == 'NonProcessing'
|
||||
assert state['last_air_sensing_level'] == 'Kr2'
|
||||
assert state['after_run_active'] is False
|
||||
assert state['after_run_progress'] == 0
|
||||
assert state["fan"] == "14"
|
||||
assert state["alarm_code"] == "none"
|
||||
assert state["automatic_operation"] is False
|
||||
assert state["lamp"] is False
|
||||
assert state["lamp_brightness"] == "2"
|
||||
assert state["hood_filter_usage"] == 100
|
||||
assert state["hood_filter_status"] == "wash"
|
||||
assert state["energy_kwh"] == 165.62
|
||||
assert state["clean_level"] == 2
|
||||
assert state["dust"] == 18
|
||||
assert state["fine_dust"] == 14
|
||||
assert state["super_fine_dust"] == 9
|
||||
assert state["periodic_air_sensing"] is False
|
||||
assert state["air_sensing_state"] == "NonProcessing"
|
||||
assert state["last_air_sensing_level"] == "Kr2"
|
||||
assert state["after_run_active"] is False
|
||||
assert state["after_run_progress"] == 0
|
||||
|
||||
|
||||
def test_one_composite_fan_is_bound():
|
||||
registry, resources = _hood()
|
||||
bound = discover(
|
||||
resources, registry.capabilities, registry.pattern_capabilities,
|
||||
resources,
|
||||
registry.capabilities,
|
||||
registry.pattern_capabilities,
|
||||
)
|
||||
fans = [entity for entity in bound if isinstance(entity.desc, FanDesc)]
|
||||
assert len(fans) == 1
|
||||
assert fans[0].href == '/hood/fanspeed/vs/0'
|
||||
assert fans[0].href == "/hood/fanspeed/vs/0"
|
||||
|
||||
|
||||
def test_fan_write_contract():
|
||||
desc = range_hood.HOOD_FAN.entities[0]
|
||||
desc = next(e for e in range_hood.HOOD_FAN.entities if isinstance(e, FanDesc))
|
||||
rep = {
|
||||
'x.com.samsung.da.hood.supportedFanSpeed': ['14', '15', '16', '17'],
|
||||
"x.com.samsung.da.hood.supportedFanSpeed": ["14", "15", "16", "17"],
|
||||
}
|
||||
assert desc.write_fn(('power', True), rep) == (
|
||||
['power', '0'], {'value': True},
|
||||
assert desc.write_fn is not None
|
||||
assert desc.write_fn(("power", True), rep) == (
|
||||
["power", "0"],
|
||||
{"value": True},
|
||||
)
|
||||
assert desc.write_fn(('power', False), rep) == (
|
||||
['power', '0'], {'value': False},
|
||||
assert desc.write_fn(("power", False), rep) == (
|
||||
["power", "0"],
|
||||
{"value": False},
|
||||
)
|
||||
assert desc.write_fn(('power', True, '/power/vs/0'), rep) == (
|
||||
['power', 'vs', '0'], {'x.com.samsung.da.power': 'On'},
|
||||
assert desc.write_fn(("power", True, "/power/vs/0"), rep) == (
|
||||
["power", "vs", "0"],
|
||||
{"x.com.samsung.da.power": "On"},
|
||||
)
|
||||
assert desc.write_fn(('power', False, '/power/vs/0'), rep) == (
|
||||
['power', 'vs', '0'], {'x.com.samsung.da.power': 'Off'},
|
||||
assert desc.write_fn(("power", False, "/power/vs/0"), rep) == (
|
||||
["power", "vs", "0"],
|
||||
{"x.com.samsung.da.power": "Off"},
|
||||
)
|
||||
assert desc.write_fn(('power', True, '/not-a-power-resource'), rep) is None
|
||||
assert desc.write_fn(('speed', '16'), rep) == (
|
||||
['hood', 'fanspeed', 'vs', '0'],
|
||||
{'x.com.samsung.da.hood.fanSpeed': '16'},
|
||||
assert desc.write_fn(("power", True, "/not-a-power-resource"), rep) is None
|
||||
assert desc.write_fn(("speed", "16"), rep) == (
|
||||
["hood", "fanspeed", "vs", "0"],
|
||||
{"x.com.samsung.da.hood.fanSpeed": "16"},
|
||||
)
|
||||
assert desc.write_fn(('speed', '99'), rep) is None
|
||||
assert desc.write_fn(("speed", "99"), rep) is None
|
||||
|
||||
rep_fallback = {
|
||||
'x.com.samsung.da.hood.settableMinFanSpeed': '0',
|
||||
'x.com.samsung.da.hood.settableMaxFanSpeed': '3',
|
||||
"x.com.samsung.da.hood.settableMinFanSpeed": "0",
|
||||
"x.com.samsung.da.hood.settableMaxFanSpeed": "3",
|
||||
}
|
||||
assert desc.write_fn(('speed', '2'), rep_fallback) == (
|
||||
['hood', 'fanspeed', 'vs', '0'],
|
||||
{'x.com.samsung.da.hood.fanSpeed': '2'},
|
||||
assert desc.write_fn(("speed", "2"), rep_fallback) == (
|
||||
["hood", "fanspeed", "vs", "0"],
|
||||
{"x.com.samsung.da.hood.fanSpeed": "2"},
|
||||
)
|
||||
assert desc.write_fn(('speed', '4'), rep_fallback) is None
|
||||
assert desc.write_fn(("speed", "4"), rep_fallback) is None
|
||||
|
||||
|
||||
def test_lamp_write_contract():
|
||||
lamp, brightness = range_hood.HOOD_LAMP.entities
|
||||
rep = {'x.com.samsung.lamp.range': ['1', '2']}
|
||||
assert lamp.write_fn('On', rep) == (
|
||||
['hood', 'lamp', 'vs', '0'], {'x.com.samsung.lamp.power': 'On'},
|
||||
lamp = next(e for e in range_hood.HOOD_LAMP.entities if isinstance(e, SwitchDesc))
|
||||
brightness = next(e for e in range_hood.HOOD_LAMP.entities if isinstance(e, SelectDesc))
|
||||
rep = {"x.com.samsung.lamp.range": ["1", "2"]}
|
||||
assert lamp.write_fn is not None
|
||||
assert brightness.write_fn is not None
|
||||
assert lamp.write_fn("On", rep) == (
|
||||
["hood", "lamp", "vs", "0"],
|
||||
{"x.com.samsung.lamp.power": "On"},
|
||||
)
|
||||
assert lamp.write_fn('Off', rep) == (
|
||||
['hood', 'lamp', 'vs', '0'], {'x.com.samsung.lamp.power': 'Off'},
|
||||
assert lamp.write_fn("Off", rep) == (
|
||||
["hood", "lamp", "vs", "0"],
|
||||
{"x.com.samsung.lamp.power": "Off"},
|
||||
)
|
||||
assert brightness.write_fn('1', rep) == (
|
||||
['hood', 'lamp', 'vs', '0'], {'x.com.samsung.lamp.current': '1'},
|
||||
assert brightness.write_fn("1", rep) == (
|
||||
["hood", "lamp", "vs", "0"],
|
||||
{"x.com.samsung.lamp.current": "1"},
|
||||
)
|
||||
assert brightness.write_fn('2', rep) == (
|
||||
['hood', 'lamp', 'vs', '0'], {'x.com.samsung.lamp.current': '2'},
|
||||
assert brightness.write_fn("2", rep) == (
|
||||
["hood", "lamp", "vs", "0"],
|
||||
{"x.com.samsung.lamp.current": "2"},
|
||||
)
|
||||
assert brightness.write_fn('Unsupported', rep) is None
|
||||
assert brightness.write_fn("Unsupported", rep) is None
|
||||
|
||||
|
||||
def test_after_run_cancel_write_contract():
|
||||
"""issue #147: /afterrun/vs/0 was previously unbound. runningCancel's
|
||||
only observed value is the command name itself, so cancel is modeled as
|
||||
a ButtonDesc that writes that value back."""
|
||||
active, progress, cancel = range_hood.AFTER_RUN.entities
|
||||
assert cancel.write_fn('Cancel', {}) == (
|
||||
['afterrun', 'vs', '0'], {'x.com.samsung.da.runningCancel': 'Cancel'},
|
||||
cancel = next(e for e in range_hood.AFTER_RUN.entities if isinstance(e, ButtonDesc))
|
||||
assert cancel.write_fn is not None
|
||||
assert cancel.write_fn("Cancel", {}) == (
|
||||
["afterrun", "vs", "0"],
|
||||
{"x.com.samsung.da.runningCancel": "Cancel"},
|
||||
)
|
||||
|
||||
|
||||
def test_after_run_active_reads_on_off():
|
||||
active, progress, cancel = range_hood.AFTER_RUN.entities
|
||||
assert active.value_fn('On') is True
|
||||
assert active.value_fn('Off') is False
|
||||
active = next(e for e in range_hood.AFTER_RUN.entities if isinstance(e, BinarySensorDesc))
|
||||
assert active.value_fn is not None
|
||||
assert active.value_fn("On") is True
|
||||
assert active.value_fn("Off") is False
|
||||
@@ -1,5 +1,7 @@
|
||||
"""HA fan-entity mapping tests for the range hood."""
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from custom_components.localthings.fan import LocalThingsRangeHoodFan
|
||||
from custom_components.localthings.registry.by_type import microwave, range_hood
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
@@ -8,9 +10,9 @@ from tests.conftest import _load_device
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-HOOD-SERIAL'
|
||||
device_info = {}
|
||||
data = {}
|
||||
device_serial = "TEST-HOOD-SERIAL"
|
||||
device_info: ClassVar[dict] = {}
|
||||
data: ClassVar[dict] = {}
|
||||
|
||||
def __init__(self, resources):
|
||||
self.last_resources = resources
|
||||
@@ -37,7 +39,8 @@ def _entity(resources, coordinator=None, registry=range_hood.REGISTRY):
|
||||
)
|
||||
fan_bound = next(item for item in bound if isinstance(item.desc, FanDesc))
|
||||
return LocalThingsRangeHoodFan(
|
||||
coordinator or _FakeCoordinator(resources), fan_bound,
|
||||
coordinator or _FakeCoordinator(resources),
|
||||
fan_bound,
|
||||
)
|
||||
|
||||
|
||||
@@ -46,56 +49,48 @@ def _microwave_entity(resources, coordinator=None):
|
||||
|
||||
|
||||
def test_power_off_maps_to_zero_percent_and_four_retained_speeds():
|
||||
entity = _entity(_load_device('range_hood'))
|
||||
entity = _entity(_load_device("range_hood"))
|
||||
assert entity.is_on is False
|
||||
assert entity.speed_count == 4
|
||||
assert entity.percentage == 0
|
||||
|
||||
|
||||
def test_active_codes_map_to_ordered_percentages():
|
||||
resources = _load_device('range_hood')
|
||||
resources['/power/0']['value'] = True
|
||||
resources = _load_device("range_hood")
|
||||
resources["/power/0"]["value"] = True
|
||||
|
||||
resources['/hood/fanspeed/vs/0'][
|
||||
'x.com.samsung.da.hood.fanSpeed'
|
||||
] = '14'
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "14"
|
||||
assert _entity(resources).percentage == 25
|
||||
|
||||
resources['/hood/fanspeed/vs/0'][
|
||||
'x.com.samsung.da.hood.fanSpeed'
|
||||
] = '15'
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "15"
|
||||
assert _entity(resources).percentage == 50
|
||||
|
||||
resources['/hood/fanspeed/vs/0'][
|
||||
'x.com.samsung.da.hood.fanSpeed'
|
||||
] = '16'
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "16"
|
||||
assert _entity(resources).percentage == 75
|
||||
|
||||
resources['/hood/fanspeed/vs/0'][
|
||||
'x.com.samsung.da.hood.fanSpeed'
|
||||
] = '17'
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "17"
|
||||
assert _entity(resources).percentage == 100
|
||||
|
||||
|
||||
async def test_power_write_prefers_standard_resource_when_both_exist():
|
||||
resources = _load_device('range_hood')
|
||||
resources = _load_device("range_hood")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_turn_on()
|
||||
|
||||
assert coordinator.commands[-1][1] == ('power', True, '/power/0')
|
||||
assert coordinator.commands[-1][1] == ("power", True, "/power/0")
|
||||
|
||||
|
||||
async def test_power_write_falls_back_to_vendor_resource():
|
||||
resources = _load_device('range_hood')
|
||||
resources.pop('/power/0')
|
||||
resources = _load_device("range_hood")
|
||||
resources.pop("/power/0")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_turn_off()
|
||||
|
||||
assert coordinator.commands[-1][1] == ('power', False, '/power/vs/0')
|
||||
assert coordinator.commands[-1][1] == ("power", False, "/power/vs/0")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -104,19 +99,20 @@ async def test_power_write_falls_back_to_vendor_resource():
|
||||
# itself the off state.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_standalone_hood_has_separate_power():
|
||||
"""Explicit converse of the microwave case below: guards the
|
||||
discriminator itself, not just its downstream effects, so a future
|
||||
change to it fails loudly here instead of only via behavioral drift."""
|
||||
entity = _entity(_load_device('range_hood'))
|
||||
entity = _entity(_load_device("range_hood"))
|
||||
assert entity._has_separate_power() is True
|
||||
assert entity._speed_zero_is_off() is False
|
||||
|
||||
|
||||
def test_microwave_vent_fan_has_no_separate_power_resource():
|
||||
resources = _load_device('microwave_me7500d')
|
||||
assert '/power/0' not in resources
|
||||
assert '/power/vs/0' not in resources
|
||||
resources = _load_device("microwave_me7500d")
|
||||
assert "/power/0" not in resources
|
||||
assert "/power/vs/0" not in resources
|
||||
entity = _microwave_entity(resources)
|
||||
assert entity._has_separate_power() is False
|
||||
assert entity._speed_zero_is_off() is True
|
||||
@@ -129,9 +125,9 @@ async def test_combi_microwave_with_cavity_power_still_treats_zero_speed_as_fan_
|
||||
_speed_zero_is_off must key off the hood resource itself, not merely
|
||||
"some power resource exists on this device", so turning the fan off
|
||||
writes fan speed rather than the shared cavity power resource."""
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources['/power/0'] = {'value': True}
|
||||
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '2'
|
||||
resources = _load_device("microwave_me7500d")
|
||||
resources["/power/0"] = {"value": True}
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "2"
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _microwave_entity(resources, coordinator)
|
||||
|
||||
@@ -140,13 +136,13 @@ async def test_combi_microwave_with_cavity_power_still_treats_zero_speed_as_fan_
|
||||
|
||||
await entity.async_turn_off()
|
||||
|
||||
assert coordinator.commands[-1][1] == ('speed', '0')
|
||||
assert coordinator.commands[-1][1] == ("speed", "0")
|
||||
|
||||
|
||||
def test_microwave_vent_fan_off_state_excludes_zero_from_speed_codes():
|
||||
"""supportedFanSpeed reports ['0'..'4'] with 0 meaning off -- unlike the
|
||||
standalone hood's codes, which never include an off entry."""
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources = _load_device("microwave_me7500d")
|
||||
entity = _microwave_entity(resources)
|
||||
assert entity.is_on is False
|
||||
assert entity.percentage == 0
|
||||
@@ -154,59 +150,59 @@ def test_microwave_vent_fan_off_state_excludes_zero_from_speed_codes():
|
||||
|
||||
|
||||
def test_microwave_vent_fan_nonzero_speed_reads_as_on():
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '2'
|
||||
resources = _load_device("microwave_me7500d")
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "2"
|
||||
entity = _microwave_entity(resources)
|
||||
assert entity.is_on is True
|
||||
assert entity.percentage == 50 # 2nd of ['1', '2', '3', '4']
|
||||
|
||||
|
||||
async def test_microwave_vent_fan_turn_off_writes_zero_speed_not_power():
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '2'
|
||||
resources = _load_device("microwave_me7500d")
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "2"
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _microwave_entity(resources, coordinator)
|
||||
|
||||
await entity.async_turn_off()
|
||||
|
||||
assert coordinator.commands[-1][1] == ('speed', '0')
|
||||
assert coordinator.commands[-1][1] == ("speed", "0")
|
||||
|
||||
|
||||
async def test_microwave_vent_fan_turn_on_without_percentage_picks_lowest_speed():
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources = _load_device("microwave_me7500d")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _microwave_entity(resources, coordinator)
|
||||
|
||||
await entity.async_turn_on()
|
||||
|
||||
assert coordinator.commands[-1][1] == ('speed', '1')
|
||||
assert coordinator.commands[-1][1] == ("speed", "1")
|
||||
|
||||
|
||||
async def test_microwave_vent_fan_set_percentage_writes_speed_only():
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources = _load_device("microwave_me7500d")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _microwave_entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_percentage(100)
|
||||
|
||||
assert coordinator.commands == [(entity._bound, ('speed', '4'))]
|
||||
assert coordinator.commands == [(entity._bound, ("speed", "4"))]
|
||||
|
||||
|
||||
async def test_microwave_vent_fan_turn_on_with_percentage_writes_speed_directly():
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources = _load_device("microwave_me7500d")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _microwave_entity(resources, coordinator)
|
||||
|
||||
await entity.async_turn_on(percentage=75)
|
||||
|
||||
assert coordinator.commands == [(entity._bound, ('speed', '3'))]
|
||||
assert coordinator.commands == [(entity._bound, ("speed", "3"))]
|
||||
|
||||
|
||||
async def test_microwave_vent_fan_turn_on_without_percentage_when_already_on_is_a_noop():
|
||||
"""A scene or automation calling fan.turn_on on an already-running vent
|
||||
fan must not reset it to the lowest speed."""
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '3'
|
||||
resources = _load_device("microwave_me7500d")
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "3"
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _microwave_entity(resources, coordinator)
|
||||
|
||||
@@ -216,27 +212,26 @@ async def test_microwave_vent_fan_turn_on_without_percentage_when_already_on_is_
|
||||
|
||||
|
||||
async def test_microwave_vent_fan_set_percentage_zero_turns_off():
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '2'
|
||||
resources = _load_device("microwave_me7500d")
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.fanSpeed"] = "2"
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _microwave_entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_percentage(0)
|
||||
|
||||
assert coordinator.commands[-1][1] == ('speed', '0')
|
||||
assert coordinator.commands[-1][1] == ("speed", "0")
|
||||
|
||||
|
||||
def test_microwave_vent_fan_missing_supported_fan_speed_falls_back_to_settable_min_max():
|
||||
"""Hardware omitting supportedFanSpeed (e.g. ME8000T / issue #172) falls back
|
||||
to building speed codes from settableMinFanSpeed ('0') and settableMaxFanSpeed ('3')."""
|
||||
resources = _load_device('microwave_me7500d')
|
||||
resources['/hood/fanspeed/vs/0'].pop('x.com.samsung.da.hood.supportedFanSpeed', None)
|
||||
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.settableMinFanSpeed'] = '0'
|
||||
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.settableMaxFanSpeed'] = '3'
|
||||
resources = _load_device("microwave_me7500d")
|
||||
resources["/hood/fanspeed/vs/0"].pop("x.com.samsung.da.hood.supportedFanSpeed", None)
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.settableMinFanSpeed"] = "0"
|
||||
resources["/hood/fanspeed/vs/0"]["x.com.samsung.da.hood.settableMaxFanSpeed"] = "3"
|
||||
|
||||
entity = _microwave_entity(resources)
|
||||
assert entity._all_speed_codes() == ['0', '1', '2', '3']
|
||||
assert entity._active_speed_codes() == ['1', '2', '3']
|
||||
assert entity._all_speed_codes() == ["0", "1", "2", "3"]
|
||||
assert entity._active_speed_codes() == ["1", "2", "3"]
|
||||
assert entity.speed_count == 3
|
||||
assert entity.supported_features & 1 # FanEntityFeature.SET_SPEED is present
|
||||
|
||||
@@ -4,16 +4,16 @@ range_no_info detection path still resolves this model with zero unbound
|
||||
hrefs, plus oven.OVEN_MODE reading this dump's ConvectionRoast/KeepWarm/
|
||||
BreadProof/AirFryer/Dehydrate/SelfClean/SteamClean modes live from its own
|
||||
/mode/vs/0 supportedModes rather than needing them hardcoded."""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_resources
|
||||
from custom_components.localthings.registry.capabilities import oven
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _range():
|
||||
resources = _load_device('range_ne63a6511')
|
||||
resources = _load_device("range_ne63a6511")
|
||||
reg = for_device_by_resources(resources)
|
||||
return reg, resources
|
||||
|
||||
@@ -26,7 +26,7 @@ def _state():
|
||||
|
||||
def test_resolves_to_range_registry():
|
||||
reg, _ = _range()
|
||||
assert reg is not None and reg.name == 'range'
|
||||
assert reg is not None and reg.name == "range"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -39,9 +39,16 @@ def test_no_unbound_hrefs():
|
||||
def test_expected_entities_present():
|
||||
state = _state()
|
||||
for key in (
|
||||
'power_switch', 'oven_setpoint', 'current_temp_c', 'oven_mode',
|
||||
'machine_state', 'door_open', 'cloud_connected', 'child_lock',
|
||||
'cooktop_running_state', 'warming_center_state',
|
||||
"power_switch",
|
||||
"oven_setpoint",
|
||||
"current_temp_c",
|
||||
"oven_mode",
|
||||
"machine_state",
|
||||
"door_open",
|
||||
"cloud_connected",
|
||||
"child_lock",
|
||||
"cooktop_running_state",
|
||||
"warming_center_state",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
@@ -56,13 +63,18 @@ def test_oven_mode_accepts_this_devices_supported_modes():
|
||||
coordinator.py's async_send_command), so this passes without needing
|
||||
those modes added to any Python list."""
|
||||
_, resources = _range()
|
||||
live_rep = resources['/mode/vs/0']
|
||||
live_rep = resources["/mode/vs/0"]
|
||||
desc = oven.OVEN_MODE.entities[0]
|
||||
assert desc.options(resources) == live_rep['x.com.samsung.da.supportedModes']
|
||||
assert desc.options(resources) == live_rep["x.com.samsung.da.supportedModes"]
|
||||
for mode in (
|
||||
'ConvectionRoast', 'KeepWarm', 'BreadProof', 'AirFryer',
|
||||
'Dehydrate', 'SelfClean', 'SteamClean',
|
||||
"ConvectionRoast",
|
||||
"KeepWarm",
|
||||
"BreadProof",
|
||||
"AirFryer",
|
||||
"Dehydrate",
|
||||
"SelfClean",
|
||||
"SteamClean",
|
||||
):
|
||||
path, body = desc.write_fn(mode, live_rep)
|
||||
assert path == ['mode', 'vs', '0']
|
||||
assert body['x.com.samsung.da.modes'] == [mode]
|
||||
assert path == ["mode", "vs", "0"]
|
||||
assert body["x.com.samsung.da.modes"] == [mode]
|
||||
@@ -8,15 +8,15 @@ phantom-switch bug (both were shipped with no exists_fn, so they bound
|
||||
unconditionally, always read off, and any write went to a token this
|
||||
firmware never recognized).
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_resources
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _range():
|
||||
resources = _load_device('range_ne6516a')
|
||||
resources = _load_device("range_ne6516a")
|
||||
reg = for_device_by_resources(resources)
|
||||
return reg, resources
|
||||
|
||||
@@ -29,7 +29,7 @@ def _state():
|
||||
|
||||
def test_resolves_to_range_registry():
|
||||
reg, _ = _range()
|
||||
assert reg is not None and reg.name == 'range'
|
||||
assert reg is not None and reg.name == "range"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -43,14 +43,14 @@ def test_fast_preheat_and_natural_steam_absent_without_their_tokens():
|
||||
"""Neither token is in this dump's options[] -- both switches must stay
|
||||
unbound rather than silently reading as an always-off phantom control."""
|
||||
state = _state()
|
||||
assert 'fast_preheat' not in state
|
||||
assert 'natural_steam' not in state
|
||||
assert "fast_preheat" not in state
|
||||
assert "natural_steam" not in state
|
||||
|
||||
|
||||
def test_energy_saving_and_cooktop_alert_present():
|
||||
state = _state()
|
||||
assert state['energy_saving'] is True
|
||||
assert state['cooktop_on_alert'] is False
|
||||
assert state["energy_saving"] is True
|
||||
assert state["cooktop_on_alert"] is False
|
||||
|
||||
|
||||
def test_child_lock_already_reads_correctly():
|
||||
@@ -62,4 +62,4 @@ def test_child_lock_already_reads_correctly():
|
||||
contract), whose 'lock' device class is inverted from a switch's plain
|
||||
on/off: False means locked/closed, matching 'Run' here."""
|
||||
state = _state()
|
||||
assert state['child_lock'] is False
|
||||
assert state["child_lock"] is False
|
||||
@@ -1,15 +1,15 @@
|
||||
"""Tests for the no-/information/vs/0, no-burner-status range variant
|
||||
(NE63B8411SS-class, issue #74)."""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_resources
|
||||
from custom_components.localthings.registry.capabilities import range as range_caps
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _range():
|
||||
resources = _load_device('range_no_info')
|
||||
resources = _load_device("range_no_info")
|
||||
reg = for_device_by_resources(resources)
|
||||
return reg, resources
|
||||
|
||||
@@ -22,7 +22,7 @@ def _state():
|
||||
|
||||
def test_resolves_to_range_registry():
|
||||
reg, _ = _range()
|
||||
assert reg is not None and reg.name == 'range'
|
||||
assert reg is not None and reg.name == "range"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -38,21 +38,31 @@ def test_no_burner_entities():
|
||||
"""This board reports no /cooktop/status/vs/0, so none of range.py's
|
||||
per-burner entities should appear -- only COOKTOP_MONITORING's."""
|
||||
state = _state()
|
||||
assert not any(k.startswith('burner_') for k in state)
|
||||
assert not any(k.startswith("burner_") for k in state)
|
||||
|
||||
|
||||
def test_expected_entities_present():
|
||||
state = _state()
|
||||
for key in (
|
||||
'power_switch', 'oven_setpoint', 'current_temp_c', 'oven_mode',
|
||||
'machine_state', 'door_open', 'cloud_connected',
|
||||
'cooktop_running_state', 'warming_center_state',
|
||||
"power_switch",
|
||||
"oven_setpoint",
|
||||
"current_temp_c",
|
||||
"oven_mode",
|
||||
"machine_state",
|
||||
"door_open",
|
||||
"cloud_connected",
|
||||
"cooktop_running_state",
|
||||
"warming_center_state",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
|
||||
def test_cooktop_monitoring_reads_live_fields():
|
||||
desc = next(e for e in range_caps.COOKTOP_MONITORING.entities if e.key == 'cooktop_running_state')
|
||||
assert desc.value_fn('Ready') == 'Ready'
|
||||
desc = next(e for e in range_caps.COOKTOP_MONITORING.entities if e.key == 'warming_center_state')
|
||||
assert desc.value_fn('Off') == 'Off'
|
||||
desc = next(
|
||||
e for e in range_caps.COOKTOP_MONITORING.entities if e.key == "cooktop_running_state"
|
||||
)
|
||||
assert desc.value_fn("Ready") == "Ready"
|
||||
desc = next(
|
||||
e for e in range_caps.COOKTOP_MONITORING.entities if e.key == "warming_center_state"
|
||||
)
|
||||
assert desc.value_fn("Off") == "Off"
|
||||
+71
-55
@@ -1,109 +1,125 @@
|
||||
"""Tests for registry.redact — the safety net for diagnostics downloads."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from custom_components.localthings.registry.batch import parse_device0_batch
|
||||
from custom_components.localthings.registry.redact import REDACTED, redact_resources
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
|
||||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||
|
||||
|
||||
def _load(name: str) -> dict:
|
||||
data = json.loads((FIXTURES / name).read_text())
|
||||
return parse_device0_batch(data['device0'])
|
||||
return parse_device0_batch(data["device0"])
|
||||
|
||||
|
||||
def test_redacts_known_sensitive_fields_in_dishwasher_dump():
|
||||
resources = _load('dishwasher_device.json')
|
||||
resources = _load("dishwasher_device.json")
|
||||
redacted = redact_resources(resources)
|
||||
|
||||
info = redacted['/information/vs/0']
|
||||
assert info['x.com.samsung.da.serialNum'] == REDACTED
|
||||
assert info['x.com.samsung.da.otnDUID'] == REDACTED
|
||||
info = redacted["/information/vs/0"]
|
||||
assert info["x.com.samsung.da.serialNum"] == REDACTED
|
||||
assert info["x.com.samsung.da.otnDUID"] == REDACTED
|
||||
|
||||
wireless = redacted['/wirelessinfo/vs/0']
|
||||
assert wireless['macaddressWiFi'] == REDACTED
|
||||
assert wireless['macaddressBLE'] == REDACTED
|
||||
wireless = redacted["/wirelessinfo/vs/0"]
|
||||
assert wireless["macaddressWiFi"] == REDACTED
|
||||
assert wireless["macaddressBLE"] == REDACTED
|
||||
|
||||
provisioning = redacted['/voice/provisioning/vs/0']
|
||||
headers = provisioning['voice.provisioning.headers']
|
||||
assert headers['login_id'] == REDACTED
|
||||
deviceinfo = provisioning['voice.provisioning.deviceinfo']
|
||||
assert deviceinfo['voice.provisioning.deviceinfo.accesstoken'] == REDACTED
|
||||
assert deviceinfo['voice.provisioning.deviceinfo.deviceid'] == REDACTED
|
||||
assert deviceinfo['voice.provisioning.deviceinfo.userid'] == REDACTED
|
||||
provisioning = redacted["/voice/provisioning/vs/0"]
|
||||
headers = provisioning["voice.provisioning.headers"]
|
||||
assert headers["login_id"] == REDACTED
|
||||
deviceinfo = provisioning["voice.provisioning.deviceinfo"]
|
||||
assert deviceinfo["voice.provisioning.deviceinfo.accesstoken"] == REDACTED
|
||||
assert deviceinfo["voice.provisioning.deviceinfo.deviceid"] == REDACTED
|
||||
assert deviceinfo["voice.provisioning.deviceinfo.userid"] == REDACTED
|
||||
|
||||
|
||||
def test_ordinary_state_fields_survive_untouched():
|
||||
resources = _load('dishwasher_device.json')
|
||||
resources = _load("dishwasher_device.json")
|
||||
redacted = redact_resources(resources)
|
||||
|
||||
op_state = redacted['/operational/state/vs/0']
|
||||
assert op_state['x.com.samsung.da.state'] == 'Run'
|
||||
assert op_state['x.com.samsung.da.progress'] == 'Finish'
|
||||
op_state = redacted["/operational/state/vs/0"]
|
||||
assert op_state["x.com.samsung.da.state"] == "Run"
|
||||
assert op_state["x.com.samsung.da.progress"] == "Finish"
|
||||
|
||||
power = redacted['/power/vs/0']
|
||||
assert power['x.com.samsung.da.power'] == 'On'
|
||||
power = redacted["/power/vs/0"]
|
||||
assert power["x.com.samsung.da.power"] == "On"
|
||||
|
||||
dishwasher = redacted['/dishwasher/vs/0']
|
||||
assert dishwasher['x.com.samsung.da.sanitize'] == 'On'
|
||||
assert dishwasher['x.com.samsung.da.rinseLevel'] == '4'
|
||||
dishwasher = redacted["/dishwasher/vs/0"]
|
||||
assert dishwasher["x.com.samsung.da.sanitize"] == "On"
|
||||
assert dishwasher["x.com.samsung.da.rinseLevel"] == "4"
|
||||
|
||||
alarms = redacted['/alarms/vs/0']['x.com.samsung.da.items']
|
||||
assert alarms[0]['x.com.samsung.da.code'] == 'SNSF_Reached'
|
||||
alarms = redacted["/alarms/vs/0"]["x.com.samsung.da.items"]
|
||||
assert alarms[0]["x.com.samsung.da.code"] == "SNSF_Reached"
|
||||
|
||||
|
||||
def test_redacts_known_sensitive_fields_in_refrigerator_dump():
|
||||
resources = _load('refrigerator_device.json')
|
||||
resources = _load("refrigerator_device.json")
|
||||
redacted = redact_resources(resources)
|
||||
|
||||
info = redacted['/information/vs/0']
|
||||
assert info['x.com.samsung.da.serialNum'] == REDACTED
|
||||
info = redacted["/information/vs/0"]
|
||||
assert info["x.com.samsung.da.serialNum"] == REDACTED
|
||||
|
||||
wireless = redacted['/wirelessinfo/vs/0']
|
||||
assert wireless['macaddressWiFi'] == REDACTED
|
||||
assert wireless['macaddressBLE'] == REDACTED
|
||||
wireless = redacted["/wirelessinfo/vs/0"]
|
||||
assert wireless["macaddressWiFi"] == REDACTED
|
||||
assert wireless["macaddressBLE"] == REDACTED
|
||||
|
||||
|
||||
def test_redact_resources_does_not_mutate_input():
|
||||
resources = _load('dishwasher_device.json')
|
||||
original_serial = resources['/information/vs/0']['x.com.samsung.da.serialNum']
|
||||
resources = _load("dishwasher_device.json")
|
||||
original_serial = resources["/information/vs/0"]["x.com.samsung.da.serialNum"]
|
||||
|
||||
redact_resources(resources)
|
||||
|
||||
assert resources['/information/vs/0']['x.com.samsung.da.serialNum'] == original_serial
|
||||
assert resources["/information/vs/0"]["x.com.samsung.da.serialNum"] == original_serial
|
||||
|
||||
|
||||
def test_redacts_bare_ocf_identity_keys():
|
||||
"""/oic/d and /oic/p identify the unit with two-letter keys ('di', 'pi')
|
||||
that the substring rules can't see."""
|
||||
redacted = redact_resources({
|
||||
'/oic/d': {'di': 'ab-cd-ef', 'n': "Marc's Fridge",
|
||||
'rt': ['oic.wk.d', 'oic.d.refrigerator']},
|
||||
'/oic/p': {'pi': '12-34-56', 'mnmo': 'RF9000B'},
|
||||
})
|
||||
redacted = redact_resources(
|
||||
{
|
||||
"/oic/d": {
|
||||
"di": "ab-cd-ef",
|
||||
"n": "Marc's Fridge",
|
||||
"rt": ["oic.wk.d", "oic.d.refrigerator"],
|
||||
},
|
||||
"/oic/p": {"pi": "12-34-56", "mnmo": "RF9000B"},
|
||||
}
|
||||
)
|
||||
|
||||
assert redacted['/oic/d']['di'] == REDACTED
|
||||
assert redacted['/oic/p']['pi'] == REDACTED
|
||||
assert redacted["/oic/d"]["di"] == REDACTED
|
||||
assert redacted["/oic/p"]["pi"] == REDACTED
|
||||
# 'n' is free text the owner sets from the SmartThings app, so it can
|
||||
# carry a person's name -- redacted too. `rt`, the device-type signal
|
||||
# we actually want out of /oic/d, is not.
|
||||
assert redacted['/oic/d']['n'] == REDACTED
|
||||
assert redacted['/oic/d']['rt'] == ['oic.wk.d', 'oic.d.refrigerator']
|
||||
assert redacted['/oic/p']['mnmo'] == 'RF9000B'
|
||||
assert redacted["/oic/d"]["n"] == REDACTED
|
||||
assert redacted["/oic/d"]["rt"] == ["oic.wk.d", "oic.d.refrigerator"]
|
||||
assert redacted["/oic/p"]["mnmo"] == "RF9000B"
|
||||
|
||||
|
||||
def test_bare_key_redaction_does_not_leak_into_substring_matching():
|
||||
"""The bare keys are whole-key matches only -- plenty of ordinary
|
||||
appliance fields contain those letters and must survive untouched."""
|
||||
redacted = redact_resources({
|
||||
'/x': {
|
||||
'condition': 'Normal', 'display': 'On', 'dispenser': 'Cubed',
|
||||
'humidity': '45', 'spinSpeed': '1200', 'name': 'FilterProgress',
|
||||
},
|
||||
})
|
||||
redacted = redact_resources(
|
||||
{
|
||||
"/x": {
|
||||
"condition": "Normal",
|
||||
"display": "On",
|
||||
"dispenser": "Cubed",
|
||||
"humidity": "45",
|
||||
"spinSpeed": "1200",
|
||||
"name": "FilterProgress",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert redacted['/x'] == {
|
||||
'condition': 'Normal', 'display': 'On', 'dispenser': 'Cubed',
|
||||
'humidity': '45', 'spinSpeed': '1200', 'name': 'FilterProgress',
|
||||
assert redacted["/x"] == {
|
||||
"condition": "Normal",
|
||||
"display": "On",
|
||||
"dispenser": "Cubed",
|
||||
"humidity": "45",
|
||||
"spinSpeed": "1200",
|
||||
"name": "FilterProgress",
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Tests for the CAPABILITIES registry."""
|
||||
|
||||
from custom_components.localthings.registry.registry import CAPABILITIES
|
||||
|
||||
|
||||
@@ -16,4 +17,4 @@ def test_registry_has_no_duplicate_href():
|
||||
|
||||
def test_operational_state_present():
|
||||
"""At least one capability should have 'state' in its href."""
|
||||
assert any('state' in href for href in CAPABILITIES)
|
||||
assert any("state" in href for href in CAPABILITIES)
|
||||
@@ -6,6 +6,7 @@ unbound. This guards two things at once: that the ignored hrefs are
|
||||
actually suppressed, and (via a plain import) that no ignored href
|
||||
collides with a real capability declared elsewhere for the same family.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
@@ -13,33 +14,33 @@ from custom_components.localthings.registry.batch import parse_device0_batch
|
||||
from custom_components.localthings.registry.by_type import dishwasher, refrigerator
|
||||
from custom_components.localthings.registry.capabilities.ignored import IGNORED
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
|
||||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||
|
||||
_IGNORED_HREFS = {cap.href for cap in IGNORED}
|
||||
|
||||
|
||||
def _load(name: str) -> dict:
|
||||
data = json.loads((FIXTURES / name).read_text())
|
||||
return parse_device0_batch(data['device0'])
|
||||
return parse_device0_batch(data["device0"])
|
||||
|
||||
|
||||
def _unbound_hrefs(resources, registry) -> list[str]:
|
||||
unbound = []
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
discover(resources, registry.capabilities, registry.pattern_capabilities,
|
||||
log=unbound.append)
|
||||
|
||||
discover(resources, registry.capabilities, registry.pattern_capabilities, log=unbound.append)
|
||||
return unbound
|
||||
|
||||
|
||||
def test_ignored_hrefs_absent_from_dishwasher_gaps():
|
||||
resources = _load('dishwasher_device.json')
|
||||
resources = _load("dishwasher_device.json")
|
||||
unbound = _unbound_hrefs(resources, dishwasher.REGISTRY)
|
||||
present_ignored = _IGNORED_HREFS & set(unbound)
|
||||
assert not present_ignored, f"ignored hrefs leaked into gap report: {present_ignored}"
|
||||
|
||||
|
||||
def test_ignored_hrefs_absent_from_refrigerator_gaps():
|
||||
resources = _load('refrigerator_device.json')
|
||||
resources = _load("refrigerator_device.json")
|
||||
unbound = _unbound_hrefs(resources, refrigerator.REGISTRY)
|
||||
present_ignored = _IGNORED_HREFS & set(unbound)
|
||||
assert not present_ignored, f"ignored hrefs leaked into gap report: {present_ignored}"
|
||||
@@ -54,7 +55,7 @@ def test_dishwasher_fixture_has_no_remaining_gaps():
|
||||
look at (add the href to ignored.py or map it, don't just delete this
|
||||
assertion).
|
||||
"""
|
||||
resources = _load('dishwasher_device.json')
|
||||
resources = _load("dishwasher_device.json")
|
||||
unbound = set(_unbound_hrefs(resources, dishwasher.REGISTRY))
|
||||
assert unbound == set()
|
||||
|
||||
@@ -62,14 +63,15 @@ def test_dishwasher_fixture_has_no_remaining_gaps():
|
||||
class TestWasherIgnoredHrefs:
|
||||
def test_washer_hrefs_are_ignored(self):
|
||||
from custom_components.localthings.registry.capabilities.ignored import IGNORED
|
||||
|
||||
ignored_hrefs = {cap.href for cap in IGNORED}
|
||||
for href in (
|
||||
'/st/washercourse/vs/0',
|
||||
'/wm/welcomemsg/vs/0',
|
||||
'/wm/personalcourse/vs/0',
|
||||
'/energy/consumption/0',
|
||||
'/cycleinterface/vs/0',
|
||||
'/drlc/0',
|
||||
'/operational/state/0',
|
||||
"/st/washercourse/vs/0",
|
||||
"/wm/welcomemsg/vs/0",
|
||||
"/wm/personalcourse/vs/0",
|
||||
"/energy/consumption/0",
|
||||
"/cycleinterface/vs/0",
|
||||
"/drlc/0",
|
||||
"/operational/state/0",
|
||||
):
|
||||
assert href in ignored_hrefs, f"{href} should be in ignored.IGNORED"
|
||||
@@ -1,46 +1,47 @@
|
||||
"""Tests for select-option display casing (custom_components/localthings/select.py)."""
|
||||
|
||||
from custom_components.localthings.select import _display
|
||||
|
||||
_UNTRANSLATED = None
|
||||
_TRANSLATED = 'ice_type'
|
||||
_TRANSLATED = "ice_type"
|
||||
|
||||
|
||||
def test_display_titlecases_a_fully_lowercase_device_native_token():
|
||||
"""Samsung's sound-mode field is genuinely lowercase on the wire
|
||||
('voice'/'tone'/'mute') -- these have no other casing signal to key
|
||||
off, so title-case them for display."""
|
||||
assert _display('voice', _UNTRANSLATED) == 'Voice'
|
||||
assert _display('mute', _UNTRANSLATED) == 'Mute'
|
||||
assert _display("voice", _UNTRANSLATED) == "Voice"
|
||||
assert _display("mute", _UNTRANSLATED) == "Mute"
|
||||
|
||||
|
||||
def test_display_inserts_a_space_at_a_camelcase_boundary():
|
||||
"""'ExtraHigh' (from supportedHeatedDry) should read as two words."""
|
||||
assert _display('ExtraHigh', _UNTRANSLATED) == 'Extra High'
|
||||
assert _display("ExtraHigh", _UNTRANSLATED) == "Extra High"
|
||||
|
||||
|
||||
def test_display_passes_through_an_already_human_friendly_value():
|
||||
"""'AI Wash' etc. (dishwasher cycle names) already read fine and
|
||||
have no camelCase boundary or all-lowercase pattern -- must not be
|
||||
mangled."""
|
||||
assert _display('AI Wash', _UNTRANSLATED) == 'AI Wash'
|
||||
assert _display('Low', _UNTRANSLATED) == 'Low'
|
||||
assert _display('Off', _UNTRANSLATED) == 'Off'
|
||||
assert _display("AI Wash", _UNTRANSLATED) == "AI Wash"
|
||||
assert _display("Low", _UNTRANSLATED) == "Low"
|
||||
assert _display("Off", _UNTRANSLATED) == "Off"
|
||||
|
||||
|
||||
def test_display_lowercases_for_translation_key_lookup():
|
||||
"""An entity with a translation_key must match the catalog's
|
||||
lowercase keys exactly -- unlike the untranslated cases above, this
|
||||
is not a cosmetic transform."""
|
||||
assert _display('Whiskey_IceBall_3', _TRANSLATED) == 'whiskey_iceball_3'
|
||||
assert _display("Whiskey_IceBall_3", _TRANSLATED) == "whiskey_iceball_3"
|
||||
|
||||
|
||||
def test_unknown_translated_vendor_value_keeps_readable_fallback():
|
||||
"""A firmware-added value must remain readable instead of being mangled."""
|
||||
assert _display('FutureVendorMode', _TRANSLATED) == 'Future Vendor Mode'
|
||||
assert _display("FutureVendorMode", _TRANSLATED) == "Future Vendor Mode"
|
||||
|
||||
|
||||
def test_known_camel_case_state_uses_snake_case_translation_key():
|
||||
assert _display('ExtraHigh', 'heated_dry') == 'extra_high'
|
||||
assert _display("ExtraHigh", "heated_dry") == "extra_high"
|
||||
|
||||
|
||||
def test_display_passes_through_non_string_values():
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
(custom_components/localthings/select.py) -- the static tuple, options_field,
|
||||
and callable forms of SelectDesc.options.
|
||||
"""
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from custom_components.localthings.registry.capability import Capability
|
||||
from custom_components.localthings.registry.discovery import BoundEntity
|
||||
from custom_components.localthings.registry.entities import SelectDesc
|
||||
@@ -9,7 +12,7 @@ from custom_components.localthings.select import LocalThingsSelect
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-SERIAL'
|
||||
device_serial = "TEST-SERIAL"
|
||||
|
||||
def __init__(self, last_resources):
|
||||
self.last_resources = last_resources
|
||||
@@ -28,15 +31,15 @@ def _make_select(desc, href, last_resources):
|
||||
|
||||
|
||||
def test_static_options_unaffected():
|
||||
desc = SelectDesc(key='x', options=('A', 'B'))
|
||||
entity = _make_select(desc, '/x/vs/0', {})
|
||||
assert entity.options == ['A', 'B']
|
||||
desc = SelectDesc(key="x", options=("A", "B"))
|
||||
entity = _make_select(desc, "/x/vs/0", {})
|
||||
assert entity.options == ["A", "B"]
|
||||
|
||||
|
||||
def test_options_field_unaffected():
|
||||
desc = SelectDesc(key='x', options_field='supported')
|
||||
entity = _make_select(desc, '/x/vs/0', {'/x/vs/0': {'supported': ['Lo', 'Hi']}})
|
||||
assert entity.options == ['Lo', 'Hi']
|
||||
desc = SelectDesc(key="x", options_field="supported")
|
||||
entity = _make_select(desc, "/x/vs/0", {"/x/vs/0": {"supported": ["Lo", "Hi"]}})
|
||||
assert entity.options == ["Lo", "Hi"]
|
||||
|
||||
|
||||
def test_callable_options_receives_full_resource_snapshot():
|
||||
@@ -47,21 +50,21 @@ def test_callable_options_receives_full_resource_snapshot():
|
||||
|
||||
def _options_fn(resources):
|
||||
calls.append(resources)
|
||||
return list(resources.get('/other/vs/0', {}).get('codes', []))
|
||||
return list(resources.get("/other/vs/0", {}).get("codes", []))
|
||||
|
||||
desc = SelectDesc(key='cycle', translation_key='fake_cycle', options=_options_fn)
|
||||
desc = SelectDesc(key="cycle", translation_key="fake_cycle", options=_options_fn)
|
||||
resources = {
|
||||
'/x/vs/0': {},
|
||||
'/other/vs/0': {'codes': ['1C', '1D']},
|
||||
"/x/vs/0": {},
|
||||
"/other/vs/0": {"codes": ["1C", "1D"]},
|
||||
}
|
||||
entity = _make_select(desc, '/x/vs/0', resources)
|
||||
assert entity.options == ['1C', '1D']
|
||||
entity = _make_select(desc, "/x/vs/0", resources)
|
||||
assert entity.options == ["1C", "1D"]
|
||||
assert calls == [resources]
|
||||
|
||||
|
||||
def test_callable_options_empty_result():
|
||||
desc = SelectDesc(key='cycle', options=lambda resources: [])
|
||||
entity = _make_select(desc, '/x/vs/0', {})
|
||||
desc = SelectDesc(key="cycle", options=lambda resources: [])
|
||||
entity = _make_select(desc, "/x/vs/0", {})
|
||||
assert entity.options == []
|
||||
|
||||
|
||||
@@ -73,19 +76,20 @@ def test_callable_translation_key_reresolves_live_not_once_at_construction():
|
||||
(see entity.py's _is_included docstring), and a one-time resolution
|
||||
would permanently show untranslated codes even after a later poll
|
||||
populates the real value."""
|
||||
desc = SelectDesc(key='cycle', translation_key=lambda resources: resources.get('key'))
|
||||
resources = {'key': None}
|
||||
entity = _make_select(desc, '/x/vs/0', resources)
|
||||
desc = SelectDesc(key="cycle", translation_key=lambda resources: resources.get("key"))
|
||||
resources = {"key": None}
|
||||
entity = _make_select(desc, "/x/vs/0", resources)
|
||||
assert entity.translation_key is None
|
||||
|
||||
resources['key'] = 'washer_cycle_table_02'
|
||||
assert entity.translation_key == 'washer_cycle_table_02'
|
||||
resources["key"] = "washer_cycle_table_02"
|
||||
assert entity.translation_key == "washer_cycle_table_02"
|
||||
|
||||
|
||||
async def test_unknown_vendor_option_round_trips_to_exact_raw_value():
|
||||
"""Readable fallback labels must still write the exact Samsung token."""
|
||||
|
||||
class _WritableCoordinator(_FakeCoordinator):
|
||||
data = {'mode': 'FutureVendorMode'}
|
||||
data: ClassVar[dict] = {"mode": "FutureVendorMode"}
|
||||
|
||||
def __init__(self, last_resources):
|
||||
super().__init__(last_resources)
|
||||
@@ -95,14 +99,16 @@ async def test_unknown_vendor_option_round_trips_to_exact_raw_value():
|
||||
self.writes.append(value)
|
||||
|
||||
desc = SelectDesc(
|
||||
key='mode', translation_key='door_alert',
|
||||
options=('Known', 'FutureVendorMode'), write_fn=lambda *args: None,
|
||||
key="mode",
|
||||
translation_key="door_alert",
|
||||
options=("Known", "FutureVendorMode"),
|
||||
write_fn=lambda *args: None,
|
||||
)
|
||||
capability = Capability(href='/x/vs/0', entities=(desc,))
|
||||
bound = BoundEntity(href='/x/vs/0', capability=capability, desc=desc)
|
||||
capability = Capability(href="/x/vs/0", entities=(desc,))
|
||||
bound = BoundEntity(href="/x/vs/0", capability=capability, desc=desc)
|
||||
coordinator = _WritableCoordinator({})
|
||||
entity = LocalThingsSelect(coordinator, bound)
|
||||
|
||||
assert entity.options[-1] == 'Future Vendor Mode'
|
||||
await entity.async_select_option('Future Vendor Mode')
|
||||
assert coordinator.writes == ['FutureVendorMode']
|
||||
assert entity.options[-1] == "Future Vendor Mode"
|
||||
await entity.async_select_option("Future Vendor Mode")
|
||||
assert coordinator.writes == ["FutureVendorMode"]
|
||||
@@ -1,14 +1,15 @@
|
||||
"""Unit tests for LocalThingsSensor's hysteresis gate (finish_time churn)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from custom_components.localthings.const import CONF_FINISH_TIME_HYSTERESIS_MINUTES
|
||||
from custom_components.localthings.registry.capabilities.operational import OPERATIONAL_STATE
|
||||
from custom_components.localthings.registry.discovery import BoundEntity
|
||||
from custom_components.localthings.sensor import LocalThingsSensor
|
||||
|
||||
_FINISH_TIME_DESC = next(e for e in OPERATIONAL_STATE.entities if e.key == 'finish_time')
|
||||
_FINISH_TIME_DESC = next(e for e in OPERATIONAL_STATE.entities if e.key == "finish_time")
|
||||
|
||||
|
||||
class _FakeConfigEntry:
|
||||
@@ -20,17 +21,21 @@ class _FakeCoordinator:
|
||||
"""Just enough surface for LocalThingsEntity/LocalThingsSensor."""
|
||||
|
||||
def __init__(self, threshold_minutes):
|
||||
self.device_serial = 'TEST-SERIAL'
|
||||
self.config_entry = _FakeConfigEntry({
|
||||
CONF_FINISH_TIME_HYSTERESIS_MINUTES: threshold_minutes,
|
||||
})
|
||||
self.device_serial = "TEST-SERIAL"
|
||||
self.config_entry = _FakeConfigEntry(
|
||||
{
|
||||
CONF_FINISH_TIME_HYSTERESIS_MINUTES: threshold_minutes,
|
||||
}
|
||||
)
|
||||
self.data: dict = {}
|
||||
|
||||
|
||||
def _sensor(threshold_minutes=3):
|
||||
coordinator = _FakeCoordinator(threshold_minutes)
|
||||
bound = BoundEntity(
|
||||
href=OPERATIONAL_STATE.href, capability=OPERATIONAL_STATE, desc=_FINISH_TIME_DESC,
|
||||
href=OPERATIONAL_STATE.href,
|
||||
capability=OPERATIONAL_STATE,
|
||||
desc=_FINISH_TIME_DESC,
|
||||
)
|
||||
sensor = LocalThingsSensor(coordinator, bound)
|
||||
return sensor, coordinator
|
||||
@@ -38,63 +43,63 @@ def _sensor(threshold_minutes=3):
|
||||
|
||||
def test_small_change_is_suppressed():
|
||||
sensor, coordinator = _sensor(threshold_minutes=3)
|
||||
base = datetime(2026, 7, 31, 17, 0, tzinfo=timezone.utc)
|
||||
base = datetime(2026, 7, 31, 17, 0, tzinfo=UTC)
|
||||
|
||||
coordinator.data = {'finish_time': base}
|
||||
coordinator.data = {"finish_time": base}
|
||||
assert sensor.native_value == base
|
||||
|
||||
coordinator.data = {'finish_time': base + timedelta(minutes=1)}
|
||||
coordinator.data = {"finish_time": base + timedelta(minutes=1)}
|
||||
assert sensor.native_value == base, "a 1-minute wobble should be held back"
|
||||
|
||||
|
||||
def test_change_past_threshold_is_reported():
|
||||
sensor, coordinator = _sensor(threshold_minutes=3)
|
||||
base = datetime(2026, 7, 31, 17, 0, tzinfo=timezone.utc)
|
||||
base = datetime(2026, 7, 31, 17, 0, tzinfo=UTC)
|
||||
|
||||
coordinator.data = {'finish_time': base}
|
||||
coordinator.data = {"finish_time": base}
|
||||
assert sensor.native_value == base
|
||||
|
||||
new = base + timedelta(minutes=5)
|
||||
coordinator.data = {'finish_time': new}
|
||||
coordinator.data = {"finish_time": new}
|
||||
assert sensor.native_value == new
|
||||
|
||||
|
||||
def test_zero_threshold_disables_hysteresis():
|
||||
sensor, coordinator = _sensor(threshold_minutes=0)
|
||||
base = datetime(2026, 7, 31, 17, 0, tzinfo=timezone.utc)
|
||||
base = datetime(2026, 7, 31, 17, 0, tzinfo=UTC)
|
||||
|
||||
coordinator.data = {'finish_time': base}
|
||||
coordinator.data = {"finish_time": base}
|
||||
assert sensor.native_value == base
|
||||
|
||||
new = base + timedelta(seconds=1)
|
||||
coordinator.data = {'finish_time': new}
|
||||
coordinator.data = {"finish_time": new}
|
||||
assert sensor.native_value == new
|
||||
|
||||
|
||||
def test_cycle_end_passes_through_immediately():
|
||||
"""A cycle ending (finish_time -> None) must never be held back."""
|
||||
sensor, coordinator = _sensor(threshold_minutes=3)
|
||||
base = datetime(2026, 7, 31, 17, 0, tzinfo=timezone.utc)
|
||||
base = datetime(2026, 7, 31, 17, 0, tzinfo=UTC)
|
||||
|
||||
coordinator.data = {'finish_time': base}
|
||||
coordinator.data = {"finish_time": base}
|
||||
assert sensor.native_value == base
|
||||
|
||||
coordinator.data = {'finish_time': None}
|
||||
coordinator.data = {"finish_time": None}
|
||||
assert sensor.native_value is None
|
||||
|
||||
|
||||
def test_non_hysteresis_sensor_is_unaffected():
|
||||
"""A SensorDesc without hysteresis=True reads straight through, unchanged."""
|
||||
machine_state_desc = next(
|
||||
e for e in OPERATIONAL_STATE.entities if e.key == 'machine_state'
|
||||
)
|
||||
machine_state_desc = next(e for e in OPERATIONAL_STATE.entities if e.key == "machine_state")
|
||||
coordinator = _FakeCoordinator(threshold_minutes=3)
|
||||
bound = BoundEntity(
|
||||
href=OPERATIONAL_STATE.href, capability=OPERATIONAL_STATE, desc=machine_state_desc,
|
||||
href=OPERATIONAL_STATE.href,
|
||||
capability=OPERATIONAL_STATE,
|
||||
desc=machine_state_desc,
|
||||
)
|
||||
sensor = LocalThingsSensor(coordinator, bound)
|
||||
|
||||
coordinator.data = {'machine_state': 'active'}
|
||||
assert sensor.native_value == 'active'
|
||||
coordinator.data = {'machine_state': 'idle'}
|
||||
assert sensor.native_value == 'idle'
|
||||
coordinator.data = {"machine_state": "active"}
|
||||
assert sensor.native_value == "active"
|
||||
coordinator.data = {"machine_state": "idle"}
|
||||
assert sensor.native_value == "idle"
|
||||
+164
-116
@@ -5,39 +5,47 @@ what actually exercises _enumerate_subdevices_blocking + _run_discovery
|
||||
together, including device_info_for/via_device and the "no phantom
|
||||
/device/2 entities" guarantee.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from homeassistant.core import HomeAssistant
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.localthings.const import (
|
||||
CONF_HOST, CONF_LEAF_CERT_PEM, CONF_LEAF_KEY_PEM, CONF_PORT, DOMAIN,
|
||||
CONF_HOST,
|
||||
CONF_LEAF_CERT_PEM,
|
||||
CONF_LEAF_KEY_PEM,
|
||||
CONF_PORT,
|
||||
DOMAIN,
|
||||
)
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
from custom_components.localthings.registry.entities import ClimateDesc
|
||||
from custom_components.localthings.registry.identity import DeviceIdentity
|
||||
|
||||
from tests.conftest import FakeCoapSession, _load_device_full
|
||||
|
||||
ENTRY_DATA = {
|
||||
CONF_HOST: '10.0.0.177',
|
||||
CONF_HOST: "10.0.0.177",
|
||||
CONF_PORT: 49154,
|
||||
CONF_LEAF_CERT_PEM: '-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----',
|
||||
CONF_LEAF_KEY_PEM: '-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----',
|
||||
CONF_LEAF_CERT_PEM: "-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----",
|
||||
CONF_LEAF_KEY_PEM: "-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----",
|
||||
}
|
||||
|
||||
|
||||
def _coordinator(hass: HomeAssistant) -> LocalThingsCoordinator:
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data=ENTRY_DATA, unique_id='localthings_SUBDEVICE-TEST',
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_DATA,
|
||||
unique_id="localthings_SUBDEVICE-TEST",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
return LocalThingsCoordinator(hass, entry)
|
||||
|
||||
|
||||
async def _discover_with(
|
||||
coordinator: LocalThingsCoordinator, resources: dict, oic_res, seeds: dict,
|
||||
coordinator: LocalThingsCoordinator,
|
||||
resources: dict,
|
||||
oic_res,
|
||||
seeds: dict,
|
||||
) -> None:
|
||||
"""Run the same two-step sequence _async_update_data's first cycle does
|
||||
(enumerate, then discover) against arbitrary resources/oic_res/seeds,
|
||||
@@ -50,11 +58,16 @@ async def _discover_with(
|
||||
# the fixture's real /oic/res so enumeration sees the same links a live
|
||||
# read_identity call would have captured.
|
||||
coordinator._identity = DeviceIdentity(
|
||||
manufacturer='Samsung Electronics', model='', name='', serial=None,
|
||||
device_types=(), raw={'/oic/p': {}, '/oic/d': {}, '/oic/res': oic_res},
|
||||
manufacturer="Samsung Electronics",
|
||||
model="",
|
||||
name="",
|
||||
serial=None,
|
||||
device_types=(),
|
||||
raw={"/oic/p": {}, "/oic/d": {}, "/oic/res": oic_res},
|
||||
)
|
||||
merged = await coordinator.hass.async_add_executor_job(
|
||||
coordinator._enumerate_subdevices_blocking, resources,
|
||||
coordinator._enumerate_subdevices_blocking,
|
||||
resources,
|
||||
)
|
||||
# Mirror _async_update_data's first-cycle order exactly: discover, then
|
||||
# drop the candidates the liveness gate rejected, then apply what's left
|
||||
@@ -66,7 +79,7 @@ async def _discover_with(
|
||||
# longer uses.
|
||||
coordinator._run_discovery(merged)
|
||||
for href, rep in coordinator._live_subdevice_resources(merged).items():
|
||||
coordinator._observe.apply(href, rep, source='poll')
|
||||
coordinator._observe.apply(href, rep, source="poll")
|
||||
|
||||
|
||||
async def _discover(coordinator: LocalThingsCoordinator, name: str) -> None:
|
||||
@@ -77,6 +90,7 @@ async def _discover(coordinator: LocalThingsCoordinator, name: str) -> None:
|
||||
|
||||
def _climate_bound(coordinator, subdevice_key: str):
|
||||
from custom_components.localthings.registry.subdevices import MAIN
|
||||
|
||||
for b in coordinator.bound:
|
||||
if isinstance(b.desc, ClimateDesc):
|
||||
if subdevice_key is None and b.subdevice == MAIN:
|
||||
@@ -90,18 +104,19 @@ def _climate_bound(coordinator, subdevice_key: str):
|
||||
# Pattern A reporter -- ARTIK051_DONGLE_FAC_18K, indexed siblings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_pattern_a_materializes_master_and_bedroom_subdevice(hass: HomeAssistant):
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_dongle_fac_18k')
|
||||
await _discover(coordinator, "airconditioner_artik051_dongle_fac_18k")
|
||||
|
||||
assert [su.key for su in coordinator.subdevices] == ['1']
|
||||
assert [su.key for su in coordinator.subdevices] == ["1"]
|
||||
|
||||
main_climate = _climate_bound(coordinator, None)
|
||||
sub1_climate = _climate_bound(coordinator, '1')
|
||||
sub1_climate = _climate_bound(coordinator, "1")
|
||||
assert main_climate is not None
|
||||
assert sub1_climate is not None
|
||||
assert main_climate.href == '/mode/vs/0'
|
||||
assert sub1_climate.href == '/mode/vs/1'
|
||||
assert main_climate.href == "/mode/vs/0"
|
||||
assert sub1_climate.href == "/mode/vs/1"
|
||||
|
||||
|
||||
async def test_pattern_a_device_2_produces_no_entities_at_all(hass: HomeAssistant):
|
||||
@@ -110,31 +125,31 @@ async def test_pattern_a_device_2_produces_no_entities_at_all(hass: HomeAssistan
|
||||
batch, but every climate-state rep on it is empty. It must be recorded
|
||||
as skipped, not materialized, and must contribute zero bound entities."""
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_dongle_fac_18k')
|
||||
await _discover(coordinator, "airconditioner_artik051_dongle_fac_18k")
|
||||
|
||||
assert '2' not in [su.key for su in coordinator.subdevices]
|
||||
assert "2" not in [su.key for su in coordinator.subdevices]
|
||||
assert any(
|
||||
skip.subdevice.kind == 'indexed' and skip.subdevice.key == '2'
|
||||
skip.subdevice.kind == "indexed" and skip.subdevice.key == "2"
|
||||
for skip in coordinator._skipped_subdevices
|
||||
)
|
||||
assert not any(b.subdevice.key == '2' for b in coordinator.bound)
|
||||
assert not any(href.endswith('/2') for href in coordinator._hot_hrefs)
|
||||
assert not any(href.endswith('/2') for href in coordinator._warm_hrefs)
|
||||
assert not any(b.subdevice.key == "2" for b in coordinator.bound)
|
||||
assert not any(href.endswith("/2") for href in coordinator._hot_hrefs)
|
||||
assert not any(href.endswith("/2") for href in coordinator._warm_hrefs)
|
||||
|
||||
|
||||
async def test_pattern_a_sub1_device_info_links_via_device_to_master(hass: HomeAssistant):
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_dongle_fac_18k')
|
||||
await _discover(coordinator, "airconditioner_artik051_dongle_fac_18k")
|
||||
|
||||
sub1 = next(su for su in coordinator.subdevices if su.key == '1')
|
||||
sub1 = next(su for su in coordinator.subdevices if su.key == "1")
|
||||
info = coordinator.device_info_for(sub1)
|
||||
|
||||
master_serial = coordinator.device_serial
|
||||
assert info['identifiers'] == {(DOMAIN, f'{master_serial}_1')}
|
||||
assert info['via_device'] == (DOMAIN, master_serial)
|
||||
assert info["identifiers"] == {(DOMAIN, f"{master_serial}_1")}
|
||||
assert info["via_device"] == (DOMAIN, master_serial)
|
||||
# The subdevice's own /information/vs/1 (real, ARTIK051_DONGLE_FAC_RAC_18K)
|
||||
# is what names/models this device, not the master's.
|
||||
assert info['model'] == 'ARTIK051_DONGLE_FAC_RAC_18K'
|
||||
assert info["model"] == "ARTIK051_DONGLE_FAC_RAC_18K"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -142,6 +157,7 @@ async def test_pattern_a_sub1_device_info_links_via_device_to_master(hass: HomeA
|
||||
# answers with an unused slot that reports the appliance's energy counter.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_krac_18k_energy_only_slot_is_not_materialized(hass: HomeAssistant):
|
||||
"""The issue #214 reporter's single-split AR12NXWXCWKNEU (ARTIK051_KRAC_18K,
|
||||
one indoor unit) answers /device/1 with the Pattern A /device/2 shape --
|
||||
@@ -154,27 +170,31 @@ async def test_krac_18k_energy_only_slot_is_not_materialized(hass: HomeAssistant
|
||||
slot, so the candidate must now be recorded as skipped and contribute
|
||||
nothing: no bound entities, no HA device, no hot/warm hrefs."""
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_krac_18k_slot')
|
||||
await _discover(coordinator, "airconditioner_artik051_krac_18k_slot")
|
||||
|
||||
assert coordinator.subdevices == []
|
||||
assert [s.subdevice.key for s in coordinator._skipped_subdevices] == ['1']
|
||||
assert [s.subdevice.key for s in coordinator._skipped_subdevices] == ["1"]
|
||||
# The gate ran against real bindings, not against nothing -- these are the
|
||||
# six hrefs the reporter's own diagnostics reported for the (then
|
||||
# materialized) subdevice, /energy/consumption/vs/1 among them.
|
||||
assert coordinator._skipped_subdevices[0].hrefs == (
|
||||
'/alarms/vs/1', '/diagnosis/vs/1', '/energy/consumption/vs/1',
|
||||
'/humidity/vs/1', '/mode/vs/1', '/temperature/current/1',
|
||||
"/alarms/vs/1",
|
||||
"/diagnosis/vs/1",
|
||||
"/energy/consumption/vs/1",
|
||||
"/humidity/vs/1",
|
||||
"/mode/vs/1",
|
||||
"/temperature/current/1",
|
||||
)
|
||||
assert coordinator._subdevice_probes['/device/1'] is True
|
||||
assert coordinator._subdevice_probes["/device/1"] is True
|
||||
|
||||
assert not any(b.subdevice.key == '1' for b in coordinator.bound)
|
||||
assert not any(href.endswith('/1') for href in coordinator._hot_hrefs)
|
||||
assert not any(href.endswith('/1') for href in coordinator._warm_hrefs)
|
||||
assert not any(b.subdevice.key == "1" for b in coordinator.bound)
|
||||
assert not any(href.endswith("/1") for href in coordinator._hot_hrefs)
|
||||
assert not any(href.endswith("/1") for href in coordinator._warm_hrefs)
|
||||
|
||||
# The master is untouched -- one climate entity, on the master's own
|
||||
# device, exactly as this board behaved before subdevice support existed.
|
||||
assert _climate_bound(coordinator, None) is not None
|
||||
assert _climate_bound(coordinator, '1') is None
|
||||
assert _climate_bound(coordinator, "1") is None
|
||||
|
||||
|
||||
async def test_krac_18k_slot_state_never_reaches_the_cache(hass: HomeAssistant):
|
||||
@@ -185,49 +205,49 @@ async def test_krac_18k_slot_state_never_reaches_the_cache(hass: HomeAssistant):
|
||||
from it -- at its first-discovery value forever, since nothing polls the
|
||||
slot again."""
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_artik051_krac_18k_slot')
|
||||
await _discover(coordinator, "airconditioner_artik051_krac_18k_slot")
|
||||
|
||||
assert not any(href.endswith('/1') for href in coordinator.last_resources)
|
||||
assert not any(href.endswith("/1") for href in coordinator.last_resources)
|
||||
# It's kept aside for diagnostics only, which is where a reader can still
|
||||
# check the gate's call for themselves.
|
||||
assert '/energy/consumption/vs/1' in coordinator._skipped_subdevice_resources
|
||||
assert "/energy/consumption/vs/1" in coordinator._skipped_subdevice_resources
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Issue #177's Pattern B reporter -- TP2X_FAC_BORA_21K, UUID-prefixed tree
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SUB_UUID = '6c2dff6d-ee5c-dad1-6a5e-000000000001'
|
||||
_SUB_UUID = "6c2dff6d-ee5c-dad1-6a5e-000000000001"
|
||||
|
||||
|
||||
async def test_fac_bora_2in1_materializes_prefixed_wall_subdevice(hass: HomeAssistant):
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_fac_bora_2in1')
|
||||
await _discover(coordinator, "airconditioner_fac_bora_2in1")
|
||||
|
||||
assert [su.key for su in coordinator.subdevices] == [_SUB_UUID]
|
||||
assert coordinator.subdevices[0].kind == 'prefixed'
|
||||
assert coordinator.subdevices[0].kind == "prefixed"
|
||||
|
||||
main_climate = _climate_bound(coordinator, None)
|
||||
sub_climate = _climate_bound(coordinator, _SUB_UUID)
|
||||
assert main_climate is not None
|
||||
assert sub_climate is not None
|
||||
assert main_climate.href == '/mode/vs/0'
|
||||
assert sub_climate.href == f'/{_SUB_UUID}/mode/vs/0'
|
||||
assert main_climate.href == "/mode/vs/0"
|
||||
assert sub_climate.href == f"/{_SUB_UUID}/mode/vs/0"
|
||||
|
||||
|
||||
async def test_fac_bora_2in1_subdevice_device_info(hass: HomeAssistant):
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_fac_bora_2in1')
|
||||
await _discover(coordinator, "airconditioner_fac_bora_2in1")
|
||||
|
||||
subdevice = coordinator.subdevices[0]
|
||||
info = coordinator.device_info_for(subdevice)
|
||||
|
||||
master_serial = coordinator.device_serial
|
||||
assert info['identifiers'] == {(DOMAIN, f'{master_serial}_{_SUB_UUID}')}
|
||||
assert info['via_device'] == (DOMAIN, master_serial)
|
||||
assert info["identifiers"] == {(DOMAIN, f"{master_serial}_{_SUB_UUID}")}
|
||||
assert info["via_device"] == (DOMAIN, master_serial)
|
||||
# Confirmed live by the reporter (DESIGN-177.md section 1): the wall
|
||||
# subdevice's own identity, distinct from the master's TP2X_FAC_BORA_21K.
|
||||
assert info['model'] == 'TP2X_FAC_BORA_RAC_21K'
|
||||
assert info["model"] == "TP2X_FAC_BORA_RAC_21K"
|
||||
|
||||
|
||||
async def test_fac_bora_2in1_unique_ids_include_subdevice_prefix(hass: HomeAssistant):
|
||||
@@ -235,12 +255,13 @@ async def test_fac_bora_2in1_unique_ids_include_subdevice_prefix(hass: HomeAssis
|
||||
(non-alphanumerics stripped), not a truncation or an ordinal -- see
|
||||
Subdevice.key_prefix."""
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_fac_bora_2in1')
|
||||
await _discover(coordinator, "airconditioner_fac_bora_2in1")
|
||||
|
||||
from custom_components.localthings.entity import LocalThingsEntity
|
||||
|
||||
sub_climate = _climate_bound(coordinator, _SUB_UUID)
|
||||
entity = LocalThingsEntity(coordinator, sub_climate)
|
||||
expected_slug = _SUB_UUID.replace('-', '')
|
||||
expected_slug = _SUB_UUID.replace("-", "")
|
||||
assert entity._attr_unique_id == (
|
||||
f"{DOMAIN}_{coordinator.device_serial}_subdevice_{expected_slug}_climate"
|
||||
)
|
||||
@@ -253,6 +274,7 @@ async def test_fac_bora_2in1_unique_ids_include_subdevice_prefix(hass: HomeAssis
|
||||
# capture instead of the synthetic sessions test_subdevices.py uses.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_fac_bora_205_flat_fallback_finds_candidate_but_gate_holds_it_back(
|
||||
hass: HomeAssistant,
|
||||
):
|
||||
@@ -266,17 +288,17 @@ async def test_fac_bora_205_flat_fallback_finds_candidate_but_gate_holds_it_back
|
||||
materializing a phantom climate card from unconfirmed hrefs. This is the
|
||||
honest current state of issue #205, not a guess at its resolution."""
|
||||
coordinator = _coordinator(hass)
|
||||
await _discover(coordinator, 'airconditioner_fac_bora_205_flat')
|
||||
await _discover(coordinator, "airconditioner_fac_bora_205_flat")
|
||||
|
||||
assert coordinator.subdevices == []
|
||||
assert [s.subdevice.key for s in coordinator._skipped_subdevices] == [_SUB_UUID]
|
||||
skipped = coordinator._skipped_subdevices[0].subdevice
|
||||
assert skipped.kind == 'prefixed'
|
||||
assert skipped.kind == "prefixed"
|
||||
assert skipped.seed_path == ()
|
||||
assert skipped.flat_hrefs == ('/information/vs/0',)
|
||||
assert skipped.flat_hrefs == ("/information/vs/0",)
|
||||
|
||||
assert coordinator._subdevice_probes[f'/{_SUB_UUID}/device/0'] is False
|
||||
assert coordinator._subdevice_probes[f'/{_SUB_UUID}/information/vs/0'] is True
|
||||
assert coordinator._subdevice_probes[f"/{_SUB_UUID}/device/0"] is False
|
||||
assert coordinator._subdevice_probes[f"/{_SUB_UUID}/information/vs/0"] is True
|
||||
|
||||
# Confirms the master itself is completely unaffected by its sibling's
|
||||
# Collection endpoint not answering -- same guarantee every other
|
||||
@@ -301,7 +323,7 @@ async def test_flat_subdevice_materializes_and_repolls_end_to_end(hass: HomeAssi
|
||||
add GETs, not freshness, so they're the ones this method must skip.
|
||||
/option/autoclean/vs/0 is cold-tier and is what actually needs this
|
||||
path."""
|
||||
resources, oic_res, _real_seeds = _load_device_full('airconditioner_fac_bora_2in1')
|
||||
resources, oic_res, _real_seeds = _load_device_full("airconditioner_fac_bora_2in1")
|
||||
seeds = {
|
||||
# No (_SUB_UUID, 'device', '0') entry -- forces the flat fallback,
|
||||
# same as the real issue #205 capture above, but this time with
|
||||
@@ -310,23 +332,27 @@ async def test_flat_subdevice_materializes_and_repolls_end_to_end(hass: HomeAssi
|
||||
# Collection-batch seed, just served individually instead of
|
||||
# batched, to isolate "does flat mode produce the same result as
|
||||
# Collection mode" as the only variable.
|
||||
f'/{_SUB_UUID}/power/vs/0': {'x.com.samsung.da.power': 'On'},
|
||||
f'/{_SUB_UUID}/mode/vs/0': {
|
||||
'x.com.samsung.da.supportedModes': ['Cool', 'Dry', 'Wind', 'Auto'],
|
||||
'x.com.samsung.da.modes': ['Cool'],
|
||||
'x.com.samsung.da.options': [],
|
||||
f"/{_SUB_UUID}/power/vs/0": {"x.com.samsung.da.power": "On"},
|
||||
f"/{_SUB_UUID}/mode/vs/0": {
|
||||
"x.com.samsung.da.supportedModes": ["Cool", "Dry", "Wind", "Auto"],
|
||||
"x.com.samsung.da.modes": ["Cool"],
|
||||
"x.com.samsung.da.options": [],
|
||||
},
|
||||
f'/{_SUB_UUID}/temperature/current/0': {
|
||||
'range': [18.0, 30.0], 'units': 'C', 'temperature': 26.0,
|
||||
f"/{_SUB_UUID}/temperature/current/0": {
|
||||
"range": [18.0, 30.0],
|
||||
"units": "C",
|
||||
"temperature": 26.0,
|
||||
},
|
||||
f'/{_SUB_UUID}/temperature/desired/0': {
|
||||
'range': [18.0, 30.0], 'units': 'C', 'temperature': 24.0,
|
||||
f"/{_SUB_UUID}/temperature/desired/0": {
|
||||
"range": [18.0, 30.0],
|
||||
"units": "C",
|
||||
"temperature": 24.0,
|
||||
},
|
||||
# Cold-tier -- not covered by _run_subpolls, so this is the href
|
||||
# that actually depends on _poll_subdevice_flat_hrefs to ever
|
||||
# refresh at all.
|
||||
f'/{_SUB_UUID}/option/autoclean/vs/0': {
|
||||
'x.com.samsung.da.settingStatus': 'Off',
|
||||
f"/{_SUB_UUID}/option/autoclean/vs/0": {
|
||||
"x.com.samsung.da.settingStatus": "Off",
|
||||
},
|
||||
}
|
||||
coordinator = _coordinator(hass)
|
||||
@@ -343,29 +369,31 @@ async def test_flat_subdevice_materializes_and_repolls_end_to_end(hass: HomeAssi
|
||||
# Re-poll: a fresh reading under the prefix should reach
|
||||
# canonical_resources through _poll_subdevice_seed's flat-mode branch,
|
||||
# not just sit frozen at the one-time enumeration snapshot.
|
||||
coordinator._session.seeds[f'/{_SUB_UUID}/temperature/current/0'] = {
|
||||
'range': [18.0, 30.0], 'units': 'C', 'temperature': 27.5,
|
||||
coordinator._session.seeds[f"/{_SUB_UUID}/temperature/current/0"] = {
|
||||
"range": [18.0, 30.0],
|
||||
"units": "C",
|
||||
"temperature": 27.5,
|
||||
}
|
||||
coordinator._session.seeds[f'/{_SUB_UUID}/option/autoclean/vs/0'] = {
|
||||
'x.com.samsung.da.settingStatus': 'On',
|
||||
coordinator._session.seeds[f"/{_SUB_UUID}/option/autoclean/vs/0"] = {
|
||||
"x.com.samsung.da.settingStatus": "On",
|
||||
}
|
||||
refreshed = coordinator._poll_subdevice_seed(subdevice)
|
||||
|
||||
# The warm-tier temperature href is skipped here -- already covered by
|
||||
# _run_subpolls at a faster cadence -- so it does NOT show up refreshed
|
||||
# through this path.
|
||||
assert f'/{_SUB_UUID}/temperature/current/0' not in refreshed
|
||||
assert f"/{_SUB_UUID}/temperature/current/0" not in refreshed
|
||||
assert refreshed == {
|
||||
f'/{_SUB_UUID}/option/autoclean/vs/0': {'x.com.samsung.da.settingStatus': 'On'},
|
||||
f"/{_SUB_UUID}/option/autoclean/vs/0": {"x.com.samsung.da.settingStatus": "On"},
|
||||
}
|
||||
|
||||
for href, rep in refreshed.items():
|
||||
coordinator._observe.apply(href, rep, source='poll')
|
||||
coordinator._observe.apply(href, rep, source="poll")
|
||||
res = coordinator.canonical_resources(subdevice)
|
||||
assert res['/option/autoclean/vs/0']['x.com.samsung.da.settingStatus'] == 'On'
|
||||
assert res["/option/autoclean/vs/0"]["x.com.samsung.da.settingStatus"] == "On"
|
||||
# Confirms the skip is about redundant re-fetching, not stale data --
|
||||
# the warm-tier value from initial discovery is still there, untouched.
|
||||
assert res['/temperature/current/0']['temperature'] == 26.0
|
||||
assert res["/temperature/current/0"]["temperature"] == 26.0
|
||||
|
||||
|
||||
class _FakeCollectionSession:
|
||||
@@ -382,8 +410,9 @@ class _FakeCollectionSession:
|
||||
self.calls.append(tuple(path))
|
||||
body = self.table.get(tuple(path))
|
||||
if body is None:
|
||||
return 0x84, b''
|
||||
return 0x84, b""
|
||||
import cbor2
|
||||
|
||||
return 0x45, cbor2.dumps(body)
|
||||
|
||||
def pace(self):
|
||||
@@ -399,19 +428,22 @@ def test_poll_subdevice_seed_collection_mode_unaffected_by_flat_fallback(
|
||||
from custom_components.localthings.registry.subdevices import Subdevice
|
||||
|
||||
coordinator = _coordinator(hass)
|
||||
devcol_rep = {'rt': ['x.com.samsung.devcol', 'oic.wk.col']}
|
||||
sess = _FakeCollectionSession({
|
||||
(_SUB_UUID, 'device', '0'): [
|
||||
devcol_rep, {'href': '/mode/vs/0', 'rep': {'mode': 'cool'}},
|
||||
],
|
||||
})
|
||||
devcol_rep = {"rt": ["x.com.samsung.devcol", "oic.wk.col"]}
|
||||
sess = _FakeCollectionSession(
|
||||
{
|
||||
(_SUB_UUID, "device", "0"): [
|
||||
devcol_rep,
|
||||
{"href": "/mode/vs/0", "rep": {"mode": "cool"}},
|
||||
],
|
||||
}
|
||||
)
|
||||
coordinator._session = sess
|
||||
subdevice = Subdevice(kind='prefixed', key=_SUB_UUID, seed_path=(_SUB_UUID, 'device', '0'))
|
||||
subdevice = Subdevice(kind="prefixed", key=_SUB_UUID, seed_path=(_SUB_UUID, "device", "0"))
|
||||
|
||||
result = coordinator._poll_subdevice_seed(subdevice)
|
||||
|
||||
assert result == {f'/{_SUB_UUID}/mode/vs/0': {'mode': 'cool'}}
|
||||
assert sess.calls == [(_SUB_UUID, 'device', '0')]
|
||||
assert result == {f"/{_SUB_UUID}/mode/vs/0": {"mode": "cool"}}
|
||||
assert sess.calls == [(_SUB_UUID, "device", "0")]
|
||||
|
||||
|
||||
def test_poll_subdevice_seed_flat_mode_polls_each_href_individually(
|
||||
@@ -425,21 +457,26 @@ def test_poll_subdevice_seed_flat_mode_polls_each_href_individually(
|
||||
from custom_components.localthings.registry.subdevices import Subdevice
|
||||
|
||||
coordinator = _coordinator(hass)
|
||||
sess = _FakeCollectionSession({
|
||||
(_SUB_UUID, 'mode', 'vs', '0'): {'mode': 'cool'},
|
||||
# (_SUB_UUID, 'power', 'vs', '0') deliberately absent -> drops out.
|
||||
})
|
||||
sess = _FakeCollectionSession(
|
||||
{
|
||||
(_SUB_UUID, "mode", "vs", "0"): {"mode": "cool"},
|
||||
# (_SUB_UUID, 'power', 'vs', '0') deliberately absent -> drops out.
|
||||
}
|
||||
)
|
||||
coordinator._session = sess
|
||||
subdevice = Subdevice(
|
||||
kind='prefixed', key=_SUB_UUID, seed_path=(),
|
||||
flat_hrefs=('/mode/vs/0', '/power/vs/0'),
|
||||
kind="prefixed",
|
||||
key=_SUB_UUID,
|
||||
seed_path=(),
|
||||
flat_hrefs=("/mode/vs/0", "/power/vs/0"),
|
||||
)
|
||||
|
||||
result = coordinator._poll_subdevice_seed(subdevice)
|
||||
|
||||
assert result == {f'/{_SUB_UUID}/mode/vs/0': {'mode': 'cool'}}
|
||||
assert result == {f"/{_SUB_UUID}/mode/vs/0": {"mode": "cool"}}
|
||||
assert sess.calls == [
|
||||
(_SUB_UUID, 'mode', 'vs', '0'), (_SUB_UUID, 'power', 'vs', '0'),
|
||||
(_SUB_UUID, "mode", "vs", "0"),
|
||||
(_SUB_UUID, "power", "vs", "0"),
|
||||
]
|
||||
|
||||
|
||||
@@ -453,21 +490,25 @@ def test_poll_subdevice_seed_flat_mode_skips_hrefs_covered_by_hot_warm_subpolls(
|
||||
from custom_components.localthings.registry.subdevices import Subdevice
|
||||
|
||||
coordinator = _coordinator(hass)
|
||||
sess = _FakeCollectionSession({
|
||||
(_SUB_UUID, 'mode', 'vs', '0'): {'mode': 'cool'},
|
||||
(_SUB_UUID, 'power', 'vs', '0'): {'power': 'On'},
|
||||
})
|
||||
sess = _FakeCollectionSession(
|
||||
{
|
||||
(_SUB_UUID, "mode", "vs", "0"): {"mode": "cool"},
|
||||
(_SUB_UUID, "power", "vs", "0"): {"power": "On"},
|
||||
}
|
||||
)
|
||||
coordinator._session = sess
|
||||
coordinator._warm_hrefs = [f'/{_SUB_UUID}/mode/vs/0']
|
||||
coordinator._warm_hrefs = [f"/{_SUB_UUID}/mode/vs/0"]
|
||||
subdevice = Subdevice(
|
||||
kind='prefixed', key=_SUB_UUID, seed_path=(),
|
||||
flat_hrefs=('/mode/vs/0', '/power/vs/0'),
|
||||
kind="prefixed",
|
||||
key=_SUB_UUID,
|
||||
seed_path=(),
|
||||
flat_hrefs=("/mode/vs/0", "/power/vs/0"),
|
||||
)
|
||||
|
||||
result = coordinator._poll_subdevice_seed(subdevice)
|
||||
|
||||
assert result == {f'/{_SUB_UUID}/power/vs/0': {'power': 'On'}}
|
||||
assert sess.calls == [(_SUB_UUID, 'power', 'vs', '0')]
|
||||
assert result == {f"/{_SUB_UUID}/power/vs/0": {"power": "On"}}
|
||||
assert sess.calls == [(_SUB_UUID, "power", "vs", "0")]
|
||||
|
||||
|
||||
async def test_multidevice_probe_never_reaches_discovery_or_the_cache(
|
||||
@@ -485,24 +526,31 @@ async def test_multidevice_probe_never_reaches_discovery_or_the_cache(
|
||||
Driven with a washer fixture precisely because the AC registry's own
|
||||
ignore entry would mask the coverage half of this on an AC.
|
||||
"""
|
||||
resources, _oic, _seeds = _load_device_full('washer_flexwash')
|
||||
resources, _oic, _seeds = _load_device_full("washer_flexwash")
|
||||
coordinator = _coordinator(hass)
|
||||
coordinator._session = FakeCoapSession({
|
||||
'/multidevice/vs/0': {'x.com.samsung.da.numofsubdevice': '2'},
|
||||
})
|
||||
coordinator._session = FakeCoapSession(
|
||||
{
|
||||
"/multidevice/vs/0": {"x.com.samsung.da.numofsubdevice": "2"},
|
||||
}
|
||||
)
|
||||
coordinator._identity = DeviceIdentity(
|
||||
manufacturer='Samsung Electronics', model='', name='', serial=None,
|
||||
device_types=(), raw={'/oic/p': {}, '/oic/d': {}, '/oic/res': []},
|
||||
manufacturer="Samsung Electronics",
|
||||
model="",
|
||||
name="",
|
||||
serial=None,
|
||||
device_types=(),
|
||||
raw={"/oic/p": {}, "/oic/d": {}, "/oic/res": []},
|
||||
)
|
||||
merged = await hass.async_add_executor_job(
|
||||
coordinator._enumerate_subdevices_blocking, resources,
|
||||
coordinator._enumerate_subdevices_blocking,
|
||||
resources,
|
||||
)
|
||||
coordinator._run_discovery(merged)
|
||||
for href, rep in coordinator._live_subdevice_resources(merged).items():
|
||||
coordinator._observe.apply(href, rep, source='poll')
|
||||
coordinator._observe.apply(href, rep, source="poll")
|
||||
|
||||
assert '/multidevice/vs/0' not in merged
|
||||
assert '/multidevice/vs/0' not in coordinator._unbound_hrefs
|
||||
assert '/multidevice/vs/0' not in coordinator.last_resources
|
||||
assert "/multidevice/vs/0" not in merged
|
||||
assert "/multidevice/vs/0" not in coordinator._unbound_hrefs
|
||||
assert "/multidevice/vs/0" not in coordinator.last_resources
|
||||
# Still captured, just not as device state.
|
||||
assert coordinator._multidevice == {'x.com.samsung.da.numofsubdevice': '2'}
|
||||
assert coordinator._multidevice == {"x.com.samsung.da.numofsubdevice": "2"}
|
||||
+384
-278
File diff suppressed because it is too large.
Load diff
+39
-32
@@ -19,17 +19,12 @@ from string import Formatter
|
||||
from custom_components.localthings.registry.capability import Capability
|
||||
from custom_components.localthings.registry.entities import PLATFORM_OF
|
||||
|
||||
|
||||
INTEGRATION = (
|
||||
Path(__file__).parents[1] / "custom_components" / "localthings"
|
||||
)
|
||||
INTEGRATION = Path(__file__).parents[1] / "custom_components" / "localthings"
|
||||
TRANSLATIONS = INTEGRATION / "translations"
|
||||
|
||||
|
||||
def _load(language: str) -> dict:
|
||||
return json.loads(
|
||||
(TRANSLATIONS / f"{language}.json").read_text(encoding="utf-8")
|
||||
)
|
||||
return json.loads((TRANSLATIONS / f"{language}.json").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _languages() -> list[str]:
|
||||
@@ -46,9 +41,7 @@ def _topology(value):
|
||||
|
||||
def _placeholders(value: str) -> set[str]:
|
||||
return {
|
||||
field_name
|
||||
for _, field_name, _, _ in Formatter().parse(value)
|
||||
if field_name is not None
|
||||
field_name for _, field_name, _, _ in Formatter().parse(value) if field_name is not None
|
||||
}
|
||||
|
||||
|
||||
@@ -105,9 +98,7 @@ def test_every_language_mirrors_the_english_catalog():
|
||||
for path, value in english_strings.items():
|
||||
# Placeholders are substituted by name, so a translation that
|
||||
# drops or invents one renders a literal '{...}' in the UI.
|
||||
assert _placeholders(value) == _placeholders(
|
||||
translated_strings[path]
|
||||
), (language, path)
|
||||
assert _placeholders(value) == _placeholders(translated_strings[path]), (language, path)
|
||||
|
||||
|
||||
def test_no_catalog_carries_unresolved_core_references():
|
||||
@@ -118,9 +109,7 @@ def test_no_catalog_carries_unresolved_core_references():
|
||||
"""
|
||||
for language in _languages():
|
||||
unresolved = [
|
||||
(path, value)
|
||||
for path, value in _walk_strings(_load(language))
|
||||
if "[%key:" in value
|
||||
(path, value) for path, value in _walk_strings(_load(language)) if "[%key:" in value
|
||||
]
|
||||
assert unresolved == [], language
|
||||
|
||||
@@ -138,7 +127,8 @@ def test_no_catalog_carries_unresolved_core_references():
|
||||
# PERFORMANCE/OFF), which Home Assistant translates itself via the
|
||||
# entity_component fallback, so no per-state entry is needed either way.
|
||||
UNNAMED_DESCRIPTORS = {
|
||||
("fan", "fan"), ("fan", "airflow_fan"),
|
||||
("fan", "fan"),
|
||||
("fan", "airflow_fan"),
|
||||
}
|
||||
|
||||
|
||||
@@ -192,22 +182,40 @@ def test_every_ac_convenient_mode_code_has_a_preset_label():
|
||||
en.json.
|
||||
"""
|
||||
from homeassistant.components.climate.const import (
|
||||
PRESET_ACTIVITY, PRESET_AWAY, PRESET_BOOST, PRESET_COMFORT,
|
||||
PRESET_ECO, PRESET_HOME, PRESET_SLEEP,
|
||||
PRESET_ACTIVITY,
|
||||
PRESET_AWAY,
|
||||
PRESET_BOOST,
|
||||
PRESET_COMFORT,
|
||||
PRESET_ECO,
|
||||
PRESET_HOME,
|
||||
PRESET_SLEEP,
|
||||
)
|
||||
standard = {PRESET_ACTIVITY, PRESET_AWAY, PRESET_BOOST, PRESET_COMFORT,
|
||||
PRESET_ECO, PRESET_HOME, PRESET_SLEEP}
|
||||
|
||||
standard = {
|
||||
PRESET_ACTIVITY,
|
||||
PRESET_AWAY,
|
||||
PRESET_BOOST,
|
||||
PRESET_COMFORT,
|
||||
PRESET_ECO,
|
||||
PRESET_HOME,
|
||||
PRESET_SLEEP,
|
||||
}
|
||||
preset_labels = set(
|
||||
_load("en")["entity"]["climate"]["airconditioner"]["state_attributes"]
|
||||
["preset_mode"]["state"]
|
||||
_load("en")["entity"]["climate"]["airconditioner"]["state_attributes"]["preset_mode"][
|
||||
"state"
|
||||
]
|
||||
)
|
||||
fixtures_dir = Path(__file__).parent / "fixtures"
|
||||
missing = []
|
||||
for path in sorted(fixtures_dir.glob("airconditioner*_device.json")):
|
||||
dump = json.loads(path.read_text())
|
||||
conv = next(
|
||||
(item for item in dump.get("device0", [])
|
||||
if item.get("href") == "/mode/convenient/vs/0"), None,
|
||||
(
|
||||
item
|
||||
for item in dump.get("device0", [])
|
||||
if item.get("href") == "/mode/convenient/vs/0"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not conv:
|
||||
continue
|
||||
@@ -228,9 +236,7 @@ def test_every_kimchi_zone_supportmode_code_has_a_state_label():
|
||||
code across any /status/kimchi/<slot>/vs/0 resource would silently
|
||||
render as its raw device token instead of the translated state.
|
||||
"""
|
||||
state_labels = set(
|
||||
_load("en")["entity"]["select"]["kimchi_zone_mode"]["state"]
|
||||
)
|
||||
state_labels = set(_load("en")["entity"]["select"]["kimchi_zone_mode"]["state"])
|
||||
fixtures_dir = Path(__file__).parent / "fixtures"
|
||||
missing = []
|
||||
for path in sorted(fixtures_dir.glob("*_device.json")):
|
||||
@@ -239,8 +245,9 @@ def test_every_kimchi_zone_supportmode_code_has_a_state_label():
|
||||
href = item.get("href", "")
|
||||
if not (href.startswith("/status/kimchi/") and href.endswith("/vs/0")):
|
||||
continue
|
||||
for code in item["rep"].get("x.com.samsung.da.supportMode", []):
|
||||
if code.lower() not in state_labels:
|
||||
missing.append((path.name, href, code))
|
||||
missing.extend(
|
||||
(path.name, href, code)
|
||||
for code in item["rep"].get("x.com.samsung.da.supportMode", [])
|
||||
if code.lower() not in state_labels
|
||||
)
|
||||
assert missing == []
|
||||
|
||||
@@ -5,6 +5,7 @@ protect this (see DESIGN-177.md section 3/6). Run over the entire fixture
|
||||
set, not just the two new subdevice fixtures, so a future dump -- subdevice-
|
||||
capable or not -- exercises it automatically.
|
||||
"""
|
||||
|
||||
from collections import Counter
|
||||
|
||||
import pytest
|
||||
@@ -12,12 +13,9 @@ import pytest
|
||||
from custom_components.localthings.entity import _is_included
|
||||
from custom_components.localthings.registry.adapter import _key
|
||||
from custom_components.localthings.registry.entities import PLATFORM_OF
|
||||
|
||||
from tests.conftest import FIXTURES, _discover_full, _load_device_full
|
||||
|
||||
_FIXTURE_NAMES = sorted(
|
||||
p.name[:-len('_device.json')] for p in FIXTURES.glob('*_device.json')
|
||||
)
|
||||
_FIXTURE_NAMES = sorted(p.name[: -len("_device.json")] for p in FIXTURES.glob("*_device.json"))
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
@@ -31,10 +29,11 @@ class _FakeCoordinator:
|
||||
|
||||
def canonical_resources(self, subdevice):
|
||||
from custom_components.localthings.registry.subdevices import canonical_view
|
||||
|
||||
return canonical_view(subdevice, self.last_resources, self._subdevices)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', _FIXTURE_NAMES)
|
||||
@pytest.mark.parametrize("name", _FIXTURE_NAMES)
|
||||
def test_key_is_unique_across_all_bound_entities(name):
|
||||
"""`_key(b)` only has to be unique among entities `_is_included` would
|
||||
actually register -- discover() alone can (deliberately) produce two
|
||||
@@ -53,8 +52,10 @@ def test_key_is_unique_across_all_bound_entities(name):
|
||||
BinarySensorDesc both named 'power_switch' on /power/0).
|
||||
"""
|
||||
resources, oic_res, seeds = _load_device_full(name)
|
||||
bound, materialized, skipped, full_resources, device_type_name = _discover_full(
|
||||
resources, oic_res, seeds,
|
||||
bound, materialized, _skipped, full_resources, _device_type_name = _discover_full(
|
||||
resources,
|
||||
oic_res,
|
||||
seeds,
|
||||
)
|
||||
coordinator = _FakeCoordinator(full_resources, materialized)
|
||||
included = [b for b in bound if _is_included(b, coordinator)]
|
||||
@@ -75,8 +76,7 @@ def test_subdevice_capable_fixtures_actually_exercise_a_subdevice():
|
||||
the two fixtures this design added actually produce a materialized
|
||||
subdevice, so that silent-vacuous-pass failure mode is caught here
|
||||
instead."""
|
||||
for name in ('airconditioner_artik051_dongle_fac_18k',
|
||||
'airconditioner_fac_bora_2in1'):
|
||||
for name in ("airconditioner_artik051_dongle_fac_18k", "airconditioner_fac_bora_2in1"):
|
||||
resources, oic_res, seeds = _load_device_full(name)
|
||||
_, materialized, _, _, _ = _discover_full(resources, oic_res, seeds)
|
||||
assert materialized, f"{name}: expected at least one materialized subdevice"
|
||||
+197
-170
@@ -4,6 +4,9 @@ Shared laundry capabilities (cycle-select machinery, buzzer, job status) are
|
||||
tested in test_laundry_capabilities.py; the OCF power/kids-lock/remote-control
|
||||
fallback pairs and the energy meter in test_common_capabilities.py.
|
||||
"""
|
||||
|
||||
from datetime import UTC
|
||||
|
||||
from custom_components.localthings.registry.capabilities import laundry, washer
|
||||
|
||||
|
||||
@@ -14,30 +17,30 @@ def _rep_by_href(cap, href):
|
||||
|
||||
class TestWasherSettings:
|
||||
def test_href(self):
|
||||
assert washer.WASHER_SETTINGS.href == '/washer/vs/0'
|
||||
assert washer.WASHER_SETTINGS.href == "/washer/vs/0"
|
||||
|
||||
def test_wash_temperature_read(self):
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == 'wash_temperature')
|
||||
assert desc.field == 'x.com.samsung.da.waterTemperature'
|
||||
assert desc.options_field == 'x.com.samsung.da.supportedWaterTemperature'
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == "wash_temperature")
|
||||
assert desc.field == "x.com.samsung.da.waterTemperature"
|
||||
assert desc.options_field == "x.com.samsung.da.supportedWaterTemperature"
|
||||
|
||||
def test_wash_temperature_write(self):
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == 'wash_temperature')
|
||||
path, body = desc.write_fn('60', {})
|
||||
assert path == ['washer', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.waterTemperature': '60'}
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == "wash_temperature")
|
||||
path, body = desc.write_fn("60", {})
|
||||
assert path == ["washer", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.waterTemperature": "60"}
|
||||
|
||||
def test_spin_speed_write(self):
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == 'spin_speed')
|
||||
path, body = desc.write_fn('1400', {})
|
||||
assert path == ['washer', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.spinLevel': '1400'}
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == "spin_speed")
|
||||
path, body = desc.write_fn("1400", {})
|
||||
assert path == ["washer", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.spinLevel": "1400"}
|
||||
|
||||
def test_rinse_cycles_write(self):
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == 'rinse_cycles')
|
||||
path, body = desc.write_fn('3', {})
|
||||
assert path == ['washer', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.rinseCycles': '3'}
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == "rinse_cycles")
|
||||
path, body = desc.write_fn("3", {})
|
||||
assert path == ["washer", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.rinseCycles": "3"}
|
||||
|
||||
|
||||
class TestDryLevel:
|
||||
@@ -45,20 +48,20 @@ class TestDryLevel:
|
||||
/washer/vs/0 itself, self-gated off on plain washers -- issue #22."""
|
||||
|
||||
def test_exists_only_when_supported_dry_level_present(self):
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == 'dry_level')
|
||||
assert desc.exists_fn({'x.com.samsung.da.supportedDryLevel': ['None', '30']}, {}) is True
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == "dry_level")
|
||||
assert desc.exists_fn({"x.com.samsung.da.supportedDryLevel": ["None", "30"]}, {}) is True
|
||||
assert desc.exists_fn({}, {}) is False
|
||||
|
||||
def test_write(self):
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == 'dry_level')
|
||||
path, body = desc.write_fn('Cupboard', {})
|
||||
assert path == ['washer', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.dryLevel': 'Cupboard'}
|
||||
desc = next(e for e in washer.WASHER_SETTINGS.entities if e.key == "dry_level")
|
||||
path, body = desc.write_fn("Cupboard", {})
|
||||
assert path == ["washer", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.dryLevel": "Cupboard"}
|
||||
|
||||
|
||||
class TestWasherCourse:
|
||||
def test_href(self):
|
||||
assert washer.WASHER_COURSE.href == '/course/vs/0'
|
||||
assert washer.WASHER_COURSE.href == "/course/vs/0"
|
||||
|
||||
def test_translation_key(self):
|
||||
"""Table-scoped (issue: course codes aren't guaranteed consistent
|
||||
@@ -66,110 +69,113 @@ class TestWasherCourse:
|
||||
board reports Table_00, not the Table_02 every washer_cycle_table_02
|
||||
name was confirmed against) -- see laundry.cycle_select. Only a
|
||||
verified table gets table-specific state translations."""
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == 'cycle')
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == "cycle")
|
||||
assert callable(desc.translation_key)
|
||||
table_02 = {'/st/washercourse/vs/0': {'x.com.samsung.da.st.courseTable': 'Table_02'}}
|
||||
assert desc.translation_key(table_02) == 'washer_cycle_table_02'
|
||||
table_00 = {'/st/washercourse/vs/0': {'x.com.samsung.da.st.courseTable': 'Table_00'}}
|
||||
assert desc.translation_key(table_00) == 'cycle'
|
||||
assert desc.translation_key({}) == 'cycle'
|
||||
table_02 = {"/st/washercourse/vs/0": {"x.com.samsung.da.st.courseTable": "Table_02"}}
|
||||
assert desc.translation_key(table_02) == "washer_cycle_table_02"
|
||||
table_00 = {"/st/washercourse/vs/0": {"x.com.samsung.da.st.courseTable": "Table_00"}}
|
||||
assert desc.translation_key(table_00) == "cycle"
|
||||
assert desc.translation_key({}) == "cycle"
|
||||
|
||||
def test_reads_raw_course_code_from_options_array(self):
|
||||
"""rep_fn returns the raw device code; display names come from
|
||||
translations/en.json via translation_key, not Python (see select.py's
|
||||
_display())."""
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == 'cycle')
|
||||
rep = {'x.com.samsung.da.options': ['DeviceType_0167', 'Course_1C', 'GMT_04']}
|
||||
assert desc.rep_fn(rep) == '1C'
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == "cycle")
|
||||
rep = {"x.com.samsung.da.options": ["DeviceType_0167", "Course_1C", "GMT_04"]}
|
||||
assert desc.rep_fn(rep) == "1C"
|
||||
|
||||
def test_missing_course_option_returns_none(self):
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == 'cycle')
|
||||
assert desc.rep_fn({'x.com.samsung.da.options': ['GMT_04']}) is None
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == "cycle")
|
||||
assert desc.rep_fn({"x.com.samsung.da.options": ["GMT_04"]}) is None
|
||||
|
||||
def test_cycle_desc_uses_cycle_options_callable(self):
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == 'cycle')
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == "cycle")
|
||||
assert desc.options is laundry.cycle_options
|
||||
|
||||
def test_exists_only_when_edit_course_list_is_live(self):
|
||||
"""No hardcoded course table is kept -- the selector only appears
|
||||
when a device actually populates editCourseList (see
|
||||
_cycle_options's docstring for why MostUsed_ isn't used either)."""
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == 'cycle')
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == "cycle")
|
||||
assert desc.exists_fn({}, {}) is False
|
||||
assert desc.exists_fn({}, {'/wm/editcourse/vs/0': {}}) is False
|
||||
live = {'/wm/editcourse/vs/0': {'x.com.samsung.da.editCourseList': 'EditCourseList_1C'}}
|
||||
assert desc.exists_fn({}, {"/wm/editcourse/vs/0": {}}) is False
|
||||
live = {"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_1C"}}
|
||||
assert desc.exists_fn({}, live) is True
|
||||
|
||||
def test_cycle_write(self):
|
||||
"""Confirmed on real hardware (issue #54): the write only needs to
|
||||
carry the changed token -- the device matches by prefix, evicts the
|
||||
stale token, and merges the result into the array itself."""
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == 'cycle')
|
||||
rep = {'x.com.samsung.da.options': ['DeviceType_0167', 'Course_1C', 'GMT_04']}
|
||||
path, body = desc.write_fn('1D', rep)
|
||||
assert path == ['course', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['Course_1D']}
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == "cycle")
|
||||
rep = {"x.com.samsung.da.options": ["DeviceType_0167", "Course_1C", "GMT_04"]}
|
||||
path, body = desc.write_fn("1D", rep)
|
||||
assert path == ["course", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["Course_1D"]}
|
||||
|
||||
|
||||
class TestDrumClean:
|
||||
def test_cycles_remaining(self):
|
||||
"""DrumCleanProposal_40 - WashingTimes_3 == 37, matching a live
|
||||
app screenshot's 'Potreba cistenia po 37 cykloch'."""
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities
|
||||
if e.key == 'drum_clean_cycles_remaining')
|
||||
rep = {'x.com.samsung.da.options': ['WashingTimes_3', 'DrumCleanProposal_40']}
|
||||
desc = next(
|
||||
e for e in washer.WASHER_COURSE.entities if e.key == "drum_clean_cycles_remaining"
|
||||
)
|
||||
rep = {"x.com.samsung.da.options": ["WashingTimes_3", "DrumCleanProposal_40"]}
|
||||
assert desc.rep_fn(rep) == 37
|
||||
|
||||
def test_cycles_remaining_never_negative(self):
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities
|
||||
if e.key == 'drum_clean_cycles_remaining')
|
||||
rep = {'x.com.samsung.da.options': ['WashingTimes_50', 'DrumCleanProposal_40']}
|
||||
desc = next(
|
||||
e for e in washer.WASHER_COURSE.entities if e.key == "drum_clean_cycles_remaining"
|
||||
)
|
||||
rep = {"x.com.samsung.da.options": ["WashingTimes_50", "DrumCleanProposal_40"]}
|
||||
assert desc.rep_fn(rep) == 0
|
||||
|
||||
def test_cycles_remaining_missing_fields(self):
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities
|
||||
if e.key == 'drum_clean_cycles_remaining')
|
||||
assert desc.rep_fn({'x.com.samsung.da.options': []}) is None
|
||||
desc = next(
|
||||
e for e in washer.WASHER_COURSE.entities if e.key == "drum_clean_cycles_remaining"
|
||||
)
|
||||
assert desc.rep_fn({"x.com.samsung.da.options": []}) is None
|
||||
|
||||
def test_cycles_remaining_exists_only_when_computable(self):
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities
|
||||
if e.key == 'drum_clean_cycles_remaining')
|
||||
assert desc.exists_fn({'x.com.samsung.da.options': []}, {}) is False
|
||||
rep = {'x.com.samsung.da.options': ['WashingTimes_3', 'DrumCleanProposal_40']}
|
||||
desc = next(
|
||||
e for e in washer.WASHER_COURSE.entities if e.key == "drum_clean_cycles_remaining"
|
||||
)
|
||||
assert desc.exists_fn({"x.com.samsung.da.options": []}, {}) is False
|
||||
rep = {"x.com.samsung.da.options": ["WashingTimes_3", "DrumCleanProposal_40"]}
|
||||
assert desc.exists_fn(rep, {}) is True
|
||||
|
||||
def test_last_cleaned(self):
|
||||
"""DrumCleanLog_2026-07-01T20:18:07 -> a UTC-aware datetime,
|
||||
matching the same screenshot's '10 days ago' (as of 2026-07-11)."""
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities
|
||||
if e.key == 'drum_clean_last_cleaned')
|
||||
rep = {'x.com.samsung.da.options': ['DrumCleanLog_2026-07-01T20:18:07']}
|
||||
from datetime import datetime, timezone
|
||||
assert desc.rep_fn(rep) == datetime(2026, 7, 1, 20, 18, 7, tzinfo=timezone.utc)
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == "drum_clean_last_cleaned")
|
||||
rep = {"x.com.samsung.da.options": ["DrumCleanLog_2026-07-01T20:18:07"]}
|
||||
from datetime import datetime
|
||||
|
||||
assert desc.rep_fn(rep) == datetime(2026, 7, 1, 20, 18, 7, tzinfo=UTC)
|
||||
|
||||
def test_last_cleaned_missing(self):
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities
|
||||
if e.key == 'drum_clean_last_cleaned')
|
||||
assert desc.rep_fn({'x.com.samsung.da.options': []}) is None
|
||||
assert desc.exists_fn({'x.com.samsung.da.options': []}, {}) is False
|
||||
desc = next(e for e in washer.WASHER_COURSE.entities if e.key == "drum_clean_last_cleaned")
|
||||
assert desc.rep_fn({"x.com.samsung.da.options": []}) is None
|
||||
assert desc.exists_fn({"x.com.samsung.da.options": []}, {}) is False
|
||||
|
||||
|
||||
# Raw options array from issue #9's diagnostic dump (trimmed to the fields
|
||||
# relevant to detergent/softener dosing).
|
||||
_DOSING_OPTIONS = [
|
||||
'Course_1C',
|
||||
'DetergentAlarm_Off',
|
||||
'SoftenerAlarm_Off',
|
||||
'DetergentLevelCtrl_3',
|
||||
'SoftenerLevelCtrl_3',
|
||||
'SupportedDetergentLevelCtrl_00010203',
|
||||
'SupportedSoftenerLevelCtrl_00010203',
|
||||
'DetergentLevel2Ctrl_2',
|
||||
'SoftenerLevel2Ctrl_2',
|
||||
'SupportedDetergentLevel2Ctrl_010203',
|
||||
'SupportedSoftenerLevel2Ctrl_010203',
|
||||
"Course_1C",
|
||||
"DetergentAlarm_Off",
|
||||
"SoftenerAlarm_Off",
|
||||
"DetergentLevelCtrl_3",
|
||||
"SoftenerLevelCtrl_3",
|
||||
"SupportedDetergentLevelCtrl_00010203",
|
||||
"SupportedSoftenerLevelCtrl_00010203",
|
||||
"DetergentLevel2Ctrl_2",
|
||||
"SoftenerLevel2Ctrl_2",
|
||||
"SupportedDetergentLevel2Ctrl_010203",
|
||||
"SupportedSoftenerLevel2Ctrl_010203",
|
||||
]
|
||||
_DOSING_RESOURCES = {'/course/vs/0': {'x.com.samsung.da.options': _DOSING_OPTIONS}}
|
||||
_DOSING_RESOURCES = {"/course/vs/0": {"x.com.samsung.da.options": _DOSING_OPTIONS}}
|
||||
|
||||
|
||||
class TestDetergentSoftenerDosing:
|
||||
@@ -182,45 +188,71 @@ class TestDetergentSoftenerDosing:
|
||||
translation keys are zero-padded supported codes ('03'); rep_fn
|
||||
normalizes to the supported code so the value is a valid option
|
||||
(issue #9 -- otherwise HA renders the select 'unknown')."""
|
||||
rep = {'x.com.samsung.da.options': _DOSING_OPTIONS}
|
||||
assert self._desc('detergent_quantity').rep_fn(rep) == '03'
|
||||
assert self._desc('detergent_water_hardness').rep_fn(rep) == '02'
|
||||
assert self._desc('softener_quantity').rep_fn(rep) == '03'
|
||||
assert self._desc('softener_concentration').rep_fn(rep) == '02'
|
||||
rep = {"x.com.samsung.da.options": _DOSING_OPTIONS}
|
||||
assert self._desc("detergent_quantity").rep_fn(rep) == "03"
|
||||
assert self._desc("detergent_water_hardness").rep_fn(rep) == "02"
|
||||
assert self._desc("softener_quantity").rep_fn(rep) == "03"
|
||||
assert self._desc("softener_concentration").rep_fn(rep) == "02"
|
||||
|
||||
def test_current_value_is_a_valid_option_for_every_dosing_select(self):
|
||||
"""The core regression: HA shows a select 'unknown' when current_option
|
||||
is not in options. Each dosing select's value must be one of its own
|
||||
options."""
|
||||
rep = {'x.com.samsung.da.options': _DOSING_OPTIONS}
|
||||
for key in ('detergent_quantity', 'detergent_water_hardness',
|
||||
'softener_quantity', 'softener_concentration'):
|
||||
rep = {"x.com.samsung.da.options": _DOSING_OPTIONS}
|
||||
for key in (
|
||||
"detergent_quantity",
|
||||
"detergent_water_hardness",
|
||||
"softener_quantity",
|
||||
"softener_concentration",
|
||||
):
|
||||
desc = self._desc(key)
|
||||
assert desc.rep_fn(rep) in desc.options(_DOSING_RESOURCES), key
|
||||
|
||||
def test_read_passes_through_when_no_supported_match(self):
|
||||
"""A value with no matching supported code is returned as-is rather than
|
||||
dropped, so an unexpected device stays visible instead of blank."""
|
||||
rep = {'x.com.samsung.da.options': ['DetergentLevelCtrl_7',
|
||||
'SupportedDetergentLevelCtrl_00010203']}
|
||||
assert self._desc('detergent_quantity').rep_fn(rep) == '7'
|
||||
rep = {
|
||||
"x.com.samsung.da.options": [
|
||||
"DetergentLevelCtrl_7",
|
||||
"SupportedDetergentLevelCtrl_00010203",
|
||||
]
|
||||
}
|
||||
assert self._desc("detergent_quantity").rep_fn(rep) == "7"
|
||||
|
||||
def test_translation_keys(self):
|
||||
"""Each entity gets its own translated name and state vocabulary."""
|
||||
assert self._desc('detergent_quantity').translation_key == 'detergent_quantity'
|
||||
assert self._desc('softener_quantity').translation_key == 'softener_quantity'
|
||||
assert self._desc('detergent_water_hardness').translation_key == 'detergent_water_hardness'
|
||||
assert self._desc('softener_concentration').translation_key == 'softener_concentration'
|
||||
assert self._desc("detergent_quantity").translation_key == "detergent_quantity"
|
||||
assert self._desc("softener_quantity").translation_key == "softener_quantity"
|
||||
assert self._desc("detergent_water_hardness").translation_key == "detergent_water_hardness"
|
||||
assert self._desc("softener_concentration").translation_key == "softener_concentration"
|
||||
|
||||
def test_quantity_and_hardness_options_decode_supported_list(self):
|
||||
assert self._desc('detergent_quantity').options(_DOSING_RESOURCES) == ['00', '01', '02', '03']
|
||||
assert self._desc('softener_quantity').options(_DOSING_RESOURCES) == ['00', '01', '02', '03']
|
||||
assert self._desc('detergent_water_hardness').options(_DOSING_RESOURCES) == ['01', '02', '03']
|
||||
assert self._desc('softener_concentration').options(_DOSING_RESOURCES) == ['01', '02', '03']
|
||||
assert self._desc("detergent_quantity").options(_DOSING_RESOURCES) == [
|
||||
"00",
|
||||
"01",
|
||||
"02",
|
||||
"03",
|
||||
]
|
||||
assert self._desc("softener_quantity").options(_DOSING_RESOURCES) == [
|
||||
"00",
|
||||
"01",
|
||||
"02",
|
||||
"03",
|
||||
]
|
||||
assert self._desc("detergent_water_hardness").options(_DOSING_RESOURCES) == [
|
||||
"01",
|
||||
"02",
|
||||
"03",
|
||||
]
|
||||
assert self._desc("softener_concentration").options(_DOSING_RESOURCES) == ["01", "02", "03"]
|
||||
|
||||
def test_exists_only_when_supported_list_present(self):
|
||||
for key in ('detergent_quantity', 'detergent_water_hardness',
|
||||
'softener_quantity', 'softener_concentration'):
|
||||
for key in (
|
||||
"detergent_quantity",
|
||||
"detergent_water_hardness",
|
||||
"softener_quantity",
|
||||
"softener_concentration",
|
||||
):
|
||||
desc = self._desc(key)
|
||||
assert desc.exists_fn({}, {}) is False
|
||||
assert desc.exists_fn({}, _DOSING_RESOURCES) is True
|
||||
@@ -233,32 +265,32 @@ class TestDetergentSoftenerDosing:
|
||||
the changed token -- the device matches by prefix, evicts the stale
|
||||
token, and merges the result into the array itself. No need to read
|
||||
the current array back and rewrite it whole."""
|
||||
rep = {'x.com.samsung.da.options': list(_DOSING_OPTIONS)}
|
||||
path, body = self._desc('detergent_quantity').write_fn('01', rep)
|
||||
assert path == ['course', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['DetergentLevelCtrl_1']}
|
||||
rep = {"x.com.samsung.da.options": list(_DOSING_OPTIONS)}
|
||||
path, body = self._desc("detergent_quantity").write_fn("01", rep)
|
||||
assert path == ["course", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["DetergentLevelCtrl_1"]}
|
||||
|
||||
def test_hardness_write(self):
|
||||
rep = {'x.com.samsung.da.options': list(_DOSING_OPTIONS)}
|
||||
path, body = self._desc('softener_concentration').write_fn('03', rep)
|
||||
assert path == ['course', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': ['SoftenerLevel2Ctrl_3']}
|
||||
rep = {"x.com.samsung.da.options": list(_DOSING_OPTIONS)}
|
||||
path, body = self._desc("softener_concentration").write_fn("03", rep)
|
||||
assert path == ["course", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": ["SoftenerLevel2Ctrl_3"]}
|
||||
|
||||
def test_low_reservoir_off_when_alarm_off(self):
|
||||
rep = {'x.com.samsung.da.options': _DOSING_OPTIONS}
|
||||
assert self._desc('detergent_low').rep_fn(rep) is False
|
||||
assert self._desc('softener_low').rep_fn(rep) is False
|
||||
rep = {"x.com.samsung.da.options": _DOSING_OPTIONS}
|
||||
assert self._desc("detergent_low").rep_fn(rep) is False
|
||||
assert self._desc("softener_low").rep_fn(rep) is False
|
||||
|
||||
def test_low_reservoir_on_when_alarm_active(self):
|
||||
opts = ['DetergentAlarm_On', 'SoftenerAlarm_On']
|
||||
rep = {'x.com.samsung.da.options': opts}
|
||||
assert self._desc('detergent_low').rep_fn(rep) is True
|
||||
assert self._desc('softener_low').rep_fn(rep) is True
|
||||
opts = ["DetergentAlarm_On", "SoftenerAlarm_On"]
|
||||
rep = {"x.com.samsung.da.options": opts}
|
||||
assert self._desc("detergent_low").rep_fn(rep) is True
|
||||
assert self._desc("softener_low").rep_fn(rep) is True
|
||||
|
||||
def test_low_reservoir_exists_only_when_alarm_field_present(self):
|
||||
assert self._desc('detergent_low').exists_fn({'x.com.samsung.da.options': []}, {}) is False
|
||||
rep = {'x.com.samsung.da.options': _DOSING_OPTIONS}
|
||||
assert self._desc('detergent_low').exists_fn(rep, {}) is True
|
||||
assert self._desc("detergent_low").exists_fn({"x.com.samsung.da.options": []}, {}) is False
|
||||
rep = {"x.com.samsung.da.options": _DOSING_OPTIONS}
|
||||
assert self._desc("detergent_low").exists_fn(rep, {}) is True
|
||||
|
||||
|
||||
class TestWashOptionToggles:
|
||||
@@ -272,32 +304,34 @@ class TestWashOptionToggles:
|
||||
|
||||
@staticmethod
|
||||
def _keys():
|
||||
return ('bubble_soak', 'pre_wash', 'intensive')
|
||||
return ("bubble_soak", "pre_wash", "intensive")
|
||||
|
||||
@staticmethod
|
||||
def _prefix(key):
|
||||
return {'bubble_soak': 'BubbleSoak',
|
||||
'pre_wash': 'PreWashSetting',
|
||||
'intensive': 'IntensiveSetting'}[key]
|
||||
return {
|
||||
"bubble_soak": "BubbleSoak",
|
||||
"pre_wash": "PreWashSetting",
|
||||
"intensive": "IntensiveSetting",
|
||||
}[key]
|
||||
|
||||
def test_exists_only_when_field_present(self):
|
||||
for key in self._keys():
|
||||
desc = self._desc(key)
|
||||
assert desc.exists_fn({'x.com.samsung.da.options': []}, {}) is False
|
||||
assert desc.exists_fn({"x.com.samsung.da.options": []}, {}) is False
|
||||
prefix = self._prefix(key)
|
||||
rep = {'x.com.samsung.da.options': [f'{prefix}_Off']}
|
||||
rep = {"x.com.samsung.da.options": [f"{prefix}_Off"]}
|
||||
assert desc.exists_fn(rep, {}) is True
|
||||
|
||||
def test_reads_off(self):
|
||||
for key in self._keys():
|
||||
prefix = self._prefix(key)
|
||||
rep = {'x.com.samsung.da.options': [f'{prefix}_Off']}
|
||||
rep = {"x.com.samsung.da.options": [f"{prefix}_Off"]}
|
||||
assert self._desc(key).rep_fn(rep) is False
|
||||
|
||||
def test_reads_on(self):
|
||||
for key in self._keys():
|
||||
prefix = self._prefix(key)
|
||||
rep = {'x.com.samsung.da.options': [f'{prefix}_On']}
|
||||
rep = {"x.com.samsung.da.options": [f"{prefix}_On"]}
|
||||
assert self._desc(key).rep_fn(rep) is True
|
||||
|
||||
def test_write_on_and_off(self):
|
||||
@@ -310,21 +344,21 @@ class TestWashOptionToggles:
|
||||
the device merges by prefix itself), not the whole options array."""
|
||||
for key in self._keys():
|
||||
prefix = self._prefix(key)
|
||||
rep = {'x.com.samsung.da.options': [f'{prefix}_Off', 'GMT_02']}
|
||||
path, body = self._desc(key).write_fn('On', rep)
|
||||
assert path == ['course', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.options': [f'{prefix}_On']}
|
||||
rep = {"x.com.samsung.da.options": [f"{prefix}_Off", "GMT_02"]}
|
||||
path, body = self._desc(key).write_fn("On", rep)
|
||||
assert path == ["course", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.options": [f"{prefix}_On"]}
|
||||
|
||||
rep = {'x.com.samsung.da.options': [f'{prefix}_On']}
|
||||
path, body = self._desc(key).write_fn('Off', rep)
|
||||
assert body == {'x.com.samsung.da.options': [f'{prefix}_Off']}
|
||||
assert f'{prefix}_On' not in body['x.com.samsung.da.options']
|
||||
rep = {"x.com.samsung.da.options": [f"{prefix}_On"]}
|
||||
path, body = self._desc(key).write_fn("Off", rep)
|
||||
assert body == {"x.com.samsung.da.options": [f"{prefix}_Off"]}
|
||||
assert f"{prefix}_On" not in body["x.com.samsung.da.options"]
|
||||
|
||||
def test_write_rejects_non_on_off_payload(self):
|
||||
for key in self._keys():
|
||||
prefix = self._prefix(key)
|
||||
rep = {'x.com.samsung.da.options': [f'{prefix}_Off']}
|
||||
assert self._desc(key).write_fn('bogus', rep) is None
|
||||
rep = {"x.com.samsung.da.options": [f"{prefix}_Off"]}
|
||||
assert self._desc(key).write_fn("bogus", rep) is None
|
||||
|
||||
|
||||
# editCourseList and availability bitmaps from the reporter's issue #22
|
||||
@@ -333,14 +367,13 @@ class TestWashOptionToggles:
|
||||
# (available) on all three bitmaps; course '1C' at position 0 reads '00' on
|
||||
# BubbleSoakSet (matching the app graying that control out for Eco 40-60).
|
||||
_EDIT_COURSE_RESOURCES = {
|
||||
'/wm/editcourse/vs/0': {
|
||||
'x.com.samsung.da.editCourseList':
|
||||
'EditCourseList_1C301E26361B1D1F253324322022232F212D272838393729',
|
||||
"/wm/editcourse/vs/0": {
|
||||
"x.com.samsung.da.editCourseList": "EditCourseList_1C301E26361B1D1F253324322022232F212D272838393729", # noqa: E501
|
||||
},
|
||||
}
|
||||
_BUBBLE_SOAK_SET = 'BubbleSoakSet_00F000F000F000F0F0F0F00000F000F0F00000F000000000'
|
||||
_PRE_WASH_AVAILABLE_SET = 'PreWashAvailableSet_F0F000F0F0F000F0F0F0F00000F0F0F0F00000F000000000'
|
||||
_INTENSIVE_AVAILABLE_SET = 'IntensiveAvailableSet_F0F000F0F0F000F0F0F0F00000F0F0F0F00000F000000000'
|
||||
_BUBBLE_SOAK_SET = "BubbleSoakSet_00F000F000F000F0F0F0F00000F000F0F00000F000000000"
|
||||
_PRE_WASH_AVAILABLE_SET = "PreWashAvailableSet_F0F000F0F0F000F0F0F0F00000F0F0F0F00000F000000000"
|
||||
_INTENSIVE_AVAILABLE_SET = "IntensiveAvailableSet_F0F000F0F0F000F0F0F0F00000F0F0F0F00000F000000000"
|
||||
|
||||
|
||||
class TestWashOptionToggleValidation:
|
||||
@@ -354,43 +387,37 @@ class TestWashOptionToggleValidation:
|
||||
return next(e for e in washer.WASHER_COURSE.entities if e.key == key)
|
||||
|
||||
def test_allowed_on_a_supported_course(self):
|
||||
rep = {'x.com.samsung.da.options': ['Course_30', _BUBBLE_SOAK_SET]}
|
||||
assert self._desc('bubble_soak').validate_fn(
|
||||
'On', rep, _EDIT_COURSE_RESOURCES) is None
|
||||
rep = {"x.com.samsung.da.options": ["Course_30", _BUBBLE_SOAK_SET]}
|
||||
assert self._desc("bubble_soak").validate_fn("On", rep, _EDIT_COURSE_RESOURCES) is None
|
||||
|
||||
def test_rejected_on_an_unsupported_course(self):
|
||||
rep = {'x.com.samsung.da.options': ['Course_1C', _BUBBLE_SOAK_SET]}
|
||||
translation_key = self._desc('bubble_soak').validate_fn(
|
||||
'On', rep, _EDIT_COURSE_RESOURCES
|
||||
)
|
||||
assert translation_key == 'bubble_soak_unavailable_for_cycle'
|
||||
rep = {"x.com.samsung.da.options": ["Course_1C", _BUBBLE_SOAK_SET]}
|
||||
translation_key = self._desc("bubble_soak").validate_fn("On", rep, _EDIT_COURSE_RESOURCES)
|
||||
assert translation_key == "bubble_soak_unavailable_for_cycle"
|
||||
|
||||
def test_pre_wash_and_intensive_use_their_own_availableset_field(self):
|
||||
rep = {'x.com.samsung.da.options': ['Course_30', _PRE_WASH_AVAILABLE_SET]}
|
||||
assert self._desc('pre_wash').validate_fn(
|
||||
'On', rep, _EDIT_COURSE_RESOURCES) is None
|
||||
rep = {'x.com.samsung.da.options': ['Course_30', _INTENSIVE_AVAILABLE_SET]}
|
||||
assert self._desc('intensive').validate_fn(
|
||||
'On', rep, _EDIT_COURSE_RESOURCES) is None
|
||||
rep = {"x.com.samsung.da.options": ["Course_30", _PRE_WASH_AVAILABLE_SET]}
|
||||
assert self._desc("pre_wash").validate_fn("On", rep, _EDIT_COURSE_RESOURCES) is None
|
||||
rep = {"x.com.samsung.da.options": ["Course_30", _INTENSIVE_AVAILABLE_SET]}
|
||||
assert self._desc("intensive").validate_fn("On", rep, _EDIT_COURSE_RESOURCES) is None
|
||||
|
||||
def test_turning_off_is_never_blocked(self):
|
||||
rep = {'x.com.samsung.da.options': ['Course_1C', _BUBBLE_SOAK_SET]}
|
||||
assert self._desc('bubble_soak').validate_fn(
|
||||
'Off', rep, _EDIT_COURSE_RESOURCES) is None
|
||||
rep = {"x.com.samsung.da.options": ["Course_1C", _BUBBLE_SOAK_SET]}
|
||||
assert self._desc("bubble_soak").validate_fn("Off", rep, _EDIT_COURSE_RESOURCES) is None
|
||||
|
||||
def test_allows_write_when_course_unresolvable(self):
|
||||
"""No editCourseList, no Course_ token, or a bitmap whose length
|
||||
doesn't match editCourseList -- in every case, fail open rather than
|
||||
block a write we can't actually verify."""
|
||||
desc = self._desc('bubble_soak')
|
||||
rep = {'x.com.samsung.da.options': ['Course_1C', _BUBBLE_SOAK_SET]}
|
||||
assert desc.validate_fn('On', rep, {}) is None
|
||||
desc = self._desc("bubble_soak")
|
||||
rep = {"x.com.samsung.da.options": ["Course_1C", _BUBBLE_SOAK_SET]}
|
||||
assert desc.validate_fn("On", rep, {}) is None
|
||||
|
||||
rep = {'x.com.samsung.da.options': [_BUBBLE_SOAK_SET]}
|
||||
assert desc.validate_fn('On', rep, _EDIT_COURSE_RESOURCES) is None
|
||||
rep = {"x.com.samsung.da.options": [_BUBBLE_SOAK_SET]}
|
||||
assert desc.validate_fn("On", rep, _EDIT_COURSE_RESOURCES) is None
|
||||
|
||||
rep = {'x.com.samsung.da.options': ['Course_1C', 'BubbleSoakSet_00F0']}
|
||||
assert desc.validate_fn('On', rep, _EDIT_COURSE_RESOURCES) is None
|
||||
rep = {"x.com.samsung.da.options": ["Course_1C", "BubbleSoakSet_00F0"]}
|
||||
assert desc.validate_fn("On", rep, _EDIT_COURSE_RESOURCES) is None
|
||||
|
||||
|
||||
class TestAiEnergyLevel:
|
||||
@@ -407,7 +434,7 @@ class TestAiEnergyLevel:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('washer')
|
||||
resources = _load_device("washer")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -417,7 +444,7 @@ class TestAiEnergyLevel:
|
||||
)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert state['ai_energy_level'] is False # aiLevel '0' -- off
|
||||
assert state["ai_energy_level"] is False # aiLevel '0' -- off
|
||||
|
||||
|
||||
class TestFlexWashAndComboFixturesHaveCompleteCoverage:
|
||||
@@ -431,7 +458,7 @@ class TestFlexWashAndComboFixturesHaveCompleteCoverage:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('washer_flexwash')
|
||||
resources = _load_device("washer_flexwash")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -441,7 +468,7 @@ class TestFlexWashAndComboFixturesHaveCompleteCoverage:
|
||||
)
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
assert 'dry_level' not in state # plain washer -- no supportedDryLevel field
|
||||
assert "dry_level" not in state # plain washer -- no supportedDryLevel field
|
||||
|
||||
def test_dryer_combo(self):
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
@@ -449,7 +476,7 @@ class TestFlexWashAndComboFixturesHaveCompleteCoverage:
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from tests.conftest import _load_device
|
||||
|
||||
resources = _load_device('washer_dryer_combo')
|
||||
resources = _load_device("washer_dryer_combo")
|
||||
unbound = []
|
||||
bound = discover(
|
||||
resources,
|
||||
@@ -460,4 +487,4 @@ class TestFlexWashAndComboFixturesHaveCompleteCoverage:
|
||||
assert unbound == []
|
||||
state = flatten(bound, resources)
|
||||
# the device's own "off" sentinel is the literal string 'None', not absence
|
||||
assert state['dry_level'] == 'None'
|
||||
assert state["dry_level"] == "None"
|
||||
@@ -1,5 +1,7 @@
|
||||
"""HA water_heater-entity mapping tests for the EHS DHW loop."""
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from homeassistant.components.water_heater import (
|
||||
STATE_ECO,
|
||||
STATE_HEAT_PUMP,
|
||||
@@ -17,9 +19,9 @@ from tests.conftest import _load_device
|
||||
|
||||
|
||||
class _FakeCoordinator:
|
||||
device_serial = 'TEST-EHS-SERIAL'
|
||||
device_info = {}
|
||||
data = {}
|
||||
device_serial = "TEST-EHS-SERIAL"
|
||||
device_info: ClassVar[dict] = {}
|
||||
data: ClassVar[dict] = {}
|
||||
|
||||
def __init__(self, resources):
|
||||
self.last_resources = resources
|
||||
@@ -40,20 +42,22 @@ class _FakeCoordinator:
|
||||
|
||||
def _entity(resources, coordinator=None):
|
||||
bound = discover(
|
||||
resources, ehs.REGISTRY.capabilities, ehs.REGISTRY.pattern_capabilities,
|
||||
resources,
|
||||
ehs.REGISTRY.capabilities,
|
||||
ehs.REGISTRY.pattern_capabilities,
|
||||
)
|
||||
water_heater_bound = next(item for item in bound if isinstance(item.desc, WaterHeaterDesc))
|
||||
return LocalThingsWaterHeater(coordinator or _FakeCoordinator(resources), water_heater_bound)
|
||||
|
||||
|
||||
def test_current_operation_reads_eco_when_on():
|
||||
entity = _entity(_load_device('ehs'))
|
||||
entity = _entity(_load_device("ehs"))
|
||||
assert entity.current_operation == STATE_ECO
|
||||
|
||||
|
||||
def test_current_operation_is_off_when_powered_off():
|
||||
resources = _load_device('ehs')
|
||||
resources['/power/dhw/vs/0']['x.com.samsung.da.power'] = 'Off'
|
||||
resources = _load_device("ehs")
|
||||
resources["/power/dhw/vs/0"]["x.com.samsung.da.power"] = "Off"
|
||||
entity = _entity(resources)
|
||||
assert entity.current_operation == STATE_OFF
|
||||
|
||||
@@ -62,14 +66,18 @@ def test_operation_list_includes_off_and_mapped_modes():
|
||||
"""Fixture's supportedModes is Eco/Std/Power/Force -- all four map onto
|
||||
HA's own standard water_heater states (see water_heater.py's module
|
||||
docstring for the SmartThings-cloud precedent this mirrors)."""
|
||||
entity = _entity(_load_device('ehs'))
|
||||
entity = _entity(_load_device("ehs"))
|
||||
assert entity.operation_list == [
|
||||
STATE_OFF, STATE_ECO, STATE_HEAT_PUMP, STATE_PERFORMANCE, STATE_HIGH_DEMAND,
|
||||
STATE_OFF,
|
||||
STATE_ECO,
|
||||
STATE_HEAT_PUMP,
|
||||
STATE_PERFORMANCE,
|
||||
STATE_HIGH_DEMAND,
|
||||
]
|
||||
|
||||
|
||||
def test_temperature_reads_current_and_target():
|
||||
entity = _entity(_load_device('ehs'))
|
||||
entity = _entity(_load_device("ehs"))
|
||||
assert entity.current_temperature == 38.0
|
||||
assert entity.target_temperature == 40.0
|
||||
assert entity.temperature_unit == UnitOfTemperature.CELSIUS
|
||||
@@ -82,8 +90,8 @@ def test_temperature_bounds_fall_back_together():
|
||||
"""A board reporting only one end of the range must not pair a real
|
||||
device bound with an HA default -- both ends or neither, same rule as
|
||||
climate._range()."""
|
||||
resources = _load_device('ehs')
|
||||
del resources['/temperatures/dhw/vs/0']['x.com.samsung.da.maximum']
|
||||
resources = _load_device("ehs")
|
||||
del resources["/temperatures/dhw/vs/0"]["x.com.samsung.da.maximum"]
|
||||
entity = _entity(resources)
|
||||
|
||||
# Neither end comes from the device: the device minimum (40.0) is
|
||||
@@ -98,16 +106,16 @@ def test_temperature_bounds_fall_back_together():
|
||||
|
||||
def test_zero_increment_is_not_collapsed_into_the_default():
|
||||
"""`or` would turn a genuine 0 into 0.5 (issue #160)."""
|
||||
resources = _load_device('ehs')
|
||||
resources['/temperatures/dhw/vs/0']['x.com.samsung.da.increment'] = '0'
|
||||
resources = _load_device("ehs")
|
||||
resources["/temperatures/dhw/vs/0"]["x.com.samsung.da.increment"] = "0"
|
||||
entity = _entity(resources)
|
||||
|
||||
assert entity.target_temperature_step == 0.0
|
||||
|
||||
|
||||
def test_current_operation_tolerates_lowercase_device_codes():
|
||||
resources = _load_device('ehs')
|
||||
resources['/mode/dhw/vs/0']['x.com.samsung.da.modes'] = ['eco']
|
||||
resources = _load_device("ehs")
|
||||
resources["/mode/dhw/vs/0"]["x.com.samsung.da.modes"] = ["eco"]
|
||||
entity = _entity(resources)
|
||||
|
||||
assert entity.current_operation == STATE_ECO
|
||||
@@ -116,55 +124,54 @@ def test_current_operation_tolerates_lowercase_device_codes():
|
||||
def test_entity_is_named_rather_than_taking_the_device_name():
|
||||
"""Unlike climate.py's AC, DHW is one loop of a two-loop device, so it
|
||||
takes a catalog name instead of presenting as the device itself."""
|
||||
entity = _entity(_load_device('ehs'))
|
||||
entity = _entity(_load_device("ehs"))
|
||||
|
||||
# No _attr_name override (that would present as the bare device name,
|
||||
# and would also beat the catalog); the name comes from the catalog key.
|
||||
assert '_attr_name' not in entity.__dict__
|
||||
assert entity.translation_key == 'dhw'
|
||||
assert "_attr_name" not in entity.__dict__
|
||||
assert entity.translation_key == "dhw"
|
||||
|
||||
|
||||
async def test_set_temperature_writes_dhw_temperature():
|
||||
resources = _load_device('ehs')
|
||||
resources = _load_device("ehs")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_temperature(temperature=45.0)
|
||||
|
||||
assert coordinator.commands == [(entity._bound, ('temperature', 45.0))]
|
||||
assert coordinator.commands == [(entity._bound, ("temperature", 45.0))]
|
||||
|
||||
|
||||
async def test_set_temperature_honours_operation_mode():
|
||||
"""water_heater.set_temperature carries an optional operation_mode
|
||||
(SET_TEMPERATURE_SCHEMA); dropping it would move the setpoint without
|
||||
ever changing mode -- same bug fixed for climate's hvac_mode."""
|
||||
resources = _load_device('ehs')
|
||||
resources['/power/dhw/vs/0']['x.com.samsung.da.power'] = 'Off'
|
||||
resources = _load_device("ehs")
|
||||
resources["/power/dhw/vs/0"]["x.com.samsung.da.power"] = "Off"
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_temperature(temperature=55.0,
|
||||
operation_mode=STATE_HIGH_DEMAND)
|
||||
await entity.async_set_temperature(temperature=55.0, operation_mode=STATE_HIGH_DEMAND)
|
||||
|
||||
assert coordinator.commands == [
|
||||
(entity._bound, ('power', True)),
|
||||
(entity._bound, ('mode', 'Force')),
|
||||
(entity._bound, ('temperature', 55.0)),
|
||||
(entity._bound, ("power", True)),
|
||||
(entity._bound, ("mode", "Force")),
|
||||
(entity._bound, ("temperature", 55.0)),
|
||||
]
|
||||
|
||||
|
||||
async def test_set_temperature_with_off_mode_skips_the_setpoint_write():
|
||||
resources = _load_device('ehs')
|
||||
resources = _load_device("ehs")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_temperature(temperature=55.0, operation_mode=STATE_OFF)
|
||||
|
||||
assert coordinator.commands == [(entity._bound, ('power', False))]
|
||||
assert coordinator.commands == [(entity._bound, ("power", False))]
|
||||
|
||||
|
||||
async def test_turn_on_and_off_write_dhw_power():
|
||||
resources = _load_device('ehs')
|
||||
resources = _load_device("ehs")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
@@ -172,41 +179,41 @@ async def test_turn_on_and_off_write_dhw_power():
|
||||
await entity.async_turn_off()
|
||||
|
||||
assert coordinator.commands == [
|
||||
(entity._bound, ('power', True)),
|
||||
(entity._bound, ('power', False)),
|
||||
(entity._bound, ("power", True)),
|
||||
(entity._bound, ("power", False)),
|
||||
]
|
||||
|
||||
|
||||
async def test_set_operation_mode_off_turns_off_without_writing_mode():
|
||||
resources = _load_device('ehs')
|
||||
resources = _load_device("ehs")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_operation_mode(STATE_OFF)
|
||||
|
||||
assert coordinator.commands == [(entity._bound, ('power', False))]
|
||||
assert coordinator.commands == [(entity._bound, ("power", False))]
|
||||
|
||||
|
||||
async def test_set_operation_mode_writes_mapped_device_code():
|
||||
resources = _load_device('ehs')
|
||||
resources = _load_device("ehs")
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_operation_mode(STATE_HIGH_DEMAND)
|
||||
|
||||
# DHW power is already on (fixture default) -- no extra power write.
|
||||
assert coordinator.commands == [(entity._bound, ('mode', 'Force'))]
|
||||
assert coordinator.commands == [(entity._bound, ("mode", "Force"))]
|
||||
|
||||
|
||||
async def test_set_operation_mode_powers_on_first_when_off():
|
||||
resources = _load_device('ehs')
|
||||
resources['/power/dhw/vs/0']['x.com.samsung.da.power'] = 'Off'
|
||||
resources = _load_device("ehs")
|
||||
resources["/power/dhw/vs/0"]["x.com.samsung.da.power"] = "Off"
|
||||
coordinator = _FakeCoordinator(resources)
|
||||
entity = _entity(resources, coordinator)
|
||||
|
||||
await entity.async_set_operation_mode(STATE_PERFORMANCE)
|
||||
|
||||
assert coordinator.commands == [
|
||||
(entity._bound, ('power', True)),
|
||||
(entity._bound, ('mode', 'Power')),
|
||||
(entity._bound, ("power", True)),
|
||||
(entity._bound, ("mode", "Power")),
|
||||
]
|
||||
@@ -3,19 +3,20 @@
|
||||
HA-free like the rest of the suite: exercises the registry, discovery/
|
||||
flatten, and the write contracts.
|
||||
"""
|
||||
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
from custom_components.localthings.registry.by_type import for_device_by_model
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.entities import NumberDesc
|
||||
|
||||
from tests.conftest import _load_device
|
||||
|
||||
|
||||
def _water_purifier():
|
||||
resources = _load_device('water_purifier')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("water_purifier")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -37,7 +38,7 @@ def _desc(key):
|
||||
|
||||
def test_model_resolves_to_water_purifier_registry():
|
||||
reg, _ = _water_purifier()
|
||||
assert reg is not None and reg.name == 'water_purifier'
|
||||
assert reg is not None and reg.name == "water_purifier"
|
||||
|
||||
|
||||
def test_no_unbound_hrefs():
|
||||
@@ -51,30 +52,39 @@ def test_no_unbound_hrefs():
|
||||
|
||||
def test_expected_state_keys_present():
|
||||
state = _state()
|
||||
for key in ('dispense_type', 'hot_water_temperature', 'dispense_capacity',
|
||||
'pouring', 'waterpurifier_status', 'filter_usage', 'filter_status',
|
||||
'hotwater_lock', 'coldwater_lock', 'buzz_lock'):
|
||||
for key in (
|
||||
"dispense_type",
|
||||
"hot_water_temperature",
|
||||
"dispense_capacity",
|
||||
"pouring",
|
||||
"waterpurifier_status",
|
||||
"filter_usage",
|
||||
"filter_status",
|
||||
"hotwater_lock",
|
||||
"coldwater_lock",
|
||||
"buzz_lock",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
|
||||
def test_dispense_type_options_come_from_live_supported_types():
|
||||
desc = _desc('dispense_type')
|
||||
assert desc.options_field == 'x.com.samsung.da.supportedTypes'
|
||||
desc = _desc("dispense_type")
|
||||
assert desc.options_field == "x.com.samsung.da.supportedTypes"
|
||||
|
||||
|
||||
def test_dispense_type_write_contract():
|
||||
desc = _desc('dispense_type')
|
||||
path, body = desc.write_fn('hotwater', {})
|
||||
assert path == ['setting', 'waterpurifier', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.desiredType': 'hotwater'}
|
||||
desc = _desc("dispense_type")
|
||||
path, body = desc.write_fn("hotwater", {})
|
||||
assert path == ["setting", "waterpurifier", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.desiredType": "hotwater"}
|
||||
|
||||
|
||||
def test_hot_water_temperature_is_a_select_not_a_number():
|
||||
"""Only a handful of discrete temperatures are selectable (not a
|
||||
continuous range) -- confirmed by supportedHotTemperatures being a short
|
||||
enumerated list, not a [min, max] range field."""
|
||||
desc = _desc('hot_water_temperature')
|
||||
assert desc.options_field == 'x.com.samsung.da.supportedHotTemperatures'
|
||||
desc = _desc("hot_water_temperature")
|
||||
assert desc.options_field == "x.com.samsung.da.supportedHotTemperatures"
|
||||
|
||||
|
||||
def test_dispense_capacity_bounds_come_live_not_hardcoded():
|
||||
@@ -82,51 +92,59 @@ def test_dispense_capacity_bounds_come_live_not_hardcoded():
|
||||
capacityResolution fields, not a hardcoded constant -- see the
|
||||
adding-device-support skill's 'never hard-code the one dump's values'
|
||||
section."""
|
||||
desc = _desc('dispense_capacity')
|
||||
desc = _desc("dispense_capacity")
|
||||
assert isinstance(desc, NumberDesc)
|
||||
assert desc.native_min is None
|
||||
assert desc.native_max is None
|
||||
assert desc.range_field == 'x.com.samsung.da.desiredCapacityRange'
|
||||
rep = {'x.com.samsung.da.desiredCapacityRange': ['50', '2000'],
|
||||
'x.com.samsung.da.capacityResolution': '10'}
|
||||
assert desc.range_field == "x.com.samsung.da.desiredCapacityRange"
|
||||
rep = {
|
||||
"x.com.samsung.da.desiredCapacityRange": ["50", "2000"],
|
||||
"x.com.samsung.da.capacityResolution": "10",
|
||||
}
|
||||
assert desc.step_fn(rep) == 10
|
||||
|
||||
|
||||
def test_dispense_capacity_write_contract():
|
||||
desc = _desc('dispense_capacity')
|
||||
path, body = desc.write_fn('550', {})
|
||||
assert path == ['setting', 'waterpurifier', 'vs', '0']
|
||||
assert body == {'x.com.samsung.da.desiredCapacity': '550'}
|
||||
desc = _desc("dispense_capacity")
|
||||
path, body = desc.write_fn("550", {})
|
||||
assert path == ["setting", "waterpurifier", "vs", "0"]
|
||||
assert body == {"x.com.samsung.da.desiredCapacity": "550"}
|
||||
|
||||
|
||||
def test_lock_switches_read_unlocked_as_off():
|
||||
state = _state()
|
||||
assert state['hotwater_lock'] is False
|
||||
assert state['coldwater_lock'] is False
|
||||
assert state['buzz_lock'] is False
|
||||
assert state["hotwater_lock"] is False
|
||||
assert state["coldwater_lock"] is False
|
||||
assert state["buzz_lock"] is False
|
||||
|
||||
|
||||
def test_lock_switch_write_contracts():
|
||||
hot = _desc('hotwater_lock')
|
||||
cold = _desc('coldwater_lock')
|
||||
buzz = _desc('buzz_lock')
|
||||
assert hot.write_fn('On', {}) == (
|
||||
['status', 'lock', 'vs', '0'], {'x.com.samsung.da.hotwaterLock': 'Locked'})
|
||||
assert cold.write_fn('Off', {}) == (
|
||||
['status', 'lock', 'vs', '0'], {'x.com.samsung.da.coldwaterLock': 'Unlocked'})
|
||||
assert buzz.write_fn('On', {}) == (
|
||||
['status', 'lock', 'vs', '0'], {'x.com.samsung.da.buzzLock': 'Locked'})
|
||||
hot = _desc("hotwater_lock")
|
||||
cold = _desc("coldwater_lock")
|
||||
buzz = _desc("buzz_lock")
|
||||
assert hot.write_fn("On", {}) == (
|
||||
["status", "lock", "vs", "0"],
|
||||
{"x.com.samsung.da.hotwaterLock": "Locked"},
|
||||
)
|
||||
assert cold.write_fn("Off", {}) == (
|
||||
["status", "lock", "vs", "0"],
|
||||
{"x.com.samsung.da.coldwaterLock": "Unlocked"},
|
||||
)
|
||||
assert buzz.write_fn("On", {}) == (
|
||||
["status", "lock", "vs", "0"],
|
||||
{"x.com.samsung.da.buzzLock": "Locked"},
|
||||
)
|
||||
|
||||
|
||||
def test_favorite_capacity_options_come_from_live_capacity_list():
|
||||
desc = _desc('favorite_capacity')
|
||||
assert desc.options_field == 'x.com.samsung.da.capacityList'
|
||||
desc = _desc("favorite_capacity")
|
||||
assert desc.options_field == "x.com.samsung.da.capacityList"
|
||||
|
||||
|
||||
def test_sterilize_timestamps_parsed_as_utc():
|
||||
state = _state()
|
||||
assert state['sterilize_last_time'].tzinfo is not None
|
||||
assert state['sterilize_plan_time'].tzinfo is not None
|
||||
assert state["sterilize_last_time"].tzinfo is not None
|
||||
assert state["sterilize_plan_time"].tzinfo is not None
|
||||
|
||||
|
||||
def test_mode_hrefs_are_ignored_not_guessed():
|
||||
@@ -135,9 +153,10 @@ def test_mode_hrefs_are_ignored_not_guessed():
|
||||
plumbing, left unmodeled per the 'don't guess' rule rather than exposed
|
||||
as a nonsensical select."""
|
||||
from custom_components.localthings.registry.capabilities import water_purifier
|
||||
|
||||
ignored_hrefs = {cap.href for cap in water_purifier.COVERAGE}
|
||||
assert '/mode/vs/0' in ignored_hrefs
|
||||
assert '/automation/waterpurifier/vs/0' in ignored_hrefs
|
||||
assert "/mode/vs/0" in ignored_hrefs
|
||||
assert "/automation/waterpurifier/vs/0" in ignored_hrefs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -145,11 +164,13 @@ def test_mode_hrefs_are_ignored_not_guessed():
|
||||
# /favorite/hotwater/vs/0, not present in issue #90's original dump.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _water_purifier_coffee():
|
||||
resources = _load_device('water_purifier_coffee')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("water_purifier_coffee")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -188,17 +209,25 @@ def test_coffee_variant_no_unbound_hrefs():
|
||||
|
||||
def test_coffee_variant_expected_state_keys_present():
|
||||
state = _state_coffee()
|
||||
for key in ('favorite_coffee_enabled', 'coffee_brew_status',
|
||||
'hotwater_lock', 'favorite_hotwater_temperature'):
|
||||
for key in (
|
||||
"favorite_coffee_enabled",
|
||||
"coffee_brew_status",
|
||||
"hotwater_lock",
|
||||
"favorite_hotwater_temperature",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
|
||||
def test_favorite_coffee_write_contract():
|
||||
desc = _desc_coffee('favorite_coffee_enabled')
|
||||
assert desc.write_fn('On', {}) == (
|
||||
['favorite', 'coffee', 'vs', '0'], {'favorite.activate': 'On'})
|
||||
assert desc.write_fn('Off', {}) == (
|
||||
['favorite', 'coffee', 'vs', '0'], {'favorite.activate': 'Off'})
|
||||
desc = _desc_coffee("favorite_coffee_enabled")
|
||||
assert desc.write_fn("On", {}) == (
|
||||
["favorite", "coffee", "vs", "0"],
|
||||
{"favorite.activate": "On"},
|
||||
)
|
||||
assert desc.write_fn("Off", {}) == (
|
||||
["favorite", "coffee", "vs", "0"],
|
||||
{"favorite.activate": "Off"},
|
||||
)
|
||||
|
||||
|
||||
def test_favorite_hotwater_switch_is_a_lock_not_an_enable_flag():
|
||||
@@ -207,13 +236,17 @@ def test_favorite_hotwater_switch_is_a_lock_not_an_enable_flag():
|
||||
hot-water lock as LOCK.hotwater_lock, just surfaced through this href on
|
||||
boards (like this fixture's) that don't populate /status/lock/vs/0's
|
||||
hotwaterLock field."""
|
||||
lock = _desc_coffee_by_href('hotwater_lock', '/favorite/hotwater/vs/0')
|
||||
assert lock.write_fn('On', {}) == (
|
||||
['favorite', 'hotwater', 'vs', '0'], {'x.com.samsung.da.switchHotwater': 'Locked'})
|
||||
assert lock.write_fn('Off', {}) == (
|
||||
['favorite', 'hotwater', 'vs', '0'], {'x.com.samsung.da.switchHotwater': 'Unlocked'})
|
||||
assert lock.value_fn('Unlocked') is False
|
||||
assert lock.value_fn('Locked') is True
|
||||
lock = _desc_coffee_by_href("hotwater_lock", "/favorite/hotwater/vs/0")
|
||||
assert lock.write_fn("On", {}) == (
|
||||
["favorite", "hotwater", "vs", "0"],
|
||||
{"x.com.samsung.da.switchHotwater": "Locked"},
|
||||
)
|
||||
assert lock.write_fn("Off", {}) == (
|
||||
["favorite", "hotwater", "vs", "0"],
|
||||
{"x.com.samsung.da.switchHotwater": "Unlocked"},
|
||||
)
|
||||
assert lock.value_fn("Unlocked") is False
|
||||
assert lock.value_fn("Locked") is True
|
||||
|
||||
|
||||
def test_favorite_hotwater_lock_wins_in_flattened_state():
|
||||
@@ -229,7 +262,7 @@ def test_favorite_hotwater_lock_wins_in_flattened_state():
|
||||
and flatten() would pick whichever of the two entities happens to be
|
||||
processed last."""
|
||||
state = _state_coffee()
|
||||
assert state['hotwater_lock'] is False
|
||||
assert state["hotwater_lock"] is False
|
||||
|
||||
|
||||
def test_exactly_one_hotwater_lock_descriptor_exists_per_resource_state():
|
||||
@@ -239,12 +272,11 @@ def test_exactly_one_hotwater_lock_descriptor_exists_per_resource_state():
|
||||
the two must ever pass, regardless of iteration order, or two switch
|
||||
entities would be registered with the same unique_id."""
|
||||
bound, resources = _bound_coffee()
|
||||
candidates = [b for b in bound if b.desc.key == 'hotwater_lock']
|
||||
candidates = [b for b in bound if b.desc.key == "hotwater_lock"]
|
||||
assert len(candidates) == 2
|
||||
included = [b for b in candidates
|
||||
if b.desc.exists_fn(resources.get(b.href) or {}, resources)]
|
||||
included = [b for b in candidates if b.desc.exists_fn(resources.get(b.href) or {}, resources)]
|
||||
assert len(included) == 1
|
||||
assert included[0].href == '/favorite/hotwater/vs/0'
|
||||
assert included[0].href == "/favorite/hotwater/vs/0"
|
||||
|
||||
|
||||
def test_hotwater_lock_fallback_gating_across_status_lock_states():
|
||||
@@ -252,29 +284,29 @@ def test_hotwater_lock_fallback_gating_across_status_lock_states():
|
||||
activate only once /status/lock/vs/0 is confirmed to lack hotwaterLock --
|
||||
never while that resource is an unfetched stub ({}), and never when it
|
||||
does carry the field. LOCK's own descriptor is the mirror image."""
|
||||
fallback = _desc_coffee_by_href('hotwater_lock', '/favorite/hotwater/vs/0')
|
||||
primary = _desc_coffee_by_href('hotwater_lock', '/status/lock/vs/0')
|
||||
own_rep = {'x.com.samsung.da.switchHotwater': 'Unlocked'}
|
||||
fallback = _desc_coffee_by_href("hotwater_lock", "/favorite/hotwater/vs/0")
|
||||
primary = _desc_coffee_by_href("hotwater_lock", "/status/lock/vs/0")
|
||||
own_rep = {"x.com.samsung.da.switchHotwater": "Unlocked"}
|
||||
|
||||
# /status/lock/vs/0 absent entirely -- device genuinely lacks it.
|
||||
assert fallback.exists_fn(own_rep, {}) is True
|
||||
|
||||
# /status/lock/vs/0 present but not yet fetched (a stub): outcome
|
||||
# pending, so the fallback must defer to LOCK rather than assume absence.
|
||||
stub_resources = {'/status/lock/vs/0': {}}
|
||||
stub_resources = {"/status/lock/vs/0": {}}
|
||||
assert fallback.exists_fn(own_rep, stub_resources) is False
|
||||
assert primary.exists_fn({}, stub_resources) is True
|
||||
|
||||
# /status/lock/vs/0 fetched and confirmed to lack hotwaterLock (this
|
||||
# fixture's actual shape) -- the fallback wins.
|
||||
absent_resources = {'/status/lock/vs/0': {'x.com.samsung.da.coldwaterLock': 'Unlocked'}}
|
||||
absent_resources = {"/status/lock/vs/0": {"x.com.samsung.da.coldwaterLock": "Unlocked"}}
|
||||
assert fallback.exists_fn(own_rep, absent_resources) is True
|
||||
assert primary.exists_fn(absent_resources['/status/lock/vs/0'], absent_resources) is False
|
||||
assert primary.exists_fn(absent_resources["/status/lock/vs/0"], absent_resources) is False
|
||||
|
||||
# /status/lock/vs/0 fetched and does carry hotwaterLock -- primary wins.
|
||||
present_resources = {'/status/lock/vs/0': {'x.com.samsung.da.hotwaterLock': 'Unlocked'}}
|
||||
present_resources = {"/status/lock/vs/0": {"x.com.samsung.da.hotwaterLock": "Unlocked"}}
|
||||
assert fallback.exists_fn(own_rep, present_resources) is False
|
||||
assert primary.exists_fn(present_resources['/status/lock/vs/0'], present_resources) is True
|
||||
assert primary.exists_fn(present_resources["/status/lock/vs/0"], present_resources) is True
|
||||
|
||||
# The fallback also re-asserts its own field, since it no longer gets
|
||||
# that check for free once it shares LOCK's key (issue #144 review).
|
||||
@@ -290,8 +322,8 @@ def test_favorite_hotwater_temperature_options_come_from_live_show_list():
|
||||
rendered as 'unknown' in HA (issue #196) -- see the ailite fixture's
|
||||
version of this test below for the case that actually exercises it
|
||||
(this fixture's showList == supportedList, no custom value set)."""
|
||||
desc = _desc_coffee('favorite_hotwater_temperature')
|
||||
assert desc.options_field == 'x.com.samsung.da.favorite.showList'
|
||||
desc = _desc_coffee("favorite_hotwater_temperature")
|
||||
assert desc.options_field == "x.com.samsung.da.favorite.showList"
|
||||
|
||||
|
||||
def test_coffee_recipe_hrefs_are_ignored_not_guessed():
|
||||
@@ -299,9 +331,14 @@ def test_coffee_recipe_hrefs_are_ignored_not_guessed():
|
||||
'current recipe'/'current custom slot' field to expose, per the 'don't
|
||||
guess' rule."""
|
||||
from custom_components.localthings.registry.capabilities import water_purifier
|
||||
|
||||
ignored_hrefs = {cap.href for cap in water_purifier.COVERAGE}
|
||||
for href in ('/brand/recipe/info/vs/0', '/coffee/custom/recipe/vs/0',
|
||||
'/recipe/coffee/vs/0', '/recipe/coffee/deletion/vs/0'):
|
||||
for href in (
|
||||
"/brand/recipe/info/vs/0",
|
||||
"/coffee/custom/recipe/vs/0",
|
||||
"/recipe/coffee/vs/0",
|
||||
"/recipe/coffee/deletion/vs/0",
|
||||
):
|
||||
assert href in ignored_hrefs, href
|
||||
|
||||
|
||||
@@ -315,11 +352,13 @@ def test_coffee_recipe_hrefs_are_ignored_not_guessed():
|
||||
# this device type.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _water_purifier_ailite():
|
||||
resources = _load_device('water_purifier_ailite_25k')
|
||||
info = resources['/information/vs/0']
|
||||
resources = _load_device("water_purifier_ailite_25k")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = for_device_by_model(
|
||||
info['x.com.samsung.da.modelNum'], info['x.com.samsung.da.description'],
|
||||
info["x.com.samsung.da.modelNum"],
|
||||
info["x.com.samsung.da.description"],
|
||||
)
|
||||
return reg, resources
|
||||
|
||||
@@ -341,7 +380,7 @@ def _desc_ailite(key):
|
||||
|
||||
def test_ailite_model_resolves_to_water_purifier_not_refrigerator():
|
||||
reg, _ = _water_purifier_ailite()
|
||||
assert reg is not None and reg.name == 'water_purifier'
|
||||
assert reg is not None and reg.name == "water_purifier"
|
||||
|
||||
|
||||
def test_ailite_no_unbound_hrefs():
|
||||
@@ -353,8 +392,15 @@ def test_ailite_no_unbound_hrefs():
|
||||
|
||||
def test_ailite_expected_state_keys_present():
|
||||
state = _state_ailite()
|
||||
for key in ('cup_state', 'sound_mode', 'sound_output', 'sound_volume',
|
||||
'alarm_in_mute', 'last_pour_type', 'last_pour_capacity'):
|
||||
for key in (
|
||||
"cup_state",
|
||||
"sound_mode",
|
||||
"sound_output",
|
||||
"sound_volume",
|
||||
"alarm_in_mute",
|
||||
"last_pour_type",
|
||||
"last_pour_capacity",
|
||||
):
|
||||
assert key in state, key
|
||||
|
||||
|
||||
@@ -366,7 +412,7 @@ def test_ailite_hot_water_temperature_gated_off_without_supported_list():
|
||||
an empty options list. The descriptor must gate off entirely rather than
|
||||
register with empty options."""
|
||||
state = _state_ailite()
|
||||
assert 'hot_water_temperature' not in state
|
||||
assert "hot_water_temperature" not in state
|
||||
|
||||
|
||||
def test_ailite_favorite_hotwater_temperature_options_include_the_custom_value():
|
||||
@@ -379,16 +425,16 @@ def test_ailite_favorite_hotwater_temperature_options_include_the_custom_value()
|
||||
doesn't contain the current default, so HA would render the entity as
|
||||
'unknown'. The descriptor must read from showList so '50' is in
|
||||
options."""
|
||||
desc = _desc_ailite('favorite_hotwater_temperature')
|
||||
assert desc.options_field == 'x.com.samsung.da.favorite.showList'
|
||||
desc = _desc_ailite("favorite_hotwater_temperature")
|
||||
assert desc.options_field == "x.com.samsung.da.favorite.showList"
|
||||
_, resources = _water_purifier_ailite()
|
||||
rep = resources['/favorite/hotwater/vs/0']
|
||||
rep = resources["/favorite/hotwater/vs/0"]
|
||||
# defaultTemperature='50' must be a member of the field the descriptor
|
||||
# actually reads -- this is the precise assertion that would fail under
|
||||
# the old supportedList behavior.
|
||||
assert rep['x.com.samsung.da.favorite.defaultTemperature'] == '50'
|
||||
assert '50' in rep[desc.options_field]
|
||||
assert '50' not in rep['x.com.samsung.da.favorite.supportedList']
|
||||
assert rep["x.com.samsung.da.favorite.defaultTemperature"] == "50"
|
||||
assert "50" in rep[desc.options_field]
|
||||
assert "50" not in rep["x.com.samsung.da.favorite.supportedList"]
|
||||
|
||||
|
||||
def test_ailite_sound_mode_options_come_from_live_supported_modes():
|
||||
@@ -396,16 +442,16 @@ def test_ailite_sound_mode_options_come_from_live_supported_modes():
|
||||
laundry.SOUND_MODE's hardcoded voice/tone/mute and air_purifier.SOUND_MODE's
|
||||
mute/buzzer -- reusing either would reject a value this device actually
|
||||
supports, per the oven._OVEN_MODES lesson from issue #138."""
|
||||
desc = _desc_ailite('sound_mode')
|
||||
assert desc.options_field == 'supportedModes'
|
||||
assert desc.translation_key == 'water_purifier_sound_mode'
|
||||
desc = _desc_ailite("sound_mode")
|
||||
assert desc.options_field == "supportedModes"
|
||||
assert desc.translation_key == "water_purifier_sound_mode"
|
||||
|
||||
|
||||
def test_ailite_sound_volume_bounds_come_live_not_hardcoded():
|
||||
desc = _desc_ailite('sound_volume')
|
||||
desc = _desc_ailite("sound_volume")
|
||||
assert isinstance(desc, NumberDesc)
|
||||
assert desc.native_min is None and desc.native_max is None
|
||||
rep = {'minLevel': '0', 'maxLevel': '15', 'resolution': '5'}
|
||||
rep = {"minLevel": "0", "maxLevel": "15", "resolution": "5"}
|
||||
assert desc.native_min_fn(rep) == 0
|
||||
assert desc.native_max_fn(rep) == 15
|
||||
assert desc.step_fn(rep) == 5
|
||||
@@ -416,7 +462,8 @@ def test_ailite_alarm_in_mute_is_read_only():
|
||||
as a read-only diagnostic per the 'don't guess' rule rather than an
|
||||
invented switch."""
|
||||
from custom_components.localthings.registry.entities import BinarySensorDesc
|
||||
desc = _desc_ailite('alarm_in_mute')
|
||||
|
||||
desc = _desc_ailite("alarm_in_mute")
|
||||
assert isinstance(desc, BinarySensorDesc)
|
||||
assert desc.value_fn('true') is True
|
||||
assert desc.value_fn('false') is False
|
||||
assert desc.value_fn("true") is True
|
||||
assert desc.value_fn("false") is False
|
||||
Reference in new issue
Block a user