Files
seismo-relay/tests/test_micromate_writes.py
T

163 lines
6.8 KiB
Python

"""Write plans: built from the unit's own reads, equal to THOR's frames byte for byte."""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from micromate.opcodes import OpcodeRefused # noqa: E402
from micromate.writes import ( # noqa: E402
WritePlan, WriteStep, plan_call_home_enabled, plan_setup_push,
plan_start_monitoring, plan_stop_monitoring,
)
FIX = Path(__file__).parent / "fixtures" / "micromate-writes"
PUSHES = ["setup-push-new-test1", "setup-push-overwrite-test1", "setup-push-read-scheduler",
"setup-push-pull-schedule", "setup-push-multiday"]
NO_EDIT_PUSHES = ["setup-push-read-scheduler", "setup-push-pull-schedule", "setup-push-multiday"]
def _session(slug):
return json.loads((FIX / f"{slug}.json").read_text())["exchanges"]
def _content(ex):
return bytes.fromhex(ex["response_data"])[11:]
def _first_push(slug):
"""The reads (by SUB) and THOR's writes (by SUB) of the session's first push."""
ex = _session(slug)
start = next(i for i, e in enumerate(ex) if e["sub"] == 0xDA)
reads = {}
for e in ex[:start]:
reads[e["sub"]] = _content(e) # the LAST read of each SUB before the push
writes = {}
for e in ex[start:]:
if e["sub"] in writes:
break
writes[e["sub"]] = bytes.fromhex(e["request"])
if e["sub"] == 0x72:
break
return reads, writes
def _name_from_active(content):
# Mirrors micromate.client._cstring(content): name at content[0], NUL-terminated, stripped.
return content.split(b"\x00")[0].decode("ascii", "replace").strip()
# ── start / stop ──────────────────────────────────────────────────────────────
def test_start_and_stop_equal_thors_frames():
thor = {e["sub"]: bytes.fromhex(e["request"]) for e in _session("monitor-start-stop")
if e["sub"] in (0x96, 0x97)}
assert plan_start_monitoring().frames() == [thor[0x96]]
assert plan_stop_monitoring().frames() == [thor[0x97]]
assert thor[0x96].hex() == "41021010009600ffff00000000000000000000a403"
# ── call-home ─────────────────────────────────────────────────────────────────
def test_call_home_enable_then_disable_equal_thors_frames():
ex = _session("call-home-enable-disable")
pairs, last_read = [], None
for e in ex:
if e["sub"] == 0x2C:
last_read = _content(e)
elif e["sub"] == 0x7E:
pairs.append((last_read, bytes.fromhex(e["request"])))
confirms = [bytes.fromhex(e["request"]) for e in ex if e["sub"] == 0x7F]
assert len(pairs) == 2 and len(confirms) == 2
(r1, w1), (r2, w2) = pairs
on, off = plan_call_home_enabled(r1, True), plan_call_home_enabled(r2, False)
assert on.frames() == [w1, confirms[0]]
assert off.frames() == [w2, confirms[1]]
def test_call_home_flips_exactly_one_bit_and_echoes_everything_else():
r1 = next(_content(e) for e in _session("call-home-enable-disable") if e["sub"] == 0x2C)
for enabled in (True, False):
data = plan_call_home_enabled(r1, enabled).steps[0].data
diff = [i for i in range(len(r1)) if data[i] != r1[i]]
assert set(diff) <= {5}
assert data[5] & 0x01 == (1 if enabled else 0)
assert data[5] & 0xFE == r1[5] & 0xFE
assert data[118:120] == r1[118:120]
def test_call_home_refuses_an_unobserved_size():
with pytest.raises(ValueError, match="126"):
plan_call_home_enabled(bytes(125), True)
# ── setup push ────────────────────────────────────────────────────────────────
@pytest.mark.parametrize("slug", PUSHES)
def test_setup_push_name_prefs_trigger_and_confirms_equal_thors_frames(slug):
reads, thor = _first_push(slug)
name = ("TEST1.mmb" if slug == "setup-push-new-test1"
else _name_from_active(reads[0x41]))
plan = plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], name)
ours = {s.sub: s.frame for s in plan.steps}
for sub in (0xDA, 0x68, 0x73, 0x82, 0x83, 0x72):
assert ours[sub] == thor[sub], f"{slug}: SUB 0x{sub:02X}"
assert [s.sub for s in plan.steps] == [0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72]
@pytest.mark.parametrize("slug", NO_EDIT_PUSHES)
def test_a_no_edit_push_reproduces_thors_setup_block_frame(slug):
reads, thor = _first_push(slug)
plan = plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], _name_from_active(reads[0x41]))
assert next(s.frame for s in plan.steps if s.sub == 0x71) == thor[0x71]
def test_setup_push_refuses_a_read_that_fails_its_checksum():
reads, _ = _first_push("setup-push-multiday")
bad = bytearray(reads[0x1A])
bad[100] ^= 0xFF
with pytest.raises(ValueError, match="checksum"):
plan_setup_push(reads[0x08], reads[0x2E], bytes(bad), "x.mmb")
@pytest.mark.parametrize("which", ["prefs", "trigger", "setup"])
def test_setup_push_refuses_an_unobserved_block_size(which):
reads, _ = _first_push("setup-push-multiday")
args = {"prefs": reads[0x08], "trigger": reads[0x2E], "setup": reads[0x1A]}
args[which] = args[which] + b"\x00\x00"
with pytest.raises(ValueError, match="size"):
plan_setup_push(args["prefs"], args["trigger"], args["setup"], "x.mmb")
@pytest.mark.parametrize("name", ["", "a\x00b", "é.mmb", "x" * 256])
def test_setup_push_refuses_a_bad_name(name):
reads, _ = _first_push("setup-push-multiday")
with pytest.raises(ValueError):
plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], name)
# ── the plan object ───────────────────────────────────────────────────────────
def test_a_plan_cannot_hold_a_collision_opcode():
with pytest.raises(OpcodeRefused):
WritePlan("end call-home", (WriteStep(0xA2, 0xFFFF),))
def test_a_plan_cannot_hold_a_read():
with pytest.raises(ValueError):
WritePlan("poll", (WriteStep(0x5B, 0x0030),))
def test_describe_is_the_dry_run_shape():
d = plan_stop_monitoring().describe()
assert d["action"] == "stop monitoring" and d["sends_nothing"] is True
step = d["steps"][0]
assert step == {"sub": "0x97", "what": "stop monitoring", "offset": "0xFFFF",
"data_len": 0, "expect_ack": "0x68",
"frame": "41021010009700ffff00000000000000000000a503"}