"""Handlers called directly -- every parameter passed explicitly, because FastAPI Query() defaults are FieldInfo objects, not values.""" from __future__ import annotations import json import os import sys import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from fastapi import HTTPException # noqa: E402 import sfm.server as srv # noqa: E402 from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402 from sfm.device_access.access import DeviceAccess # noqa: E402 from sfm.device_access.errors import ( # noqa: E402 BadRequest, CallHomeInProgress, ConnectFailed, MalformedReply, NoAnswer, NotSupported, UnitBusy, WrongUnit, ) TCP = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034) @pytest.fixture def da(monkeypatch): s3q = [FakeMiniMateClient() for _ in range(5)] s4q = [FakeMicromateClient() for _ in range(5)] access = DeviceAccess(s3_client_factory=lambda a, **kw: s3q.pop(0), s4_client_factory=lambda a, **kw: s4q.pop(0), start_reaper=False) monkeypatch.setattr(srv, "_device_access_instance", access) return access def test_info_with_a_serial_returns_the_shared_model(da): out = srv.device_info(force=False, serial="UM20147", **TCP) assert out["series"] == 4 and out["serial"] == "UM20147" assert set(out) == {"serial", "series", "model", "firmware", "monitoring", "active_setup", "detail"} def test_connect_passes_the_serial_through(da): out = srv.device_connect(serial="BE18193", **TCP) assert out["series"] == 3 def test_status_and_settings_with_a_serial(da): assert srv.device_monitor_status(force=False, serial="UM20147", **TCP)["event_count"] == 5 assert srv.device_settings(serial="UM20147", **TCP)["record_mode"] == "Histogram Combo" def test_status_run_state_is_opt_in(da): # called directly, a Query default is truthy: pass it as FastAPI would assert "run_state" not in srv.device_monitor_status(force=False, serial="UM20147", run_state=False, **TCP)["detail"] out = srv.device_monitor_status(force=False, serial="UM20147", run_state=True, **TCP) assert out["detail"]["run_state"] == {"code": 0, "name": "idle"} def test_hangup(da): srv.device_monitor_status(force=False, serial="UM20147", **TCP) assert srv.device_hangup(**TCP) == {"hung_up": True} @pytest.mark.parametrize( "exc, status", [(BadRequest("x"), 422), (NotSupported("x"), 501), (WrongUnit("x"), 409), (UnitBusy("x"), 423), (ConnectFailed("x"), 503), (CallHomeInProgress("x"), 503), (NoAnswer("x"), 504), (MalformedReply("x"), 502)], ) def test_typed_errors_become_their_http_status(monkeypatch, exc, status): class Raising: def identify(self, address, serial): raise exc monkeypatch.setattr(srv, "_device_access_instance", Raising()) with pytest.raises(HTTPException) as ei: srv.device_info(force=False, serial="UM20147", **TCP) assert ei.value.status_code == status def test_a_missing_address_is_a_422(da): with pytest.raises(HTTPException) as ei: srv.device_settings(serial="UM20147", port=None, baud=None, host=None, tcp_port=9034) assert ei.value.status_code == 422 def test_without_a_serial_the_legacy_path_runs_unchanged(monkeypatch): """No serial: today's Series-3 code path, today's response shape. DeviceAccess must not be touched.""" class Untouchable: def __getattr__(self, name): raise AssertionError("DeviceAccess used on the legacy path") class Cache: def get_device_info(self, key): return {"serial": "BE18193", "firmware_version": "S338.17"} monkeypatch.setattr(srv, "_device_access_instance", Untouchable()) monkeypatch.setattr(srv, "get_cache", lambda: Cache()) out = srv.device_info(force=False, serial=None, **TCP) assert out == {"serial": "BE18193", "firmware_version": "S338.17", "_cached": True} # ── the /device/* guard ─────────────────────────────────────────────────────── from sfm.device_access.models import UnitAddress # noqa: E402 ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None) Q_TCP = {"host": "10.0.0.5", "tcp_port": "9034"} @pytest.mark.parametrize("path", ["/device/events/erase", "/device/config"]) def test_guard_refuses_a_um_serial_on_unsupported_routes_with_501(path): out = srv._device_guard(path, {"serial": "um20147", **Q_TCP}) assert out is not None and out[0] == 501 and path in out[1] def test_guard_lets_a_series3_serial_through_on_legacy_routes(): assert srv._device_guard("/device/events/erase", {"serial": "BE18193", **Q_TCP}) is None @pytest.mark.parametrize("path", ["/device/info", "/device/connect", "/device/monitor/status", "/device/settings", "/device/events", "/device/events/download", "/device/monitor/start", "/device/monitor/stop", "/device/hangup"]) def test_guard_allows_um_serial_on_serial_aware_routes_and_hangup(path): assert srv._device_guard(path, {"serial": "UM20147", **Q_TCP}) is None def test_guard_refuses_serialless_requests_at_a_held_address_with_409(da): da.status(ADDR, "UM20147") out = srv._device_guard("/device/monitor/stop", dict(Q_TCP)) assert out is not None and out[0] == 409 assert "UM20147" in out[1] and "tcp:10.0.0.5:9034" in out[1] and "hangup" in out[1] def test_guard_allows_serialless_requests_at_an_unheld_address(da): assert srv._device_guard("/device/monitor/stop", dict(Q_TCP)) is None assert srv._device_guard("/device/monitor/stop", {"host": "10.9.9.9"}) is None def test_guard_ignores_non_device_paths(da): assert srv._device_guard("/db/events", {"serial": "UM20147", **Q_TCP}) is None def test_guard_allows_an_unbuildable_address_through(da): assert srv._device_guard("/device/monitor/stop", {}) is None @pytest.mark.parametrize("serial", ["BE18193", "BA1", "nonsense"]) def test_guard_refuses_any_non_um_serial_on_a_legacy_route_at_a_held_address(da, serial): # FastAPI drops the undeclared serial, so the legacy Series-3 handler would run # at the held Series-4 address -- the same hole as a serial-less request. da.status(ADDR, "UM20147") out = srv._device_guard("/device/events/erase", {"serial": serial, **Q_TCP}) assert out is not None and out[0] == 409 and "UM20147" in out[1] def test_guard_leaves_serial_aware_routes_to_device_access_at_a_held_address(da): # DeviceAccess routes by series and refuses a Series-3 serial beside a held line itself. da.status(ADDR, "UM20147") assert srv._device_guard("/device/info", {"serial": "BE18193", **Q_TCP}) is None def test_guard_ignores_an_unparseable_baud_when_checking_for_a_held_line(da): # baud is not part of the address key; pydantic would coerce "38400.0" and run the handler. da.status(ADDR, "UM20147") out = srv._device_guard("/device/monitor/stop", {"baud": "38400.0", **Q_TCP}) assert out is not None and out[0] == 409 # ── events ──────────────────────────────────────────────────────────────────── from sfm.database import SeismoDb # noqa: E402 from sfm.waveform_store import WaveformStore # noqa: E402 W_ID = "UM20147:055d4a81:20250531135901" @pytest.fixture def sdm(tmp_path, monkeypatch): db = SeismoDb(tmp_path / "seismo.db") store = WaveformStore(tmp_path / "waveforms") monkeypatch.setattr(srv, "_get_db", lambda: db) monkeypatch.setattr(srv, "_get_store", lambda: store) return store, db EV = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034) @pytest.mark.parametrize("serial,series", [("UM20147", 4), ("BE18193", 3)]) def test_events_with_a_serial_return_the_shared_list(da, serial, series): out = srv.device_events(debug=False, force=False, serial=serial, **EV) assert (out["serial"], out["series"], len(out["events"])) == (serial, series, 2) assert set(out["events"][0]) == {"event_id", "serial", "series", "index", "timestamp", "record_type", "peak_vector_sum_ips", "peaks_ips", "filename", "detail"} def test_events_without_a_serial_run_the_legacy_path(monkeypatch): class Legacy(Exception): pass def untouchable(): raise AssertionError("DeviceAccess must not be used without a serial") def legacy_cache(): raise Legacy() monkeypatch.setattr(srv, "_device_access", untouchable) monkeypatch.setattr(srv, "get_cache", legacy_cache) with pytest.raises(Legacy): srv.device_events(debug=False, force=False, serial=None, **EV) def test_download_stores_the_event_and_says_where(da, sdm): out = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) assert out["inserted"] is True and out["verified"] is True assert out["stored_filename"] == "UM20147_20250531135901.IDFW" _store, db = sdm assert db.get_event(out["db_event_id"])["serial"] == "UM20147" def test_downloading_it_again_returns_the_stored_row_rather_than_rewriting_it(da, sdm): first = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) again = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) assert again["inserted"] is False and again["db_event_id"] == first["db_event_id"] assert again["detail"]["already_stored"] is True @pytest.mark.parametrize("event_id,status", [ ("UM12947:055d4a81:20250531135901", 422), # another unit's event ("garbage", 422), ("UM20147:055d4a81:20240101000000", 409), # stale: erased since listed ("UM20147:deadbeef:-", 404), ]) def test_download_errors_have_their_statuses(da, sdm, event_id, status): with pytest.raises(HTTPException) as ei: srv.device_events_download(serial="UM20147", event_id=event_id, **EV) assert ei.value.status_code == status assert sdm[1].query_events(serial="UM20147") == [] def test_a_decode_that_disagrees_is_502_and_nothing_is_stored(da, sdm, monkeypatch): from micromate.client import DecodeMismatch def mismatch(*a, **kw): raise DecodeMismatch("decoded PVS differs by +5%") fake = FakeMicromateClient() fake.fetch_event = mismatch monkeypatch.setattr(da, "_s4_factory", lambda a, **kw: fake) with pytest.raises(HTTPException) as ei: srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) assert ei.value.status_code == 502 assert sdm[1].query_events(serial="UM20147") == [] def test_a_store_failure_is_500_and_names_what_was_downloaded(da, sdm, monkeypatch): class BrokenStore: def save_imported_idf(self, *a, **kw): raise OSError("disk full") monkeypatch.setattr(srv, "_get_store", lambda: BrokenStore()) with pytest.raises(HTTPException) as ei: srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) assert ei.value.status_code == 500 assert "UM20147_20250531135901.IDFW" in ei.value.detail and "disk full" in ei.value.detail # ── start / stop monitoring by serial ───────────────────────────────────────── import micromate.protocol as _mm_proto # noqa: E402 from sfm.audit import DbAudit # noqa: E402 CH = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034, serial="UM20147", dry_run=False, even_if_already=False, caller=None) class _Rec: 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 _s4(monkeypatch, fake, audit=None): access = DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False, audit=audit or _Rec(), sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0) monkeypatch.setattr(srv, "_device_access_instance", access) return access def _body(resp): import json return json.loads(resp.body) def test_a_dry_run_is_200_with_the_frame(monkeypatch): fake = FakeMicromateClient(run_states=[0x00]) _s4(monkeypatch, fake) resp = srv.device_monitor_start(**{**CH, "dry_run": True}) assert resp.status_code == 200 body = _body(resp) assert body["outcome"] == "dry_run" and body["plan"]["steps"][0]["frame"].startswith("4102") assert fake.executed == [] def test_a_verified_live_start_is_200(monkeypatch): fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02]) _s4(monkeypatch, fake) resp = srv.device_monitor_start(**CH) assert resp.status_code == 200 and _body(resp)["verified"] == "ok" def test_a_mismatch_is_409_and_keeps_states_seen(monkeypatch): fake = FakeMicromateClient(run_states=[0x00]) _s4(monkeypatch, fake) resp = srv.device_monitor_start(**CH) assert resp.status_code == 409 body = _body(resp) assert body["verified"] == "mismatch" and body["detail"]["states_seen"] def test_a_lost_ack_with_a_good_read_back_is_502(monkeypatch): fake = FakeMicromateClient(run_states=[0x00, 0x02], execute_error=_mm_proto.TimeoutError("no ack")) _s4(monkeypatch, fake) resp = srv.device_monitor_start(**CH) assert resp.status_code == 502 body = _body(resp) assert body["outcome"] == "failed" assert body["verified"] == "not_checked" assert body["sent"] is True assert "no clean ack" in body["detail"]["error"] def test_sent_but_unverified_is_never_a_200(): from sfm.device_access.models import ChangeResult r = ChangeResult(serial="UM20147", series=4, action="start monitoring", dry_run=False, sent=True, outcome="sent", verified="not_checked", state_before="idle", state_after=None, audit_id="c1") assert srv._change_response(lambda: r).status_code == 502 def test_stop_by_serial_works(monkeypatch): fake = FakeMicromateClient(run_states=[0x02, 0x02, 0x00]) _s4(monkeypatch, fake) resp = srv.device_monitor_stop(**CH) assert resp.status_code == 200 and _body(resp)["action"].startswith("stop") @pytest.mark.parametrize("fn", ["device_monitor_start", "device_monitor_stop"]) @pytest.mark.parametrize("exc,status", [(CallHomeInProgress("calling home"), 503), (WrongUnit("other unit"), 409), (NoAnswer("silent"), 504)]) def test_a_device_error_maps_to_its_own_status(monkeypatch, fn, exc, status): class Raises: def start_monitoring(self, *a, **kw): raise exc stop_monitoring = start_monitoring monkeypatch.setattr(srv, "_device_access_instance", Raises()) with pytest.raises(HTTPException) as e: getattr(srv, fn)(**CH) assert e.value.status_code == status def test_a_wrong_unit_is_409(monkeypatch): _s4(monkeypatch, FakeMicromateClient(serial_reported="UM12947")) with pytest.raises(HTTPException) as e: srv.device_monitor_start(**CH) assert e.value.status_code == 409 def test_a_live_change_through_the_real_wiring_records_an_audit_row(tmp_path, monkeypatch): db = SeismoDb(tmp_path / "seismo.db") fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02]) _s4(monkeypatch, fake, audit=DbAudit(lambda: db)) resp = srv.device_monitor_start(**CH) assert resp.status_code == 200 rows = db.query_device_commands() assert len(rows) == 1 and rows[0]["outcome"] == "sent" def test_the_module_instance_is_built_with_an_audit_sink(): assert srv._device_access_instance._audit is not None @pytest.mark.parametrize("fn", ["device_monitor_start", "device_monitor_stop"]) def test_monitor_without_a_serial_runs_the_legacy_path_unchanged(monkeypatch, fn): class Legacy(Exception): pass def untouchable(): raise AssertionError("DeviceAccess must not be used without a serial") def legacy_client(**kw): assert kw["baud"] == 38400 # the default is restored on the legacy path raise Legacy() monkeypatch.setattr(srv, "_device_access", untouchable) monkeypatch.setattr(srv, "_build_client", legacy_client) with pytest.raises(Legacy): getattr(srv, fn)(**{**CH, "serial": None}) def test_a_change_unconfirmed_keeps_its_cause_status_and_names_the_audit_record(monkeypatch): from sfm.device_access.errors import ChangeUnconfirmed class Raises: def start_monitoring(self, *a, **kw): raise ChangeUnconfirmed( "start monitoring was sent and acknowledged, but reading the state back " "failed: silent -- audit record c7", audit_id="c7", sent="acknowledged", http_status=504) monkeypatch.setattr(srv, "_device_access_instance", Raises()) resp = srv.device_monitor_start(**CH) assert resp.status_code == 504 # the cause's status, unchanged body = json.loads(resp.body) assert "audit record c7" in body["detail"] # #10 (2026-11-02): the page tells "may have been sent" from "nothing sent" by # these, not by matching the message. assert (body["sent"], body["audit_id"]) == ("acknowledged", "c7") def test_device_commands_normalises_the_serial(tmp_path, monkeypatch): db = SeismoDb(tmp_path / "seismo.db") db.begin_device_command(serial="UM20147", series=4, address="tcp:10.0.0.5:9034", action="start monitoring", tier="change", request={}, caller="test") monkeypatch.setattr(srv, "_get_db", lambda: db) assert len(srv.db_device_commands(serial=" um20147 ", limit=100)["commands"]) == 1 # ── call-home by serial (phase 4) ───────────────────────────────────────────── from device_access_fakes import um12947_call_home # noqa: E402 CH_STATE = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034, serial="UM20147") def test_call_home_state_route(monkeypatch): _s4(monkeypatch, FakeMicromateClient()) st = srv.device_call_home_state(**CH_STATE) assert (st["series"], st["enabled"], st["dial_string"]) == (4, True, "RADIO RING") def test_enable_route_returns_the_change_result(monkeypatch): _s4(monkeypatch, FakeMicromateClient(call_home=um12947_call_home(False))) resp = srv.device_call_home_enable(**CH) assert resp.status_code == 200 and _body(resp)["action"] == "enable call-home" def test_disable_route_returns_the_change_result(monkeypatch): _s4(monkeypatch, FakeMicromateClient()) resp = srv.device_call_home_disable(**CH) assert resp.status_code == 200 and _body(resp)["state_after"] == "disabled" def _asgi(method, path, query=""): import asyncio msgs = [] async def receive(): return {"type": "http.request", "body": b"", "more_body": False} async def send(m): msgs.append(m) scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method, "scheme": "http", "path": path, "raw_path": path.encode(), "root_path": "", "query_string": query.encode(), "headers": [(b"host", b"sfm.local")], "server": ("sfm.local", 80), "client": ("127.0.0.1", 1)} asyncio.run(srv.app(scope, receive, send)) return next(m for m in msgs if m["type"] == "http.response.start")["status"] @pytest.mark.parametrize("method,path", [("GET", "/device/call_home/state"), ("POST", "/device/call_home/enable"), ("POST", "/device/call_home/disable")]) def test_call_home_routes_need_a_serial(method, path): assert _asgi(method, path, "host=10.0.0.5&tcp_port=9034") == 422 def test_call_home_routes_are_serial_aware(): assert {"/device/call_home/state", "/device/call_home/enable", "/device/call_home/disable"} <= srv._SERIAL_AWARE_PATHS def test_legacy_call_home_post_still_refuses_a_micromate_serial(): refusal = srv._device_guard("/device/call_home", {"serial": "UM20147"}) assert refusal is not None and refusal[0] == 501