test(micromate): an AST scan pins execute() as the only write grant; cover the last mutants

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-23 16:17:04 -04:00
1 parent a90b8158b6
commit 9ed9578d12
4 files changed
+90 -25

No files matched your search

+83 -16
View File
@@ -2,8 +2,9 @@
from __future__ import annotations
import os
import ast
import pathlib
import re
import subprocess
import sys
from types import SimpleNamespace
@@ -98,11 +99,6 @@ def test_a_permit_beyond_the_ceiling_cannot_send():
assert t.written == []
def test_the_constructor_no_longer_grants_anything():
with pytest.raises(TypeError):
proto([], allowed_writes={0xA8})
def test_a_duck_typed_plan_is_refused():
p, t = _ready([])
fake = SimpleNamespace(subs=frozenset({0x96}), steps=(WriteStep(0x7E, 0),))
@@ -166,15 +162,86 @@ def test_execute_works_right_after_a_valid_read():
assert len(t.written) == 1
# -- nothing outside protocol.py passes permit= to _send ---------------------------
def test_a_successful_two_step_plan_sends_both_in_order():
plan = WritePlan("start then stop",
(WriteStep(0x96, 0xFFFF), WriteStep(0x97, 0xFFFF)))
p, t = _ready([ACK_START, frame(0x68, bytes(ACK_DATA_LEN))])
acks = p.execute(plan)
assert t.written == [build_request(0x96, 0xFFFF), build_request(0x97, 0xFFFF)]
assert [a.sub for a in acks] == [0x69, 0x68]
def test_only_protocol_py_passes_permit():
def test_an_in_ceiling_frame_sub_mismatch_is_refused():
class Liar(WriteStep):
@property
def frame(self):
return build_request(0x97, 0xFFFF)
p, t = _ready([ACK_START])
plan = WritePlan("x", (Liar(0x96, 0xFFFF),))
with pytest.raises(OpcodeRefused):
p.execute(plan)
assert t.written == []
@pytest.mark.parametrize("bad", [
frame(0x99, bytes(48)), # Micromate flags, wrong SUB
frame(0xA4, bytes(48))[:-2] + b"\x00\x03", # Micromate flags, bad checksum
])
def test_a_flagged_reply_that_fails_validation_leaves_no_trust(bad):
p, t = _ready([bad])
with pytest.raises(Exception):
p.poll()
assert p.last_flags is None
t.written.clear()
with pytest.raises(OpcodeRefused):
p.execute(plan_start_monitoring())
assert t.written == []
# -- nothing outside protocol.py reaches the wire with permission -----------------
def scan_source(src: str, name: str = "<s>") -> list[str]:
"""Hits: a `permit=` keyword, `**kw` into _send/_request, any `._request` call."""
hits = []
for node in ast.walk(ast.parse(src)):
if not isinstance(node, ast.Call):
continue
fn = node.func
fname = fn.attr if isinstance(fn, ast.Attribute) else getattr(fn, "id", "")
if any(k.arg == "permit" for k in node.keywords):
hits.append(f"{name}:{node.lineno} permit=")
if fname in ("_send", "_request") and any(k.arg is None for k in node.keywords):
hits.append(f"{name}:{node.lineno} **kwargs into {fname}")
if isinstance(fn, ast.Attribute) and fn.attr == "_request":
hits.append(f"{name}:{node.lineno} ._request call")
return hits
@pytest.mark.parametrize("src", [
"p._send(build_request(0x96, 0xFFFF), permit=frozenset({0x96}))",
"p._send(frame, **kw)",
"p._request(frame, 0x69, permit=x)",
"p._request(frame, 0x69)",
])
def test_the_scanner_catches_each_shape(src):
assert scan_source(src)
def test_the_scanner_ignores_ordinary_calls():
assert scan_source("p._send(frame)\nf(a, b=1)") == []
def test_only_protocol_py_grants_write_permission():
root = pathlib.Path(__file__).resolve().parent.parent
offenders = []
for d in ("micromate", "sfm", "bridges", "scratch", "scripts"):
for f in (root / d).rglob("*.py"):
if f == root / "micromate" / "protocol.py":
continue
if re.search(r"_send\([^)]*permit\s*=", f.read_text(errors="ignore"), re.S):
offenders.append(str(f))
assert offenders == []
files = subprocess.run(["git", "ls-files", "*.py"], cwd=root, capture_output=True,
text=True, check=True).stdout.split()
hits = []
for rel in files:
if rel.startswith("tests/") or rel == "micromate/protocol.py":
continue
try:
src = (root / rel).read_text(errors="ignore")
hits += scan_source(src, rel)
except SyntaxError:
pass
assert hits == []