refactor(observe): stop tearing down live sessions on data-drift or poll hiccups
Replace the breadth/silence downgrade heuristic with a simpler rule: a still-live OBSERVE session is never torn down on a sweep/cache mismatch (the 30s sweep already corrects the cache regardless of mode) -- only a proven reconnect invalidates subscriptions. A mismatch instead triggers extra hot/warm subpolls this cycle as a bounded fallback. Also stop treating a summary-poll block-level ACK timeout as session death: distinguish TimeoutError (transfer was progressing, session likely alive) from ConnectionError (session actually closed), backed by a consecutive-timeout counter so a genuinely dead channel still recovers. This was causing a flaky/slow device (e.g. a dishwasher) to flap observe<->poll every ~45s on nothing but a slow blockwise GET. Also remove the dead is_active/active_when scaffolding (never wired into the coordinator) and add DEBUG logging for each OBSERVE notify received, including its href.
This commit is contained in:
1 parent
7024b170fe
commit
569029c116
13 files changed
+745
-93
No files matched your search
@@ -35,6 +35,32 @@ 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.
|
||||
|
||||
`_run_subpolls` and `_attempt_observe_mode` are, by design, blocking/
|
||||
real-time operations in production (a real sub-poll cadence and a real
|
||||
CoAP OBSERVE grace period). Tests that drive them through a full
|
||||
`hass.config_entries.async_setup(...)` + `hass.async_block_till_done()`
|
||||
would otherwise burn tens of real seconds per test waiting them out.
|
||||
|
||||
This patches only the *class* attributes coordinator.py exposes for
|
||||
this purpose (`_SUBPOLL_STEP_S`, `_OBSERVE_GRACE_PERIOD_S`) — the
|
||||
production defaults they're computed from (`SUMMARY_INTERVAL_S`,
|
||||
`GRACE_PERIOD_S`) are untouched. Tests that need to exercise the real
|
||||
grace-period race (e.g. test_observe.py's own `ObserveManager` tests)
|
||||
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),
|
||||
):
|
||||
yield
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parent.parent / 'fixtures'
|
||||
|
||||
|
||||
@@ -12,10 +12,10 @@ from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import issue_registry as ir
|
||||
|
||||
from custom_components.localthings.const import (
|
||||
DOMAIN, SUMMARY_INTERVAL_S,
|
||||
CONF_HOST, DOMAIN, SUMMARY_INTERVAL_S,
|
||||
)
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
from custom_components.localthings.observe import MODE_OBSERVE, MODE_POLL
|
||||
from custom_components.localthings.observe import MODE_OBSERVE, MODE_POLL, PUSH_HEALTH_WINDOW_S
|
||||
|
||||
from .conftest import ENTRY_DATA, MOCK_SERIAL
|
||||
|
||||
@@ -182,6 +182,41 @@ async def test_last_resources_backed_by_state_cache(
|
||||
assert resources # fridge fixture is non-empty
|
||||
|
||||
|
||||
def test_logger_is_scoped_to_device_host(
|
||||
hass: HomeAssistant, mock_entry
|
||||
) -> None:
|
||||
"""Every log line (coordinator's own, DataUpdateCoordinator's internal
|
||||
messages, and ObserveManager's) must identify which device it's about —
|
||||
a bare module-level logger is shared across every configured device and
|
||||
makes multi-device logs ambiguous."""
|
||||
coordinator = LocalThingsCoordinator(hass, mock_entry)
|
||||
|
||||
assert coordinator._log.name.endswith(ENTRY_DATA[CONF_HOST])
|
||||
assert coordinator.logger is coordinator._log
|
||||
assert coordinator._observe.log is coordinator._log
|
||||
|
||||
|
||||
def test_cache_changes_coalesce_into_a_single_push(
|
||||
hass: HomeAssistant, mock_entry
|
||||
) -> None:
|
||||
"""A poll/sweep cycle applying many hrefs in a tight loop must not
|
||||
schedule one hass.add_job push per href — only one push per burst."""
|
||||
coordinator = LocalThingsCoordinator(hass, mock_entry)
|
||||
|
||||
with patch.object(hass, 'add_job') as mock_add_job:
|
||||
coordinator._on_cache_changed(True, 'poll')
|
||||
coordinator._on_cache_changed(True, 'poll')
|
||||
coordinator._on_cache_changed(True, 'poll')
|
||||
|
||||
assert mock_add_job.call_count == 1
|
||||
|
||||
coordinator._push_cache_snapshot()
|
||||
|
||||
coordinator._on_cache_changed(True, 'poll')
|
||||
|
||||
assert mock_add_job.call_count == 2
|
||||
|
||||
|
||||
async def test_enters_poll_mode_when_no_notifies_arrive(
|
||||
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
|
||||
) -> None:
|
||||
@@ -259,8 +294,21 @@ async def test_reconnect_while_observe_mode_downgrades_to_poll(
|
||||
assert entered is True
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
# Age out the notify so recently_notified() is False — a poll failure
|
||||
# with a recent notify is now treated as evidence the session is
|
||||
# still alive (see test_poll_failure_skips_reconnect_when_push_is_healthy)
|
||||
# and would not trigger a reconnect at all. This test covers a
|
||||
# genuinely dead channel: no recent push, poll fails, reconnect fires.
|
||||
coordinator._observe._last_notify_ts -= PUSH_HEALTH_WINDOW_S + 1
|
||||
|
||||
# Simulate the existing "poll failed, reconnecting" branch: _poll_once
|
||||
# fails once (triggering the reconnect/backoff path), then succeeds.
|
||||
# No fresh notifies are supplied for the immediate resubscribe attempt
|
||||
# this now triggers, so its grace period (shortened for tests by the
|
||||
# `_fast_coordinator_timers` autouse fixture — see conftest.py) times
|
||||
# out and mode stays 'poll' — this test only asserts the tear-down half of
|
||||
# the fix; test_reconnect_from_observe_mode_resubscribes_immediately
|
||||
# covers the successful-immediate-resubscribe half.
|
||||
with (
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
@@ -277,6 +325,332 @@ async def test_reconnect_while_observe_mode_downgrades_to_poll(
|
||||
assert coordinator._observe.mode == MODE_POLL
|
||||
|
||||
|
||||
async def test_poll_timeout_skips_reconnect_when_push_is_healthy(
|
||||
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
|
||||
) -> None:
|
||||
"""A poll (summary GET) TimeoutError with a recent OBSERVE notify must
|
||||
not reconnect or downgrade at all — the notify proves the DTLS session
|
||||
and its subscriptions are still alive, so the GET failure is just a
|
||||
choked blockwise transfer on a slow device, not a dead channel. This
|
||||
is the fix for a flaky device (e.g. a slow dishwasher) repeatedly
|
||||
tearing down a healthy observe session on nothing but a poll hiccup."""
|
||||
fake = mock_coordinator_observe_session
|
||||
await hass.config_entries.async_setup(mock_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
|
||||
|
||||
def _notify_during_grace_period():
|
||||
time.sleep(0.005)
|
||||
for href in hrefs:
|
||||
fake.on_notification(href, cbor2.dumps({'notified': True}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
entered = await hass.async_add_executor_job(
|
||||
coordinator._observe.try_enter_observe_mode,
|
||||
fake, hrefs, 0.02, 0.8,
|
||||
)
|
||||
notifier.join()
|
||||
assert entered is True
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
with (
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
side_effect=TimeoutError('GET /device/0 block 11 timeout'),
|
||||
),
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._close_session',
|
||||
) as mock_close,
|
||||
):
|
||||
await coordinator.async_request_refresh()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
mock_close.assert_not_called()
|
||||
|
||||
|
||||
async def test_poll_timeout_reconnects_after_consecutive_limit_even_with_push(
|
||||
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session, fridge_resources
|
||||
) -> None:
|
||||
"""Push health only matters at the moment of the failing poll — if
|
||||
notifies later go stale too (not supplied here, so recently_notified()
|
||||
becomes False once the window elapses) a run of consecutive timeouts
|
||||
must still escalate to a reconnect, so a genuinely dead channel isn't
|
||||
stuck forever just because it looked healthy once."""
|
||||
fake = mock_coordinator_observe_session
|
||||
await hass.config_entries.async_setup(mock_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
|
||||
|
||||
def _notify_during_grace_period():
|
||||
time.sleep(0.005)
|
||||
for href in hrefs:
|
||||
fake.on_notification(href, cbor2.dumps({'notified': True}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
entered = await hass.async_add_executor_job(
|
||||
coordinator._observe.try_enter_observe_mode,
|
||||
fake, hrefs, 0.02, 0.8,
|
||||
)
|
||||
notifier.join()
|
||||
assert entered is True
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
# No notify is recent any more, so every timeout below counts toward
|
||||
# the consecutive-timeout limit instead of being deferred.
|
||||
coordinator._observe._last_notify_ts -= PUSH_HEALTH_WINDOW_S + 1
|
||||
|
||||
# Call _async_update_data directly rather than via
|
||||
# async_request_refresh() — the coordinator's built-in debouncer
|
||||
# (REQUEST_REFRESH_DEFAULT_COOLDOWN, real wall-clock seconds) would
|
||||
# otherwise coalesce these rapid-fire calls into far fewer than the
|
||||
# consecutive-timeout count this test needs to exercise.
|
||||
with patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
side_effect=TimeoutError('GET /device/0 block 11 timeout'),
|
||||
):
|
||||
for _ in range(coordinator._POLL_TIMEOUT_LIMIT - 1):
|
||||
await coordinator._async_update_data()
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
# The final consecutive timeout crosses the limit and triggers the
|
||||
# existing reconnect path, which then succeeds and downgrades.
|
||||
with (
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
side_effect=[TimeoutError('GET /device/0 block 11 timeout'), fridge_resources],
|
||||
),
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.asyncio.sleep',
|
||||
new=AsyncMock(),
|
||||
),
|
||||
):
|
||||
await coordinator._async_update_data()
|
||||
|
||||
assert coordinator.observe_mode == MODE_POLL
|
||||
|
||||
|
||||
async def test_poll_timeout_counter_resets_when_push_is_healthy_again(
|
||||
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
|
||||
) -> None:
|
||||
"""Timeouts accrued during a quiet stretch must not survive into a
|
||||
later burst of healthy push — otherwise an intermittently-active
|
||||
device could reconnect on old timeouts even though push just proved
|
||||
the session alive. The counter means "consecutive timeouts with no
|
||||
push activity to vouch for the session," not just "consecutive
|
||||
timeouts count.\""""
|
||||
fake = mock_coordinator_observe_session
|
||||
await hass.config_entries.async_setup(mock_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
|
||||
|
||||
def _notify_during_grace_period():
|
||||
time.sleep(0.005)
|
||||
for href in hrefs:
|
||||
fake.on_notification(href, cbor2.dumps({'notified': True}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
entered = await hass.async_add_executor_job(
|
||||
coordinator._observe.try_enter_observe_mode,
|
||||
fake, hrefs, 0.02, 0.8,
|
||||
)
|
||||
notifier.join()
|
||||
assert entered is True
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
# Age the notify out so timeouts accrue toward the limit.
|
||||
coordinator._observe._last_notify_ts -= PUSH_HEALTH_WINDOW_S + 1
|
||||
with patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
side_effect=TimeoutError('GET /device/0 block 11 timeout'),
|
||||
):
|
||||
for _ in range(coordinator._POLL_TIMEOUT_LIMIT - 1):
|
||||
await coordinator._async_update_data()
|
||||
assert coordinator._consecutive_poll_timeouts == coordinator._POLL_TIMEOUT_LIMIT - 1
|
||||
|
||||
# A fresh notify proves push is healthy again — the next timeout must
|
||||
# not add to the pre-existing count, and must not reconnect.
|
||||
fake.on_notification(hrefs[0], cbor2.dumps({'notified': True}))
|
||||
with patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
side_effect=TimeoutError('GET /device/0 block 11 timeout'),
|
||||
):
|
||||
await coordinator._async_update_data()
|
||||
|
||||
assert coordinator._consecutive_poll_timeouts == 0
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
|
||||
async def test_reconnect_from_observe_mode_resubscribes_immediately(
|
||||
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session, fridge_resources
|
||||
) -> None:
|
||||
"""A reconnect just proved the session is healthy, so the coordinator
|
||||
must attempt resubscribe in the same update cycle rather than waiting
|
||||
for the 600s poll-mode retry timer (_RECOVERY_RETRY_S) — that timer
|
||||
exists to throttle devices that never had observe working at all, not
|
||||
ones that just proved their session works."""
|
||||
fake = mock_coordinator_observe_session
|
||||
await hass.config_entries.async_setup(mock_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
|
||||
|
||||
def _notify(delay: float = 0.005) -> threading.Thread:
|
||||
def _run():
|
||||
time.sleep(delay)
|
||||
for href in hrefs:
|
||||
fake.on_notification(href, cbor2.dumps({'notified': True}))
|
||||
t = threading.Thread(target=_run, daemon=True)
|
||||
t.start()
|
||||
return t
|
||||
|
||||
notifier = _notify()
|
||||
entered = await hass.async_add_executor_job(
|
||||
coordinator._observe.try_enter_observe_mode,
|
||||
fake, hrefs, 0.02, 0.8,
|
||||
)
|
||||
notifier.join()
|
||||
assert entered is True
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
# Age out the notify so recently_notified() is False and the poll
|
||||
# failure below actually triggers a reconnect (see
|
||||
# test_poll_failure_skips_reconnect_when_push_is_healthy for the
|
||||
# healthy-push case, which now skips reconnecting entirely).
|
||||
coordinator._observe._last_notify_ts -= PUSH_HEALTH_WINDOW_S + 1
|
||||
|
||||
# If a stale retry timer (rather than an immediate resubscribe) were
|
||||
# driving recovery, mode would still be 'poll' right after this single
|
||||
# refresh call — the 600s gate wouldn't have elapsed yet.
|
||||
with (
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
side_effect=[RuntimeError('connection lost'), fridge_resources],
|
||||
),
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.asyncio.sleep',
|
||||
new=AsyncMock(),
|
||||
),
|
||||
):
|
||||
notifier = _notify()
|
||||
await coordinator.async_request_refresh()
|
||||
await hass.async_block_till_done()
|
||||
notifier.join()
|
||||
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
|
||||
async def test_sweep_mismatch_never_downgrades_a_live_observe_session(
|
||||
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
|
||||
) -> None:
|
||||
"""A sweep/cache mismatch is diagnostic-only (see test_observe.py) —
|
||||
it must never tear down a still-live OBSERVE session. The sweep
|
||||
already re-applies the authoritative state to the cache regardless of
|
||||
mode, so a downgrade would only throw away working push coverage on
|
||||
every other subscribed href without fixing anything."""
|
||||
fake = mock_coordinator_observe_session
|
||||
await hass.config_entries.async_setup(mock_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
|
||||
assert len(hrefs) >= 2
|
||||
|
||||
def _notify(delay: float = 0.005) -> threading.Thread:
|
||||
def _run():
|
||||
time.sleep(delay)
|
||||
for href in hrefs:
|
||||
fake.on_notification(href, cbor2.dumps({'notified': True}))
|
||||
t = threading.Thread(target=_run, daemon=True)
|
||||
t.start()
|
||||
return t
|
||||
|
||||
notifier = _notify()
|
||||
entered = await hass.async_add_executor_job(
|
||||
coordinator._observe.try_enter_observe_mode,
|
||||
fake, hrefs, 0.02, 0.8,
|
||||
)
|
||||
notifier.join()
|
||||
assert entered is True
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
# A sweep result disagreeing with the cache on every subscribed href —
|
||||
# previously treated as a device-wide miss and downgraded.
|
||||
stale_sweep = {href: {'notified': False} for href in hrefs}
|
||||
|
||||
with patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
return_value=stale_sweep,
|
||||
):
|
||||
await coordinator.async_request_refresh()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
# The mismatch is diagnostic-only, but the sweep result still won —
|
||||
# the cache reflects the latest authoritative state either way.
|
||||
assert coordinator.last_resources[hrefs[0]]['notified'] is False
|
||||
|
||||
|
||||
async def test_sweep_mismatch_forces_subpolls_on_a_live_observe_session(
|
||||
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
|
||||
) -> None:
|
||||
"""A sweep/cache mismatch on a live observe session must not tear
|
||||
anything down, but it should trigger extra hot/warm subpolls this
|
||||
cycle — the bounded fallback for a channel gone silent without a
|
||||
reconnect (e.g. lost internet on an otherwise-live local session)."""
|
||||
fake = mock_coordinator_observe_session
|
||||
await hass.config_entries.async_setup(mock_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
|
||||
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
|
||||
assert len(hrefs) >= 2
|
||||
|
||||
def _notify(delay: float = 0.005) -> threading.Thread:
|
||||
def _run():
|
||||
time.sleep(delay)
|
||||
for href in hrefs:
|
||||
fake.on_notification(href, cbor2.dumps({'notified': True}))
|
||||
t = threading.Thread(target=_run, daemon=True)
|
||||
t.start()
|
||||
return t
|
||||
|
||||
notifier = _notify()
|
||||
entered = await hass.async_add_executor_job(
|
||||
coordinator._observe.try_enter_observe_mode,
|
||||
fake, hrefs, 0.02, 0.8,
|
||||
)
|
||||
notifier.join()
|
||||
assert entered is True
|
||||
assert coordinator.observe_mode == MODE_OBSERVE
|
||||
|
||||
stale_sweep = {href: {'notified': False} for href in hrefs}
|
||||
|
||||
with (
|
||||
patch(
|
||||
'custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once',
|
||||
return_value=stale_sweep,
|
||||
),
|
||||
patch.object(
|
||||
LocalThingsCoordinator, '_run_subpolls', new_callable=AsyncMock,
|
||||
) as mock_subpolls,
|
||||
):
|
||||
await coordinator.async_request_refresh()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
mock_subpolls.assert_called_once_with(force=True)
|
||||
|
||||
|
||||
async def test_write_marks_href_pending_before_post(
|
||||
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
|
||||
) -> None:
|
||||
|
||||
@@ -9,7 +9,9 @@ import pytest
|
||||
|
||||
from smartthings_local.ocf.state_cache import StateCache
|
||||
|
||||
from custom_components.localthings.observe import ObserveManager, MODE_POLL
|
||||
from custom_components.localthings.observe import (
|
||||
ObserveManager, MODE_POLL, _rep_diff,
|
||||
)
|
||||
|
||||
|
||||
class _NullDescriptor:
|
||||
@@ -156,6 +158,25 @@ def test_on_notification_ignores_malformed_cbor():
|
||||
assert mgr.cache.get('/oven/vs/0') is None
|
||||
|
||||
|
||||
def test_recently_notified_false_before_any_notify():
|
||||
mgr = _manager()
|
||||
assert mgr.recently_notified() is False
|
||||
|
||||
|
||||
def test_recently_notified_true_just_after_a_notify():
|
||||
mgr = _manager()
|
||||
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}))
|
||||
assert mgr.recently_notified(window_s=0.01) is True
|
||||
time.sleep(0.02)
|
||||
assert mgr.recently_notified(window_s=0.01) is False
|
||||
|
||||
|
||||
def test_try_enter_observe_mode_clears_stale_notifications_on_retry():
|
||||
"""Regression test: verify second call to try_enter_observe_mode() doesn't
|
||||
get polluted by notifications from the first call. This happens in real
|
||||
@@ -200,19 +221,65 @@ def test_try_enter_observe_mode_clears_stale_notifications_on_retry():
|
||||
mgr.close()
|
||||
|
||||
|
||||
def test_check_sweep_for_misses_false_when_not_in_observe_mode():
|
||||
def test_log_sweep_discrepancies_noop_when_not_in_observe_mode(caplog):
|
||||
mgr = _manager()
|
||||
assert mgr.check_sweep_for_misses({'/oven/vs/0': {'a': 2}}) is False
|
||||
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_check_sweep_for_misses_detects_mismatch():
|
||||
def test_log_sweep_discrepancies_never_changes_mode():
|
||||
"""A sweep/cache mismatch is diagnostic-only — a still-live OBSERVE
|
||||
session is never torn down over a data-drift inference. The 30s sweep
|
||||
already re-applies the authoritative state to the cache regardless of
|
||||
mode, so there's nothing a downgrade would fix; it would only throw
|
||||
away working push coverage on every other subscribed href."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
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}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
|
||||
try:
|
||||
mgr.try_enter_observe_mode(session, hrefs, grace_period_s=0.02)
|
||||
notifier.join()
|
||||
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}})
|
||||
|
||||
assert mgr.mode == 'observe'
|
||||
finally:
|
||||
mgr.close()
|
||||
|
||||
|
||||
def test_rep_diff_reports_only_shared_fields_that_differ():
|
||||
"""Fields present on only one side (a shape difference, e.g. batch
|
||||
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})
|
||||
|
||||
assert diff == {'b': (2, 5)}
|
||||
|
||||
|
||||
def test_log_sweep_discrepancies_ignores_shape_only_differences(caplog):
|
||||
"""A sweep rep missing/adding fields the cache doesn't have (or vice
|
||||
versa) is a representation-shape difference, not a missed change —
|
||||
must not be logged as a discrepancy."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
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, 'rt': ['x'], 'if': ['y']}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
@@ -222,15 +289,48 @@ def test_check_sweep_for_misses_detects_mismatch():
|
||||
notifier.join()
|
||||
assert mgr.mode == 'observe'
|
||||
|
||||
# Sweep sees a value the cache never got via notify -> observe missed it.
|
||||
missed = mgr.check_sweep_for_misses({href: {'a': 2}})
|
||||
# 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}})
|
||||
finally:
|
||||
mgr.close()
|
||||
|
||||
assert missed is True
|
||||
assert 'observe missed a change' not in caplog.text
|
||||
|
||||
|
||||
def test_log_sweep_discrepancies_includes_the_diff(caplog):
|
||||
"""The log line must include what actually differed, not just that it
|
||||
did."""
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
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}))
|
||||
|
||||
notifier = threading.Thread(target=_notify_during_grace_period, daemon=True)
|
||||
notifier.start()
|
||||
|
||||
try:
|
||||
mgr.try_enter_observe_mode(session, hrefs, grace_period_s=0.02)
|
||||
notifier.join()
|
||||
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}}
|
||||
)
|
||||
|
||||
assert "{'b': (2, 5)}" in caplog.text
|
||||
assert mgr.mode == 'observe'
|
||||
finally:
|
||||
mgr.close()
|
||||
|
||||
|
||||
def test_check_sweep_for_misses_ignores_href_during_settle_window():
|
||||
def test_log_sweep_discrepancies_ignores_href_during_settle_window(caplog):
|
||||
mgr = _manager()
|
||||
session = _FakeSession()
|
||||
href = '/oven/vs/0'
|
||||
@@ -238,9 +338,10 @@ def test_check_sweep_for_misses_ignores_href_during_settle_window():
|
||||
mgr.try_enter_observe_mode(session, [href], grace_period_s=0.01)
|
||||
mgr.mark_write_pending(href, settle_s=5.0)
|
||||
|
||||
missed = mgr.check_sweep_for_misses({href: {'a': 2}})
|
||||
with caplog.at_level('DEBUG'):
|
||||
mgr.log_sweep_discrepancies({href: {'a': 2}})
|
||||
|
||||
assert missed is False
|
||||
assert 'observe missed a change' not in caplog.text
|
||||
|
||||
|
||||
def test_downgrade_to_poll_moves_subscribed_to_fallback():
|
||||
|
||||
@@ -6,7 +6,6 @@ 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'
|
||||
assert c.active_when is None
|
||||
assert len(c.entities) == 1
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import pytest
|
||||
from tests.conftest import _load_device
|
||||
from custom_components.localthings.registry.by_type import for_device, _type_key
|
||||
from custom_components.localthings.registry.discovery import discover
|
||||
from custom_components.localthings.registry.adapter import flatten, is_active
|
||||
from custom_components.localthings.registry.adapter import flatten
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name,expected_type_key', [
|
||||
@@ -24,5 +24,3 @@ def test_full_pipeline_v2(name, expected_type_key):
|
||||
|
||||
state = flatten(bound, resources)
|
||||
assert state
|
||||
# is_active returns bool; just verify it runs without error
|
||||
is_active(bound, resources)
|
||||
@@ -6,8 +6,3 @@ def test_machine_state_maps_samsung_to_ocf():
|
||||
assert ms.value_fn('Run') == 'active'
|
||||
assert ms.value_fn('Pause') == 'pause'
|
||||
assert ms.value_fn('Ready') == 'idle'
|
||||
|
||||
|
||||
def test_active_when_true_only_when_running():
|
||||
assert OPERATIONAL_STATE.active_when({'x.com.samsung.da.state': 'Run'}) is True
|
||||
assert OPERATIONAL_STATE.active_when({'x.com.samsung.da.state': 'Ready'}) is False
|
||||
Reference in new issue
Block a user