Files
seismo-relay/tests/test_server_device_access.py
T
serversdownandClaude Opus 5.5 278921796a fix(sfm): any request taking the legacy path is refused beside a held line
The /device guard let every non-UM serial through before its held-line
check.  FastAPI drops an undeclared `serial`, so `?serial=BE18193` on a
legacy route still ran Series-3 code at an address holding a Series-4
line -- the hole the guard exists to close.  Serial-aware routes go
straight to DeviceAccess, which refuses that case itself; everything
else is checked.  baud is no longer parsed (it is not in the address
key, and pydantic's coercion made "38400.0" a second way past).

Also, from the same review:
- RingWatchTransport clears its frame state on every write, so a stray
  STX on an idle line cannot hide the ring that answers the next request.
- Series4Session.is_open reads _client once; held_serial() calls it
  without the unit lock, and a concurrent hang-up between two reads was
  an AttributeError (a 500).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-21 01:58:57 -04:00

160 lines
6.6 KiB
Python

"""Handlers called directly -- every parameter passed explicitly, because
FastAPI Query() defaults are FieldInfo objects, not values."""
from __future__ import annotations
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: s3q.pop(0),
s4_client_factory=lambda a: 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_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/monitor/stop", "/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/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