DeviceAccess.change_settings refuses before any I/O a request with no changes, a live change without its preview's revision, or no audit log, then dispatches the series' change (never retried). The route returns the preview (fields old -> new, warnings, blocked, revision) or the result (fields old/new/now), statuses as the other changes, and marks the cached by-host config dirty after a live change. /device/config and /device/config/project now answer 410 with a pointer. Deleted with them: MiniMateClient.apply_config / set_project_info and the raw-offset _encode_compliance_config (#46 found it wrong), the lab script poc_set_project.py and experiments.py's EXP6, both of which wrote a live unit through it. Git keeps them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
154 lines
5.8 KiB
Python
154 lines
5.8 KiB
Python
"""POST /device/settings/change (phase 5), and the legacy config write retired.
|
|
Handlers are called directly, every parameter passed, as in
|
|
test_server_device_access.py."""
|
|
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__))))
|
|
|
|
import micromate.protocol as mm_proto # noqa: E402
|
|
import sfm.server as srv # noqa: E402
|
|
from device_access_fakes import FakeMicromateClient, schedule_record # noqa: E402
|
|
from fastapi import HTTPException # noqa: E402
|
|
from sfm.device_access.access import DeviceAccess # noqa: E402
|
|
|
|
TCP = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034)
|
|
|
|
|
|
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)
|
|
|
|
|
|
class Cache:
|
|
def __init__(self):
|
|
self.dirty = []
|
|
|
|
def mark_config_dirty(self, key):
|
|
self.dirty.append(key)
|
|
|
|
|
|
@pytest.fixture
|
|
def unit(monkeypatch):
|
|
def make(fake):
|
|
access = DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False,
|
|
audit=Audit(), sleep=lambda s: None)
|
|
monkeypatch.setattr(srv, "_device_access_instance", access)
|
|
cache = Cache()
|
|
monkeypatch.setattr(srv, "get_cache", lambda: cache)
|
|
return cache
|
|
return make
|
|
|
|
|
|
def _post(changes, *, revision=None, dry_run=False, serial="UM20147"):
|
|
return srv.device_settings_change(body=srv.SettingsChangeBody(changes=changes, revision=revision),
|
|
serial=serial, dry_run=dry_run, caller="test", **TCP)
|
|
|
|
|
|
def _body(resp):
|
|
return json.loads(resp.body)
|
|
|
|
|
|
def test_route_dry_run_returns_fields_and_revision(unit):
|
|
cache = unit(FakeMicromateClient())
|
|
resp = _post({"geo_trigger_ips": 0.3}, dry_run=True)
|
|
body = _body(resp)
|
|
assert resp.status_code == 200 and body["outcome"] == "dry_run"
|
|
assert body["plan"]["fields"]["geo_trigger_ips"] == {"label": "Geophone trigger", "old": 0.5, "new": 0.3}
|
|
assert len(body["plan"]["revision"]) == 16 and cache.dirty == []
|
|
|
|
|
|
def test_route_verified_change_is_200_and_mismatch_409(unit, monkeypatch):
|
|
fake = FakeMicromateClient()
|
|
cache = unit(fake)
|
|
rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"]
|
|
resp = _post({"geo_trigger_ips": 0.3}, revision=rev)
|
|
assert resp.status_code == 200 and _body(resp)["state_after"] == "as asked"
|
|
assert len(cache.dirty) == 1 # a by-host read must not serve stale settings
|
|
# a unit that acks but stores something else reads back "differs": 409
|
|
fake2 = FakeMicromateClient()
|
|
unit(fake2)
|
|
rev = _body(_post({"job_number": 7}, dry_run=True))["plan"]["revision"]
|
|
real = fake2.protocol.execute
|
|
|
|
def wrong(plan):
|
|
acks = real(plan)
|
|
fake2.setup = fake2.setup[:40] + b"\x00\x08" + fake2.setup[42:]
|
|
from micromate.setup_block import with_crc
|
|
fake2.setup = with_crc(fake2.setup)
|
|
return acks
|
|
monkeypatch.setattr(fake2.protocol, "execute", wrong)
|
|
resp = _post({"job_number": 7}, revision=rev)
|
|
assert resp.status_code == 409 and _body(resp)["verified"] == "mismatch"
|
|
|
|
|
|
def test_route_unconfirmed_carries_sent_and_audit_id(unit, monkeypatch):
|
|
fake = FakeMicromateClient()
|
|
unit(fake)
|
|
rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"]
|
|
real = fake.protocol.execute
|
|
|
|
def then_drop(plan):
|
|
acks = real(plan)
|
|
fake.run_states = [0x03] # it began calling home before the read-back
|
|
return acks
|
|
monkeypatch.setattr(fake.protocol, "execute", then_drop)
|
|
resp = _post({"geo_trigger_ips": 0.3}, revision=rev)
|
|
body = _body(resp)
|
|
assert body["sent"] == "acknowledged" and body["audit_id"]
|
|
|
|
|
|
@pytest.mark.parametrize("fake_kw, match", [
|
|
(dict(schedule_body=schedule_record(14, 0x02, "other.mmb") + bytes(264)), "other.mmb"),
|
|
(dict(active_name="factory.MMB"), "factory setup"),
|
|
(dict(run_states=[0x02]), "stop it first"),
|
|
])
|
|
def test_route_refusal_is_409_with_reason(unit, fake_kw, match):
|
|
fake = FakeMicromateClient(**fake_kw)
|
|
unit(fake)
|
|
rev = "0000000000000000"
|
|
if 0x02 not in fake.run_states: # a monitoring unit refuses the preview too
|
|
rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"]
|
|
with pytest.raises(HTTPException) as e:
|
|
_post({"geo_trigger_ips": 0.3}, revision=rev)
|
|
assert e.value.status_code == 409 and match in str(e.value.detail)
|
|
|
|
|
|
def test_route_stale_preview_is_409(unit):
|
|
unit(FakeMicromateClient())
|
|
with pytest.raises(HTTPException) as e:
|
|
_post({"geo_trigger_ips": 0.3}, revision="0000000000000000")
|
|
assert e.value.status_code == 409 and "preview again" in str(e.value.detail)
|
|
|
|
|
|
def test_route_live_without_revision_is_422(unit):
|
|
unit(FakeMicromateClient())
|
|
with pytest.raises(HTTPException) as e:
|
|
_post({"geo_trigger_ips": 0.3})
|
|
assert e.value.status_code == 422 and "preview first" in str(e.value.detail)
|
|
|
|
|
|
@pytest.mark.parametrize("route", ["device_config", "device_config_project"])
|
|
def test_legacy_config_routes_are_gone(route, monkeypatch):
|
|
monkeypatch.setattr(srv, "_build_client", lambda *a, **kw: pytest.fail("no client may be built"))
|
|
resp = getattr(srv, route)()
|
|
assert resp.status_code == 410 and "/device/settings/change" in _body(resp)["detail"]
|
|
|
|
|
|
def test_settings_change_is_serial_aware():
|
|
assert "/device/settings/change" in srv._SERIAL_AWARE_PATHS
|
|
assert srv._device_guard("/device/settings/change", {"serial": "UM20147", "host": "h"}) is None
|