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:
Marc Billow committed 2026-08-02 23:56:38 +00:00
1 parent b0eab93b58
commit daf7e3787f
147 files changed
+9977 -7584

No files matched your search

+52 -45
View File
@@ -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
+219 -173
View File
@@ -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
+15 -9
View File
@@ -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
+74 -62
View File
@@ -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
+96 -90
View File
@@ -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
+10 -17
View File
@@ -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"