"""Start/stop through the safety layer: identity, state, dry run, audit, read-back, no retry.""" from __future__ import annotations import os import sys import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import micromate.protocol as mm_proto # noqa: E402 from device_access_fakes import FakeMicromateClient # noqa: E402 from sfm.device_access.access import DeviceAccess # noqa: E402 from sfm.device_access.errors import ( # noqa: E402 CallHomeInProgress, NotSupported, WrongUnit, ) from sfm.device_access.models import UnitAddress # noqa: E402 ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None) class Audit: def __init__(self): self.rows = {} def begin(self, **f): cid = f"c{len(self.rows) + 1}" self.rows[cid] = dict(f, outcome="pending") return cid def finish(self, cid, **f): self.rows[cid].update(f) def access(fake, audit="default"): return DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False, audit=Audit() if audit == "default" else audit, sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0) def test_a_dry_run_returns_the_exact_frames_and_sends_nothing(): fake = FakeMicromateClient(run_states=[0x00]) da = access(fake) r = da.start_monitoring(ADDR, "UM20147", dry_run=True) assert (r.dry_run, r.sent, r.outcome, r.state_before) == (True, False, "dry_run", "idle") assert r.plan["steps"][0]["frame"] == "41021010009600ffff00000000000000000000a403" assert r.plan["sends_nothing"] is True assert fake.executed == [] and da._audit.rows == {} def test_start_sends_once_and_verifies_by_reading_back(): fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02]) da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert (r.sent, r.outcome, r.verified, r.state_after) == (True, "sent", "ok", "monitoring") assert len(fake.executed) == 1 row = da._audit.rows[r.audit_id] assert (row["outcome"], row["verified"], row["action"]) == ("sent", "ok", "start monitoring") assert r.detail["states_seen"][-1] == "monitoring" assert r.plan["sends_nothing"] is False assert row["request"]["plan"]["sends_nothing"] is False def test_already_in_state_is_skipped_and_audited_as_skipped(): fake = FakeMicromateClient(run_states=[0x02]) da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert (r.sent, r.outcome) == (False, "skipped") and fake.executed == [] assert da._audit.rows[r.audit_id]["outcome"] == "skipped" def test_even_if_already_sends_anyway(): fake = FakeMicromateClient(run_states=[0x02]) r = access(fake).start_monitoring(ADDR, "UM20147", even_if_already=True) assert r.sent and len(fake.executed) == 1 def test_a_unit_calling_home_is_refused_and_nothing_is_sent(): fake = FakeMicromateClient(run_states=[0x03]) da = access(fake) with pytest.raises(CallHomeInProgress): da.stop_monitoring(ADDR, "UM20147") assert fake.executed == [] assert fake.is_open() is False # the line was released for THOR assert da.held_serial(ADDR) is None # and the session dropped def test_a_different_unit_on_the_fresh_serial_read_is_refused_before_writing(): fake = FakeMicromateClient(serial_reported="UM12947") da = access(fake) with pytest.raises(WrongUnit): da.start_monitoring(ADDR, "UM20147") assert fake.executed == [] assert fake.is_open() is False assert da.held_serial(ADDR) is None def test_a_live_change_without_an_audit_sink_is_refused(): fake = FakeMicromateClient() with pytest.raises(NotSupported, match="audit"): access(fake, audit=None).start_monitoring(ADDR, "UM20147") assert fake.executed == [] def test_a_clean_ack_but_no_state_change_is_a_failed_change(): fake = FakeMicromateClient(run_states=[0x00]) # never leaves idle da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert (r.outcome, r.verified, r.state_after) == ("failed", "mismatch", "idle") assert len(r.detail["states_seen"]) == 4 # 6 s window / 2 s + the first read assert da._audit.rows[r.audit_id]["verified"] == "mismatch" def test_a_lost_ack_is_never_retried(): fake = FakeMicromateClient(run_states=[0x00, 0x02], execute_error=mm_proto.TimeoutError("no ack")) da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert len(fake.executed) == 1 assert (r.outcome, r.state_after) == ("failed", "monitoring") assert "no ack" in r.detail["error"] assert da._audit.rows[r.audit_id]["outcome"] == "failed" def test_a_change_on_a_dropped_held_line_is_not_retried(): fake = FakeMicromateClient(run_states=[0x00]) da = access(fake) da.status(ADDR, "UM20147") # hold the line fake.fail = [mm_proto.TimeoutError("peer gone")] # next call fails with pytest.raises(Exception): da.start_monitoring(ADDR, "UM20147") assert fake.executed == [] # never reached the write, never re-tried def test_a_read_back_that_fails_still_finishes_the_audit_row(): fake = FakeMicromateClient(run_states=[0x00]) da = access(fake) orig = fake.read_run_state calls = [] def flaky(): calls.append(1) if len(calls) == 2: # the first read-back raise mm_proto.TimeoutError("dropped") return orig() fake.read_run_state = flaky with pytest.raises(Exception): da.start_monitoring(ADDR, "UM20147") (row,) = da._audit.rows.values() assert len(fake.executed) == 1 assert (row["outcome"], row["verified"]) == ("failed", "not_checked")