Files
seismo-relay/tests/test_minimate_write_frames.py
serversdownandClaude Opus 5.5 4d0984dcaf test: everything the tests read is in git -- a fresh checkout passes on its own
A fresh checkout of dev failed 10 tests, errored 3 and skipped 64: the
tests read 100 files that were only on the dev box.  Recorded with an
audit hook over a full run: 100 files, 2.3 MB, out of 1.1 GB of
bridges/captures/ and 45 MB of histogram-extension-re/.

- Force-added in place: tests/fixtures/thor-idf (14), histogram-multi-
  interval (2) and the one histogram-extension-re file read.
- Copied into tests/fixtures/example-events/ (10) and
  tests/fixtures/captures/ (73, from bridges/captures/), and the tests
  pointed there.
- The presence skips ('not on this machine', 'gitignored', 'fixture
  missing') are gone: a missing fixture now fails instead of skipping.

The worktree now runs as the dev box does: 1,787 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-19 13:32:59 -05:00

237 lines
8.5 KiB
Python

"""MiniMate config writes, against Blastware's own (issue #46).
Measured 2026-10-26/27: every Blastware request on record -- 3,869 frames from
February to April 2026 plus tonight's -- is the standard 16-byte payload with a
SUM8 checksum and every 02/03/04/10 escaped, write frames included (77 carrying
data). A write's length field is its data's length, and each block is written as
read plus two trailing bytes: event index (68) `02 00`, trigger (82) `00 00`, the
2,092-byte compliance image (71) in addressed chunks. The old builder ("raw
except BW_CMD", "DLE-aware checksum") got 7 of every 13 frames wrong, and
apply_config wrote a trigger block hard-coded from March whose byte 5 differs by
unit and session (01 / 03 / 04).
"""
from __future__ import annotations
import glob
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import minimateplus.protocol as mp # noqa: E402
from minimateplus.framing import S3FrameParser, build_bw_write_frame, unescape_reply # noqa: E402
FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram"
CAPTURES = Path(__file__).parent / "fixtures" / "captures" # copied from bridges/captures/
def _unstuff(b: bytes) -> bytes:
out, k = bytearray(), 0
while k < len(b):
if b[k] == 0x10 and k + 1 < len(b):
out.append(b[k + 1]); k += 2
else:
out.append(b[k]); k += 1
return bytes(out)
def _frames(raw: bytes) -> list:
out, i = [], 0
while i < len(raw):
if raw[i:i + 2] == b"\x41\x03":
i += 2
continue
if raw[i:i + 2] != b"\x41\x02":
i += 1
continue
j = i + 2
while j < len(raw) and raw[j] != 0x03:
j += 2 if raw[j] == 0x10 else 1
out.append(raw[i:j + 1])
i = j + 1
return out
def _payload(frame: bytes) -> bytes:
return _unstuff(frame[2:-1])[:-1]
REQS = _frames((FIX / "requests.bin").read_bytes())
WRITES = [f for f in REQS if 0x68 <= _payload(f)[2] <= 0x83]
SEND2 = WRITES[13:26] # 16:27:21, the interval back to 2 s
def _image(sub: int) -> bytes:
return b"".join(_payload(f)[16:] for f in SEND2 if _payload(f)[2] == sub)
def test_the_fixture_holds_two_whole_sends():
assert [f"{_payload(f)[2]:02X}" for f in SEND2] == \
["68", "73", "71", "71", "71", "71", "71", "72", "82", "83", "69", "74", "72"]
def _rebuilds(frames: list) -> bool:
for f in frames:
p = _payload(f)
if build_bw_write_frame(p[2], p[16:], params=p[6:16]) != f:
return False
return True
def test_every_write_frame_tonight_is_rebuilt_byte_for_byte():
assert len(WRITES) == 26 and _rebuilds(WRITES)
_OLD = sorted(glob.glob(str(CAPTURES / "[234]-*" / "**" / "raw_bw*.bin"), recursive=True))
def test_every_write_frame_since_february_is_rebuilt_byte_for_byte():
assert _OLD, f"no Feb-Apr 2026 Blastware captures under {CAPTURES}"
frames = [f for path in _OLD for f in _frames(Path(path).read_bytes())
if 0x68 <= _payload(f)[2] <= 0x83]
assert len([f for f in frames if len(_payload(f)) > 16]) >= 48
assert _rebuilds(frames)
# -- the protocol: images in, Blastware's frames out ---------------------------
def _ack(write_sub: int) -> bytes:
raw, start, p = (FIX / "unit_replies.bin").read_bytes(), 0, S3FrameParser()
for i in range(len(raw)):
for f in p.feed(raw[i:i + 1]):
w = raw[start:i + 1]
if f.sub == (0xFF - write_sub) & 0xFF:
return w[w.index(b"\x10\x02"):]
start = i + 1
raise AssertionError(f"no ack for 0x{write_sub:02X}")
class Acks:
"""Answers every write request with the unit's recorded ack for its SUB."""
def __init__(self):
self.sent, self._buf = [], b""
def write(self, data):
data = bytes(data)
self.sent.append(data)
self._buf += _ack(_payload(data)[2])
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
def _proto():
t = Acks()
return mp.MiniMateProtocol(t), t
def test_the_event_index_block_as_read_is_written_as_blastware_wrote_it():
p, t = _proto()
block = _image(0x68)[:-2] # the 88 bytes 0x08 returns
p.write_event_index(block)
assert t.sent == [f for f in SEND2 if _payload(f)[2] == 0x68]
def test_the_trigger_block_as_read_is_written_as_blastware_wrote_it():
p, t = _proto()
p.write_trigger_config(_image(0x82)[:-2]) # the 26 bytes 0x2E returns
assert t.sent == [f for f in SEND2 if _payload(f)[2] == 0x82]
def test_the_compliance_image_goes_in_blastwares_chunks_then_the_confirm():
p, t = _proto()
p.write_compliance_config_raw(_image(0x71))
want = [f for f in SEND2 if _payload(f)[2] == 0x71]
assert t.sent[:-1] == want
assert _payload(t.sent[-1])[2] == 0x72
def test_the_waveform_data_block_is_written_as_given():
p, t = _proto()
p.write_waveform_data(_image(0x69))
assert t.sent == [f for f in SEND2 if _payload(f)[2] == 0x69]
def test_an_image_in_the_parsers_form_is_unescaped_first():
# what a read hands over: the parser keeps the 10 of 10 02/03/04
p, t = _proto()
img = _image(0x71)
parser_form = img.replace(b"\x03", b"\x10\x03").replace(b"\x04", b"\x10\x04")
assert unescape_reply(parser_form) == img and parser_form != img
p.write_compliance_config_raw(parser_form)
assert t.sent[:-1] == [f for f in SEND2 if _payload(f)[2] == 0x71]
def test_a_stray_byte_is_refused_before_anything_is_sent():
# the encoder's old hazard: a value changed beside a kept escape byte leaves a
# lone 10 behind -- the image is then one byte longer than its header says
p, t = _proto()
img = _image(0x71)
with pytest.raises(ValueError, match="not a whole block"):
p.write_compliance_config_raw(img[:6] + b"\x10" + img[6:])
assert t.sent == []
class Replies:
"""Answers each request with the unit's next recorded reply of the right SUB."""
def __init__(self):
raw, start, p = (FIX / "unit_replies.bin").read_bytes(), 0, S3FrameParser()
self.by_sub, self.sent, self._buf = {}, [], b""
for i in range(len(raw)):
for f in p.feed(raw[i:i + 1]):
w = raw[start:i + 1]
self.by_sub.setdefault(f.sub, []).append(w[w.index(b"\x10\x02"):])
start = i + 1
def write(self, data):
data = bytes(data)
self.sent.append(data)
self._buf += self.by_sub[(0xFF - _payload(data)[2]) & 0xFF].pop(0)
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
@pytest.mark.parametrize("read,sub,size", [("read_event_index", 0x68, 88),
("read_trigger_config", 0x82, 26),
("read_waveform_data_raw", 0x69, 202)])
def test_each_read_returns_the_block_blastware_then_wrote(read, sub, size):
"""A 02/03/04/10 inside a block arrives escaped; a slice of the parser's output
by length came up short. The reads return the unescaped block -- the bytes
Blastware wrote back (the waveform-data read includes its 2 trailing bytes,
which Blastware replaced)."""
block = getattr(mp.MiniMateProtocol(Replies()), read)()
assert len(block) == size
want = _image(sub)
assert block[:-2] == want[:-2] if sub == 0x69 else block == want[:-2]
# -- the unit's own trigger block is sent back: tests/test_device_access_s3_settings.py
# (test_s3_trigger_change_sends_the_units_own_blocks), phase 5.
def test_a_bad_block_is_refused_before_the_first_write_goes_out():
"""Review of #46 (2026-10-27, measured on 12 recorded SFM reads): the compliance
read keeps three escape bytes from its reply headers and unescapes to
00 + cfg[0:1024] + 00 00 + cfg[1024:2090]. That block was refused -- but only
after 68 and 73 had been sent. push_config_raw now checks all four first.
(The read is deliberately not 'fixed' on its own: the encoder would then write
some fields to the wrong bytes while the image still passes -- see #46.)"""
from minimateplus.client import MiniMateClient
cfg = _image(0x71)[:-2]
as_sfm_reads_it = b"\x00" + cfg[:1024] + b"\x00\x00" + cfg[1024:]
p, t = _proto()
c = MiniMateClient(transport=object())
c._proto = p
with pytest.raises(ValueError, match="not a whole block"):
c.push_config_raw(_image(0x68)[:-2], as_sfm_reads_it + b"\x00\x00",
_image(0x82)[:-2], _image(0x69))
assert t.sent == []