From 32967a1c58287024b086700b6ecba39e263cadfa Mon Sep 17 00:00:00 2001 From: MFlys Date: Thu, 3 Dec 2026 01:54:27 +0300 Subject: [PATCH] Test real Cosa coordinator freshness with virtual replay time --- examples/diff/cosa/README.md | 11 ++ .../diff/cosa/test_coordinator_scenario.py | 102 ++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 examples/diff/cosa/test_coordinator_scenario.py diff --git a/examples/diff/cosa/README.md b/examples/diff/cosa/README.md index 9edeb3b..f284dab 100644 --- a/examples/diff/cosa/README.md +++ b/examples/diff/cosa/README.md @@ -98,3 +98,14 @@ Cosa's actual transport, coordinator cache or received_at clock. The real parser's wall-clock timestamp is not asserted. No hardware, HTTP or credentials are used. The existing comparison job discovers these tests automatically. The released Scenario Preview P1 archive is unchanged. + +The coordinator scenario additionally invokes the actual `CosaCoordinator` +with an in-memory API boundary. Successful responses are projected and parsed, +then the snapshot's `received_at` is set from the replay clock. Failed responses +raise `CosaTransientError`. The real coordinator determines availability and +retains the last accepted snapshot until its default 120-second freshness +boundary. Six observations test initial failure, first success, freshness at +119999 ms, expiry at 120000 ms, prolonged outage and recovery. The test also +checks failure counters and that failed polls never advance last success. +Incorrect expiry expectations are a regression failure. No real HTTP, polling +scheduler, HA entity lifecycle or wall-clock simulation is involved. diff --git a/examples/diff/cosa/test_coordinator_scenario.py b/examples/diff/cosa/test_coordinator_scenario.py new file mode 100644 index 0000000..aaa2d8f --- /dev/null +++ b/examples/diff/cosa/test_coordinator_scenario.py @@ -0,0 +1,102 @@ +"""Exercise Cosa's actual freshness boundary with deterministic replay.""" +import asyncio +from copy import deepcopy +from dataclasses import replace +import json +from pathlib import Path +import unittest + +from custom_components.cosa_v2 import api +from custom_components.cosa_v2.coordinator import CosaCoordinator +from examples.scenario.offline_regression import REQUEST, run_document +from iot_fixturekit import FixtureError, build_fixture +from iot_fixturekit.audit import audit_json + +ENDPOINT = 'endpoint-test-1' + + +class ReplayClient: + """In-memory API boundary, not an HTTP client or coordinator substitute.""" + def __init__(self, policy, baseline): + self.policy = policy + self.baseline = baseline + self.session = None + + async def async_get_endpoint(self, endpoint_id): + if endpoint_id != ENDPOINT: + raise FixtureError('unexpected endpoint') + frame = self.session.request(REQUEST) + if frame.status == 503: + raise api.CosaTransientError('synthetic outage') + if frame.status != 200: + raise FixtureError('unexpected response') + raw = deepcopy(self.baseline) + raw['endpoint']['temperature'] = json.loads(frame.body)['temperature'] + fixture = build_fixture(raw, self.policy, profile='cosa') + if audit_json(fixture): + raise FixtureError('unexpected fixture finding') + snapshot = api.parse_endpoint(fixture['data'], endpoint_id) + # Inject only the snapshot time at the boundary; leave the real + # coordinator freshness logic and the host clock untouched. + return replace(snapshot, received_at=self.session.monotonic_ms() / 1000) + + +class CoordinatorScenarioTests(unittest.TestCase): + def setUp(self): + root = Path(api.__file__).resolve().parents[2] + policy = json.loads((root / 'tests/fixture_sources/cosa-endpoint-policy.json').read_text()) + baseline = json.loads((root / 'tests/fixtures/cosa-endpoint.json').read_text())['data'] + self.client = ReplayClient(policy, baseline) + self.coordinator = CosaCoordinator(None, self.client, ENDPOINT) + self.trace = [] + self.document = {'schema_version': 1, 'steps': [ + {'response': {'status': 503}, 'expected': {'status': 'unavailable'}}, + {'advance_ms': 1000, 'response': {'status': 200, 'temperature': 21.2}, + 'expected': {'status': 'available', 'temperature': 21.2}}, + {'advance_ms': 119999, 'response': {'status': 503}, + 'expected': {'status': 'available', 'temperature': 21.2}}, + {'advance_ms': 1, 'response': {'status': 503}, + 'expected': {'status': 'unavailable'}}, + {'advance_ms': 1000, 'response': {'status': 503}, + 'expected': {'status': 'unavailable'}}, + {'advance_ms': 1000, 'response': {'status': 200, 'temperature': 23}, + 'expected': {'status': 'available', 'temperature': 23.0}}, + ]} + + def observe(self, session): + self.client.session = session + coordinator = self.coordinator + try: + asyncio.run(coordinator.async_refresh_snapshot()) + except api.CosaTransientError: + pass + now = session.monotonic_ms() / 1000 + self.trace.append((session.monotonic_ms(), coordinator.last_success, + coordinator.consecutive_failures, coordinator.last_error)) + if not coordinator.is_fresh(now): + return {'status': 'unavailable'} + return {'status': 'available', 'temperature': coordinator.data.room_temperature} + + def test_real_freshness_boundary_and_recovery(self): + self.assertEqual(run_document(self.document, self.observe), { + 'kind': 'custom-climate', 'status': 'pass', 'observations': 6, + 'differences': {}, 'virtual_elapsed_ms': 123000}) + self.assertEqual(self.trace, [ + (0, None, 1, 'CosaTransientError'), (1000, 1.0, 0, None), + (120999, 1.0, 1, 'CosaTransientError'), + (121000, 1.0, 2, 'CosaTransientError'), + (122000, 1.0, 3, 'CosaTransientError'), (123000, 123.0, 0, None), + ]) + self.assertEqual(self.coordinator.data.room_temperature, 23.0) + + def test_incorrect_boundary_expectation_fails(self): + self.document['steps'][3]['expected'] = {'status': 'available', 'temperature': 21.2} + self.assertEqual(run_document(self.document, self.observe)['status'], 'fail') + + def test_failed_poll_does_not_advance_success_time(self): + self.document['steps'] = self.document['steps'][:5] + self.assertEqual(run_document(self.document, self.observe)['status'], 'pass') + self.assertEqual(self.coordinator.data.received_at, 1.0) + self.assertEqual(self.coordinator.last_success, 1.0) + self.assertFalse(self.coordinator.is_fresh(122.0)) + self.assertEqual(self.coordinator.consecutive_failures, 3)