"""Write plans: built from the unit's own reads, equal to THOR's frames byte for byte.""" from __future__ import annotations import dataclasses 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 _call_home_reads(): return [_content(e) for e in _session("call-home-enable-disable") if e["sub"] == 0x2C] @pytest.mark.parametrize("read_idx", [0, 1]) @pytest.mark.parametrize("enabled", [True, False]) def test_call_home_flips_exactly_one_bit_and_echoes_everything_else(read_idx, enabled): reads = _call_home_reads() assert {reads[0][5], reads[1][5]} == {0x04, 0x05} r = reads[read_idx] data = plan_call_home_enabled(r, enabled).steps[0].data diff = [i for i in range(len(r)) if data[i] != r[i]] assert set(diff) <= {5} assert data[5] & 0x01 == (1 if enabled else 0) assert data[5] & 0xFE == r[5] & 0xFE if (r[5] & 1) == int(enabled): assert data[5] == r[5] assert data[118:120] == r[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"} def test_a_plan_copies_its_steps_so_a_later_mutation_cannot_change_it(): lst = [WriteStep(0x96, 0xFFFF)] plan = WritePlan("start", lst) before = plan.frames() lst.append(WriteStep(0xA2, 0xFFFF)) lst[0] = WriteStep(0x97, 0xFFFF) assert isinstance(plan.steps, tuple) and len(plan.steps) == 1 assert plan.steps[0].sub == 0x96 assert plan.frames() == before def test_steps_cannot_be_reassigned(): plan = plan_stop_monitoring() with pytest.raises(dataclasses.FrozenInstanceError): plan.steps = () # ── warnings: where a plan leaves THOR's observed values ────────────────────── def test_call_home_off_from_an_unobserved_start_value_carries_a_warning(): r = bytearray(_call_home_reads()[0]) r[5] = 0x01 # UM20147 reads 0x01, not THOR's 0x04/0x05 plan = plan_call_home_enabled(bytes(r), False) assert any("unobserved" in w and "0x01 -> 0x00" in w for w in plan.warnings) assert plan.describe()["warnings"] and plan.describe()["warnings"] == list(plan.warnings) def test_call_home_on_when_already_on_says_it_changes_nothing(): r = next(x for x in _call_home_reads() if x[5] == 0x05) plan = plan_call_home_enabled(r, True) assert any("changes nothing" in w and "enabled" in w for w in plan.warnings) @pytest.mark.parametrize("read_idx,enabled", [(0, True), (1, False)]) def test_thors_own_call_home_writes_carry_no_unobserved_warning(read_idx, enabled): r = _call_home_reads()[read_idx] plan = plan_call_home_enabled(r, enabled) assert not any("unobserved" in w for w in plan.warnings) assert plan.warnings == () assert plan_stop_monitoring().describe()["warnings"] == []