Add guarded Meshtext, radio2 and multi-hop OTA hardware tests
Add identity-bound app flash adapters, exact-receipt radio2 sweeps through preamble 384, measured packet-window goodput, stock-peer delivery probes, Zopfli1000 USB OTA serving and bridge outage/recovery checks. Keep dwell experiments opt-in, production timing unchanged, generated artifacts outside Git, and wire offline safety tests into CI.
This commit is contained in:
1 parent
03b660e06f
commit
c6e43c5530
19 files changed
+5054
-7
No files matched your search
@@ -0,0 +1,265 @@
|
||||
"""Pure guards and simulated RAW benchmark tests: no SDK, serial or RF needed."""
|
||||
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SPEC = importlib.util.spec_from_file_location("companion_raw_radio2_sweep_test",
|
||||
ROOT / "tools/hil/companion_raw_radio2_sweep.py")
|
||||
BENCH = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(BENCH)
|
||||
|
||||
|
||||
class FakePair:
|
||||
def __init__(self, *, loss=False, bad_guard=False, primary_tx=0, conflict=False, inactive=False):
|
||||
self.clock = 100.0
|
||||
self.last_source = None
|
||||
self.last_payload = None
|
||||
self.loss = loss
|
||||
self.total_sent = 0
|
||||
owner = self
|
||||
|
||||
class Node:
|
||||
max_channels = 1
|
||||
|
||||
def __init__(self, name):
|
||||
self.name, self.preamble = name, 128
|
||||
self.commands, self.requests = [], []
|
||||
self.tx = 0
|
||||
self.tx_power = 21
|
||||
|
||||
def channel_name(self, slot):
|
||||
return "mt-conflict" if conflict else "Public"
|
||||
|
||||
def cli(self, command):
|
||||
self.commands.append(command)
|
||||
if command == "get lab.tx":
|
||||
return "> wrong guard" if bad_guard and self.name == "b" else "> " + BENCH.GUARD
|
||||
if command == "get radio":
|
||||
return "> 910.5250244,62.5,7,5"
|
||||
if command == "get radio2.status":
|
||||
return f"> RX=0,0 TX={primary_tx},{self.tx}; active=radio2"
|
||||
if command == "get tx":
|
||||
return f"> {self.tx_power}"
|
||||
if command == "set tx 2":
|
||||
self.tx_power = 2
|
||||
if command.startswith("set radio2 "):
|
||||
self.preamble = int(command.rsplit(",", 1)[1])
|
||||
if command == "get radio2":
|
||||
return f"> 909.500000,500,5,5,rxtx,{self.preamble}; saved"
|
||||
if command == "get tx.ssh":
|
||||
return "> tx.ssh radio2; active=" + ("off" if inactive else "radio2")
|
||||
if command == "get radio2.timing":
|
||||
return "> synthetic timing only"
|
||||
return "OK"
|
||||
|
||||
def request(self, command, expected):
|
||||
self.requests.append(command)
|
||||
assert command[:2] == b"\x19\x00"
|
||||
assert expected == (0,)
|
||||
owner.last_source, owner.last_payload = self.name, command[2:]
|
||||
owner.total_sent += 1
|
||||
self.tx += 1
|
||||
return b"\x00"
|
||||
|
||||
self.nodes = {name: Node(name) for name in ("a", "b")}
|
||||
|
||||
def now(self):
|
||||
self.clock += 0.01
|
||||
return self.clock
|
||||
|
||||
def receiver(self, destination, payload, timeout):
|
||||
assert destination.name != self.last_source
|
||||
assert payload == self.last_payload
|
||||
received = not (self.loss and self.total_sent % 3 == 0)
|
||||
return {"received": received, "completed_at": self.now() if received else None,
|
||||
"unexpected_raw": 0, "ignored_frames": 0}
|
||||
|
||||
|
||||
class CompanionRawRadio2SweepTest(unittest.TestCase):
|
||||
def run_matrix(self, pair):
|
||||
checkpoints = []
|
||||
with mock.patch.object(BENCH.time, "sleep"), \
|
||||
mock.patch.object(BENCH.time, "monotonic", side_effect=pair.now):
|
||||
result = BENCH.run_matrix(pair.nodes, BENCH.PREAMBLES, (64, 172), count=2,
|
||||
timeout=1, interval=0, persist=lambda value: checkpoints.append(json.loads(json.dumps(value))),
|
||||
receiver=pair.receiver, run_id=b"TESTONLY")
|
||||
return result, checkpoints
|
||||
|
||||
def test_exact_raw_sizes_and_distinct_marker_identity(self):
|
||||
first = BENCH.make_payload(b"TESTONLY", 1, 0, 172)
|
||||
self.assertEqual(len(first), 172)
|
||||
self.assertEqual(first[:4], b"SSH\x01")
|
||||
self.assertNotEqual(first, BENCH.make_payload(b"TESTONLY", 2, 0, 172))
|
||||
self.assertNotEqual(first, BENCH.make_payload(b"TESTONLY", 1, 1, 172))
|
||||
with self.assertRaisesRegex(BENCH.Failure, "172"):
|
||||
BENCH.make_payload(b"TESTONLY", 1, 0, 230)
|
||||
|
||||
def test_guard_primary_and_profile_counters_are_strict(self):
|
||||
BENCH.prove_guard("> " + BENCH.GUARD)
|
||||
self.assertEqual(BENCH.parse_primary("> 910.5250244,62.5,7,5")[1:], (62.5, 7, 5))
|
||||
self.assertEqual(BENCH.parse_tx("> TX=0,12; active"), [0, 12])
|
||||
for function, value in ((BENCH.prove_guard, "> HIL TX lock=910.525 MHz"),
|
||||
(BENCH.parse_primary, "> 909.5,500,5,5"),
|
||||
(BENCH.parse_tx, "> no counters")):
|
||||
with self.subTest(value=value), self.assertRaises(BENCH.Failure):
|
||||
function(value)
|
||||
|
||||
def test_all_cases_count_opposite_exact_receipt_not_just_command_ok(self):
|
||||
pair = FakePair()
|
||||
result, checkpoints = self.run_matrix(pair)
|
||||
self.assertEqual(result["result"], "PASS", result.get("failure"))
|
||||
self.assertEqual(len(result["cases"]), 8)
|
||||
self.assertEqual(pair.total_sent, 32)
|
||||
self.assertEqual({item["raw_bytes"] for item in result["cases"] if item["preamble"] == 384}, {64, 172})
|
||||
self.assertTrue(all(item["measurement"]["received"] == 4 for item in result["cases"]))
|
||||
self.assertGreater(len(checkpoints), pair.total_sent)
|
||||
self.assertFalse(result["mtu230_supported"])
|
||||
self.assertTrue(all(not any(command.startswith(("set radio ", "set wifi", "set mt.channel"))
|
||||
for command in node.commands) for node in pair.nodes.values()))
|
||||
|
||||
def test_rf_loss_is_reported_and_not_hidden_by_command_ok(self):
|
||||
result, _ = self.run_matrix(FakePair(loss=True))
|
||||
self.assertEqual(result["result"], "LOSS")
|
||||
self.assertGreater(sum(item["measurement"]["lost"] for item in result["cases"]), 0)
|
||||
self.assertTrue(all(packet["command_completed"] for case in result["cases"]
|
||||
for packet in case["transfers"]))
|
||||
self.assertEqual(result["retries"], 0)
|
||||
|
||||
def test_guard_failure_primary_tx_or_channel_conflict_prevents_all_setters(self):
|
||||
for pair in (FakePair(bad_guard=True), FakePair(primary_tx=1), FakePair(conflict=True)):
|
||||
with self.subTest(pair=pair):
|
||||
result, _ = self.run_matrix(pair)
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertEqual(pair.total_sent, 0)
|
||||
self.assertFalse(any(command.startswith(("set ", "normalradio"))
|
||||
for node in pair.nodes.values() for command in node.commands))
|
||||
|
||||
def test_saved_but_inactive_radio2_route_prevents_transmission(self):
|
||||
pair = FakePair(inactive=True)
|
||||
result, _ = self.run_matrix(pair)
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertEqual(pair.total_sent, 0)
|
||||
self.assertIn("saved and active", result["failure"]["message"])
|
||||
|
||||
def test_temporary_profile_release_settles_before_tx_power_is_changed(self):
|
||||
pair = FakePair()
|
||||
events = []
|
||||
for name, node in pair.nodes.items():
|
||||
original = node.cli
|
||||
|
||||
def command(text, *, name=name, original=original):
|
||||
events.append((name, text))
|
||||
return original(text)
|
||||
|
||||
node.cli = command
|
||||
with mock.patch.object(BENCH.time, "sleep", side_effect=lambda value: events.append(("sleep", value))), \
|
||||
mock.patch.object(BENCH.time, "monotonic", side_effect=pair.now):
|
||||
result = BENCH.run_matrix(pair.nodes, (256,), (64,), count=1,
|
||||
timeout=1, interval=0, persist=lambda report: None, receiver=pair.receiver, run_id=b"TESTONLY")
|
||||
self.assertEqual(result["result"], "PASS")
|
||||
first_power = events.index(("a", "set tx 2"))
|
||||
releases_done = max(events.index((name, "set tempradio2 off")) for name in ("a", "b"))
|
||||
self.assertIn(("sleep", 2.5), events[releases_done + 1:first_power])
|
||||
|
||||
def test_plan_and_invalid_230_size_never_load_hardware_helpers(self):
|
||||
for arguments, expected in ((["--plan"], 0), (["--plan", "--sizes", "230"], 2), ([], 2)):
|
||||
with self.subTest(arguments=arguments), redirect_stdout(io.StringIO()) as output, \
|
||||
redirect_stderr(io.StringIO()), \
|
||||
mock.patch.object(BENCH, "safe_identity", side_effect=AssertionError("hardware inventory")):
|
||||
try:
|
||||
code = BENCH.main(arguments)
|
||||
except SystemExit as error:
|
||||
code = error.code
|
||||
self.assertEqual(code, expected)
|
||||
if code == 0:
|
||||
plan = json.loads(output.getvalue())
|
||||
self.assertEqual(plan["total_packets"], 160)
|
||||
self.assertEqual(plan["preambles"], [128, 256, 384, 512])
|
||||
|
||||
def test_384_plan_is_accepted_but_unreviewed_or_duplicate_preambles_are_rejected(self):
|
||||
for preambles, expected in (("384", 0), ("128,384,512", 0), ("300", 2), ("384,384", 2)):
|
||||
with self.subTest(preambles=preambles), redirect_stdout(io.StringIO()) as output, \
|
||||
redirect_stderr(io.StringIO()), \
|
||||
mock.patch.object(BENCH, "safe_identity", side_effect=AssertionError("hardware inventory")):
|
||||
try:
|
||||
code = BENCH.main(["--plan", "--preambles", preambles])
|
||||
except SystemExit as error:
|
||||
code = error.code
|
||||
self.assertEqual(code, expected)
|
||||
if code == 0:
|
||||
plan = json.loads(output.getvalue())
|
||||
self.assertIn(384, plan["preambles"])
|
||||
|
||||
def test_usb_identity_rejects_mismatched_stale_tty_without_open(self):
|
||||
listing = ModuleType("serial.tools")
|
||||
listing.list_ports = SimpleNamespace(comports=lambda: [SimpleNamespace(
|
||||
device="/dev/SIMULATED", serial_number="ACTUAL", vid=1, pid=2)])
|
||||
with mock.patch.dict(sys.modules, {"serial": ModuleType("serial"), "serial.tools": listing}):
|
||||
with self.assertRaisesRegex(BENCH.Failure, "expected physical serial"):
|
||||
BENCH.safe_identity("/dev/SIMULATED", "WRONG")
|
||||
self.assertEqual(BENCH.safe_identity("/dev/SIMULATED", "ACTUAL")["serial"], "ACTUAL")
|
||||
|
||||
def test_raw_push_requires_exact_payload_bytes(self):
|
||||
class FrameTimeout(Exception):
|
||||
pass
|
||||
helper = ModuleType("esp32_companion_serial_stress")
|
||||
helper.FrameTimeout = FrameTimeout
|
||||
payload = BENCH.make_payload(b"TESTONLY", 1, 0, 64)
|
||||
node = SimpleNamespace(port=object(), reader=SimpleNamespace(read_frame=mock.Mock(
|
||||
side_effect=(b"\x83", b"\x84\x00\x00\xffwrong", b"\x84\x00\x00\xff" + payload))))
|
||||
with mock.patch.dict(sys.modules, {"esp32_companion_serial_stress": helper}):
|
||||
result = BENCH.receive_exact(node, payload, 1)
|
||||
self.assertTrue(result["received"])
|
||||
self.assertEqual(result["unexpected_raw"], 1)
|
||||
self.assertEqual(result["ignored_frames"], 1)
|
||||
|
||||
def test_existing_low_tx_skips_setter_and_transient_busy_is_bounded(self):
|
||||
node = SimpleNamespace(cli=mock.Mock(return_value="> 2"))
|
||||
result = BENCH.ensure_low_tx(node)
|
||||
self.assertEqual(result["setter_attempts"], 0)
|
||||
node.cli.assert_called_once_with("get tx")
|
||||
node = SimpleNamespace(cli=mock.Mock(side_effect=("> 21",
|
||||
RuntimeError("Companion CLI set tx rejected: Error: radio busy or TX power rejected"), "OK", "> 2")))
|
||||
with mock.patch.object(BENCH.time, "sleep") as sleep:
|
||||
result = BENCH.ensure_low_tx(node)
|
||||
self.assertEqual(result["setter_attempts"], 2)
|
||||
sleep.assert_called_once_with(0.25)
|
||||
self.assertEqual(node.cli.call_args_list[-1], mock.call("get tx"))
|
||||
|
||||
def test_unknown_tx_errors_or_wrong_readback_fail_closed(self):
|
||||
for responses in (("> 21", RuntimeError("Companion CLI set tx rejected: Error: invalid TX power")),
|
||||
("> 21", "OK", "> 21")):
|
||||
with self.subTest(responses=responses):
|
||||
node = SimpleNamespace(cli=mock.Mock(side_effect=responses))
|
||||
with self.assertRaises(Exception), mock.patch.object(BENCH.time, "sleep") as sleep:
|
||||
BENCH.ensure_low_tx(node)
|
||||
sleep.assert_not_called()
|
||||
def busy(command):
|
||||
if command == "get tx":
|
||||
return "> 21"
|
||||
raise RuntimeError("Companion CLI set tx rejected: Error: radio busy or TX power rejected")
|
||||
with mock.patch.object(BENCH.time, "sleep"), \
|
||||
mock.patch.object(BENCH.time, "monotonic", side_effect=(0, 1, 8)):
|
||||
with self.assertRaisesRegex(BENCH.Failure, "bounded8-second"):
|
||||
BENCH.ensure_low_tx(SimpleNamespace(cli=busy))
|
||||
|
||||
def test_packet_window_rate_excludes_checkpoint_time_but_keeps_loss_timeouts(self):
|
||||
packets = [{"received": True, "raw_bytes": 64, "elapsed_seconds": 0.1, "direction": "a_to_b"},
|
||||
{"received": False, "raw_bytes": 64, "elapsed_seconds": 1, "direction": "b_to_a"}]
|
||||
value = BENCH.metrics(packets, elapsed=5)
|
||||
self.assertAlmostEqual(value["application_goodput_kbps"], 60 * 8 / 5 / 1000)
|
||||
self.assertAlmostEqual(value["packet_window_application_goodput_kbps"], 60 * 8 / 1.1 / 1000)
|
||||
self.assertAlmostEqual(value["packet_window_seconds"], 1.1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Offline contract for the headless Indicator LoRa+ESP-NOW HIL recipe.
|
||||
|
||||
Does not invoke PlatformIO, a compiler, a serial port or any hardware tool.
|
||||
These checks bind the recipe to the existing physical variant and partition
|
||||
contract; actual ELF/EndF/boot/RadioLib qualification remains a separate build.
|
||||
"""
|
||||
|
||||
import configparser
|
||||
import csv
|
||||
import fnmatch
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ENV = "env:SenseCapIndicator-LoRa_repeater_bridge_espnow_hil"
|
||||
|
||||
|
||||
class IndicatorRepeaterHilRecipeTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.config = configparser.ConfigParser(interpolation=None, strict=False)
|
||||
cls.config.read([ROOT / "platformio.ini",
|
||||
ROOT / "variants/sensecap_indicator-espnow/platformio.ini",
|
||||
ROOT / "tools/hil/indicator_repeater_espnow.ini"], encoding="utf-8")
|
||||
|
||||
def option(self, section, option, depth=0):
|
||||
self.assertLess(depth, 30, "recursive recipe interpolation")
|
||||
if self.config.has_option(section, option):
|
||||
value = self.config.get(section, option)
|
||||
return re.sub(r"\$\{([^}]+)\}", lambda match:
|
||||
self.option(*match[1].split(".", 1), depth=depth + 1), value)
|
||||
for parent in self.config.get(section, "extends", fallback="").split(","):
|
||||
if parent.strip():
|
||||
try:
|
||||
return self.option(parent.strip(), option, depth + 1)
|
||||
except KeyError:
|
||||
pass
|
||||
raise KeyError((section, option))
|
||||
|
||||
def defines(self):
|
||||
words = shlex.split(self.option(ENV, "build_flags"))
|
||||
values = {}
|
||||
index = 0
|
||||
while index < len(words):
|
||||
word = words[index]
|
||||
if word in ("-D", "-U"):
|
||||
index += 1
|
||||
word += words[index]
|
||||
if word.startswith("-U"):
|
||||
values.pop(word[2:], None)
|
||||
elif word.startswith("-D"):
|
||||
name, _, value = word[2:].partition("=")
|
||||
values[name] = value or "1"
|
||||
index += 1
|
||||
return values
|
||||
|
||||
def selected(self, source):
|
||||
result = False
|
||||
for action, pattern in re.findall(r"([+-])<([^>]+)>", self.option(ENV, "build_src_filter")):
|
||||
# Top-level '*.cpp' does not mean recursive matching in PIO.
|
||||
if "/" not in pattern and "/" in source:
|
||||
continue
|
||||
match = fnmatch.fnmatchcase(source, pattern)
|
||||
if not any(character in pattern for character in "*?["):
|
||||
match = match or source.startswith(pattern.rstrip("/") + "/")
|
||||
if match:
|
||||
result = action == "+"
|
||||
return result
|
||||
|
||||
def test_exact_physical_lora_variant_and_n8r8_memory_contract(self):
|
||||
self.assertEqual(self.option(ENV, "extends"), "SenseCapIndicator-LoRa")
|
||||
self.assertEqual(self.option(ENV, "board"), "esp32-s3-devkitc-1")
|
||||
self.assertEqual(self.option(ENV, "board_upload.flash_size"), "8MB")
|
||||
self.assertEqual(self.option(ENV, "board_build.arduino.memory_type"), "qio_opi")
|
||||
self.assertEqual(self.option(ENV, "board_build.psram_type"), "opi")
|
||||
definitions = self.defines()
|
||||
self.assertEqual(definitions["MOTA_HW_ID"], '"SenseCapIndicator-LoRa"')
|
||||
self.assertEqual(definitions["SENSECAP_INDICATOR_LORA"], "1")
|
||||
self.assertEqual(definitions["WRAPPER_CLASS"], "IndicatorSX1262Wrapper")
|
||||
self.assertEqual([definitions[name] for name in ("P_LORA_NSS", "P_LORA_RESET",
|
||||
"P_LORA_BUSY", "P_LORA_DIO_1")], ["64", "65", "66", "67"])
|
||||
|
||||
def test_only_lab_frequency_can_transmit_and_boot_is_quiet(self):
|
||||
definitions = self.defines()
|
||||
for name, expected in {"LORA_FREQ": "908.5", "MESH_HIL_TX_FREQ_MHZ": "908.5",
|
||||
"LORA_BW": "500", "LORA_SF": "5", "LORA_CR": "5", "LORA_TX_POWER": "2",
|
||||
"ENABLE_ADVERT_ON_BOOT": "0", "DEFAULT_ADVERT_INTERVAL_MINUTES": "0",
|
||||
"DEFAULT_FLOOD_ADVERT_INTERVAL_HOURS": "0"}.items():
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(definitions[name], expected)
|
||||
|
||||
def test_headless_keeps_the_radio_expander_library_not_font_or_primary_espnow(self):
|
||||
definitions = self.defines()
|
||||
for name in ("DISPLAY_CLASS", "MESH_PRIMARY_ESPNOW", "DISABLE_WIFI_OTA",
|
||||
"WEBCONFIG_DISABLED", "OTA_SEEDER_ONLY"):
|
||||
self.assertNotIn(name, definitions)
|
||||
self.assertIn("LovyanGFX", self.option(ENV, "lib_deps"))
|
||||
for source in ("../variants/sensecap_indicator-espnow/target.cpp",
|
||||
"../variants/sensecap_indicator-espnow/IndicatorRadioHal.cpp"):
|
||||
self.assertTrue(self.selected(source), source)
|
||||
for source in ("helpers/esp32/ESPNOWRadio.cpp", "helpers/ui/LGFXDisplay.cpp",
|
||||
"../variants/sensecap_indicator-espnow/IndicatorFontClient.cpp"):
|
||||
self.assertFalse(self.selected(source), source)
|
||||
|
||||
def test_full_repeater_ota_and_bridge_sources_are_not_companion_sources(self):
|
||||
definitions = self.defines()
|
||||
for name in ("WITH_ESPNOW_BRIDGE", "ENABLE_OTA", "OTA_FLASH_STORE",
|
||||
"WIFI_OTA_SEEDER", "MESHCORE_EXPANDED_PARTITION_PROFILE"):
|
||||
self.assertEqual(definitions[name], "1", name)
|
||||
for source in ("../examples/simple_repeater/main.cpp", "../examples/simple_repeater/MyMesh.cpp",
|
||||
"helpers/bridges/ESPNowBridge.cpp", "helpers/esp32/WebConfigServer.cpp",
|
||||
"helpers/esp32/WiFiOtaSeeder.cpp", "helpers/ota/OtaContext.cpp",
|
||||
"helpers/ota/detools/detools.c"):
|
||||
self.assertTrue(self.selected(source), source)
|
||||
self.assertFalse(self.selected("../examples/companion_radio/main.cpp"))
|
||||
self.assertFalse(self.selected("../examples/kiss_modem/main.cpp"))
|
||||
self.assertIn("AsyncElegantOTA", self.option(ENV, "lib_deps"))
|
||||
scripts = self.option(ENV, "extra_scripts")
|
||||
for script in ("meshcore_image_identity.py", "pio_endf.py", "check_firmware_ram.py"):
|
||||
self.assertIn(script, scripts)
|
||||
|
||||
def test_partitions_preserve_settings_and_fit_two_2p5m_slots_inside_8m(self):
|
||||
table = ROOT / self.option(ENV, "board_build.partitions")
|
||||
with table.open(encoding="utf-8") as stream:
|
||||
rows = [row for row in csv.reader(line for line in stream if not line.lstrip().startswith("#")) if row]
|
||||
partitions = {row[0].strip(): (int(row[3].strip(), 0), int(row[4].strip(), 0)) for row in rows}
|
||||
self.assertEqual(partitions["nvs"], (0x9000, 0x5000))
|
||||
self.assertEqual(partitions["spiffs"], (0x290000, 0x160000))
|
||||
self.assertEqual(partitions["app0"], (0x10000, 0x280000))
|
||||
self.assertEqual(partitions["app1"], (0x400000, 0x280000))
|
||||
self.assertEqual(int(self.option(ENV, "board_upload.maximum_size")), 0x280000)
|
||||
self.assertLessEqual(max(offset + size for offset, size in partitions.values()), 8 * 1024 * 1024)
|
||||
spans = sorted(partitions.values())
|
||||
self.assertTrue(all(offset + size <= next_offset
|
||||
for (offset, size), (next_offset, _) in zip(spans, spans[1:])))
|
||||
|
||||
def test_wrapped_bridge_and_enabled_defaults_are_existing_production_code(self):
|
||||
source = (ROOT / "examples/simple_repeater/MyMesh.cpp").read_text(encoding="utf-8")
|
||||
self.assertIn("_prefs.bridge_format = mesh::bridge::ESPNOW_FORMAT_WRAPPED;", source)
|
||||
self.assertIn("_prefs.bridge_channel = 1;", source)
|
||||
self.assertIn("_prefs.bridge_enabled = 1;", source)
|
||||
recipe = (ROOT / "tools/hil/indicator_repeater_espnow.ini").read_text(encoding="utf-8")
|
||||
self.assertIn("d8:3b:da:75:23:ac", recipe)
|
||||
self.assertIn("No production variant", recipe)
|
||||
self.assertIn("No flashing/erasing", recipe)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Exercise the S3 watchdog-finish adapter against inert flasher functions.
|
||||
|
||||
No serial device is opened. fuser/USB/DFU tools are replaced with explicit
|
||||
non-hardware stubs; the fake flasher records only phase ordering and failures.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ADAPTER = ROOT / "tools/hil/mercer_mt_flash.sh"
|
||||
PORT = "/dev/ttyACM99"
|
||||
MAC = "aabbccddeeff"
|
||||
|
||||
FAKE_FUNCTIONS = r'''
|
||||
esptool_set_variables() {
|
||||
NORESET=no-reset
|
||||
WATCHDOGRESET=${SIM_RESET_MODE-watchdog-reset}
|
||||
READMAC=read-mac
|
||||
printf 'variables\n' >> "$SIM_LOG"
|
||||
}
|
||||
prepare_esp32_flash_session() {
|
||||
printf 'prepare\n' >> "$SIM_LOG"
|
||||
ESP32_SESSION_IS_S3=${SIM_S3:-1}
|
||||
ESP32_FLASH_EXPECTED_MAC=${SIM_ACTUAL_MAC:-aabbccddeeff}
|
||||
}
|
||||
selected_flash_serial_port() {
|
||||
printf '%s\n' "$1"
|
||||
}
|
||||
esp32_verified_destructive_port() {
|
||||
printf 'verify:%s\n' "$2" >> "$SIM_LOG"
|
||||
if [[ "${SIM_FAIL_PHASE:-}" == "$2" ]]; then return 47; fi
|
||||
printf '%s\n' "$1"
|
||||
}
|
||||
run_esp32_session_esptool() {
|
||||
printf 'run:%s\n' "$*" >> "$SIM_LOG"
|
||||
case " $* " in
|
||||
*' flash-id '*) printf 'Detected flash size: %sMB\n' "${SIM_FLASH_MB:-16}" ;;
|
||||
*' write-flash '*)
|
||||
if [[ "${SIM_FAIL_PHASE:-}" == write ]]; then return 42; fi
|
||||
# Model the production wrapper's positive verification contract:
|
||||
# a missing verification marker is failure, even after exit zero.
|
||||
if [[ "${SIM_FAIL_PHASE:-}" == unverified-write ]]; then return 43; fi
|
||||
printf 'Hash of data verified.\n'
|
||||
printf 'verified-write\n' >> "$SIM_LOG" ;;
|
||||
*' write-mem '*)
|
||||
if [[ "${SIM_FAIL_PHASE:-}" == volatile ]]; then return 44; fi ;;
|
||||
*' --after watchdog-reset '*)
|
||||
if [[ "${SIM_FAIL_PHASE:-}" == reset ]]; then return 45; fi ;;
|
||||
esac
|
||||
}
|
||||
finish_esp32_flash_session() {
|
||||
printf 'ordinary-finish\n' >> "$SIM_LOG"
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
@unittest.skipUnless(os.name == "posix" and shutil.which("bash"),
|
||||
"POSIX Bash required; run on Linux/WSL")
|
||||
class MercerMtWatchdogFinishTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory(prefix="meshcore-mt-finish-mock-")
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.work = Path(temporary.name)
|
||||
self.log = self.work / "actions.log"
|
||||
self.startup = self.work / "FORBIDDEN-STARTUP"
|
||||
self.flasher = self.work / "mock-mcfirmware.sh"
|
||||
self.image = self.work / "application.bin"
|
||||
self.image.write_bytes(b"INERT MOCK IMAGE; NEVER FLASH")
|
||||
# Startup commands and traps must never be sourced by the adapter.
|
||||
source = ('#!/usr/bin/env bash\n'
|
||||
'printf startup > "$SIM_STARTUP"\n'
|
||||
'trap \'printf unwanted-trap >> "$SIM_LOG"\' EXIT\n'
|
||||
'exit 98\n') + FAKE_FUNCTIONS
|
||||
# The adapter deliberately requires a complete definitions inventory.
|
||||
source += "".join(f"inert_function_{i}() {{\n return 0\n}}\n"
|
||||
for i in range(100))
|
||||
self.flasher.write_text(source, encoding="utf-8")
|
||||
bindir = self.work / "bin"
|
||||
bindir.mkdir()
|
||||
for name in ("python3", "pipx", "timeout", "udevadm"):
|
||||
path = bindir / name
|
||||
path.write_text("#!/bin/sh\nprintf 'FORBIDDEN-TOOL\\n' >> \"$SIM_LOG\"\nexit 99\n",
|
||||
encoding="utf-8")
|
||||
path.chmod(0o700)
|
||||
fuser = bindir / "fuser"
|
||||
fuser.write_text("#!/bin/sh\nprintf 'owner-check:%s\\n' \"$*\" >> \"$SIM_LOG\"\n"
|
||||
'if [ "${SIM_BUSY:-0}" = 1 ]; then printf "1234\\n"; exit 0; fi\nexit 1\n',
|
||||
encoding="utf-8")
|
||||
fuser.chmod(0o700)
|
||||
self.env = dict(os.environ, PATH=str(bindir) + os.pathsep + os.environ["PATH"],
|
||||
SIM_LOG=str(self.log), SIM_STARTUP=str(self.startup))
|
||||
for name in ("SIM_RESET_MODE", "SIM_S3", "SIM_ACTUAL_MAC", "SIM_FAIL_PHASE",
|
||||
"SIM_BUSY", "SIM_FLASH_MB"):
|
||||
self.env.pop(name, None)
|
||||
|
||||
def invoke(self, *, mode="write-flash", watchdog=True, allow=True,
|
||||
allow_reset=False, operation_args=None, expected_mac=MAC,
|
||||
flash_bytes="16777216", environment=None):
|
||||
command = [shutil.which("bash"), str(ADAPTER), "--flasher", str(self.flasher),
|
||||
"--port", PORT, "--workdir", str(self.work),
|
||||
"--expect-mac", expected_mac, "--flash-bytes", flash_bytes]
|
||||
if watchdog:
|
||||
command.append("--watchdog-finish")
|
||||
if allow:
|
||||
command.extend(("--allow-write", "--allow-erase"))
|
||||
if allow_reset:
|
||||
command.append("--allow-reset")
|
||||
command.extend(("--", mode))
|
||||
if mode == "write-flash":
|
||||
command.extend(("0x10000", str(self.image)))
|
||||
elif mode == "read-flash":
|
||||
command.extend(("0x10000", "32", str(self.work / "unused-read.bin")))
|
||||
elif mode == "erase-region":
|
||||
command.extend(("0x10000", "4096"))
|
||||
if operation_args:
|
||||
command.extend(operation_args)
|
||||
result = subprocess.run(command, text=True, capture_output=True,
|
||||
env=dict(self.env, **(environment or {})),
|
||||
timeout=10, check=False)
|
||||
self.assertFalse(self.startup.exists(), "the flasher's global startup ran")
|
||||
actions = self.log.read_text(encoding="utf-8") if self.log.exists() else ""
|
||||
self.assertNotIn("FORBIDDEN-TOOL", actions)
|
||||
self.assertNotIn("unwanted-trap", actions)
|
||||
return result, actions
|
||||
|
||||
def test_watchdog_refuses_every_nonwrite_mode_before_flasher_or_serial_tools(self):
|
||||
for mode in ("probe", "read-flash", "erase-flash", "erase-region"):
|
||||
with self.subTest(mode=mode):
|
||||
result, actions = self.invoke(mode=mode)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("--watchdog-finish requires write-flash", result.stderr)
|
||||
self.assertEqual(actions, "")
|
||||
|
||||
def test_watchdog_does_not_grant_write_permission(self):
|
||||
result, actions = self.invoke(allow=False)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("write-flash requires --allow-write", result.stderr)
|
||||
self.assertEqual(actions, "")
|
||||
|
||||
def test_s3_and_supported_reset_are_required_before_any_flash_write(self):
|
||||
for environment, message in (({"SIM_S3": "0"}, "did not identify ESP32-S3"),
|
||||
({"SIM_RESET_MODE": ""}, "supported S3 watchdog reset"),
|
||||
({"SIM_RESET_MODE": "hard-reset"}, "supported S3 watchdog reset")):
|
||||
with self.subTest(environment=environment):
|
||||
self.log.unlink(missing_ok=True)
|
||||
result, actions = self.invoke(environment=environment)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn(message, result.stderr)
|
||||
self.assertIn("prepare", actions)
|
||||
self.assertNotIn("write-flash", actions)
|
||||
self.assertNotIn("write-mem", actions)
|
||||
self.assertNotIn("--after watchdog-reset", actions)
|
||||
|
||||
def test_expected_mac_is_checked_before_write_and_finish(self):
|
||||
result, actions = self.invoke(environment={"SIM_ACTUAL_MAC": "112233445566"})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("MAC mismatch", result.stderr)
|
||||
self.assertNotIn("write-flash", actions)
|
||||
self.assertNotIn("write-mem", actions)
|
||||
|
||||
def test_verified_write_precedes_masked_clear_identity_recheck_and_one_watchdog(self):
|
||||
result, actions = self.invoke()
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
phases = ["verify:write-flash", " write-flash ", "verified-write",
|
||||
"verify:S3 volatile forced-ROM bit clear", "write-mem 0x6000812c 0 0x1",
|
||||
"verify:S3 watchdog finish", "--after watchdog-reset --baud 115200 read-mac"]
|
||||
positions = [actions.index(phase) for phase in phases]
|
||||
self.assertEqual(positions, sorted(positions), actions)
|
||||
self.assertEqual(actions.count("--after watchdog-reset"), 1)
|
||||
self.assertNotIn("ordinary-finish", actions)
|
||||
self.assertNotIn("erase-flash", actions)
|
||||
self.assertIn("Application boot still requires an application-level check", result.stdout)
|
||||
|
||||
def test_failed_or_unverified_write_cannot_clear_rom_or_reset(self):
|
||||
for phase in ("write", "unverified-write"):
|
||||
with self.subTest(phase=phase):
|
||||
self.log.unlink(missing_ok=True)
|
||||
result, actions = self.invoke(environment={"SIM_FAIL_PHASE": phase})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn(" write-flash ", actions)
|
||||
self.assertNotIn("write-mem", actions)
|
||||
self.assertNotIn("--after watchdog-reset", actions)
|
||||
self.assertNotIn("ordinary-finish", actions)
|
||||
|
||||
def test_either_finish_identity_failure_prevents_the_next_phase(self):
|
||||
for phase, clear_expected in (("S3 volatile forced-ROM bit clear", False),
|
||||
("S3 watchdog finish", True)):
|
||||
with self.subTest(phase=phase):
|
||||
self.log.unlink(missing_ok=True)
|
||||
result, actions = self.invoke(environment={"SIM_FAIL_PHASE": phase})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual("write-mem" in actions, clear_expected)
|
||||
self.assertNotIn("--after watchdog-reset", actions)
|
||||
self.assertNotIn("ordinary-finish", actions)
|
||||
|
||||
def test_volatile_clear_failure_cannot_watchdog_or_fall_back_to_hard_reset(self):
|
||||
result, actions = self.invoke(environment={"SIM_FAIL_PHASE": "volatile"})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("write-mem", actions)
|
||||
self.assertNotIn("--after watchdog-reset", actions)
|
||||
self.assertNotIn("ordinary-finish", actions)
|
||||
|
||||
def test_failed_watchdog_is_not_retried_or_followed_by_another_reset(self):
|
||||
result, actions = self.invoke(environment={"SIM_FAIL_PHASE": "reset"})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(actions.count("--after watchdog-reset"), 1)
|
||||
self.assertNotIn("ordinary-finish", actions)
|
||||
self.assertNotIn("Application boot still requires", result.stdout)
|
||||
|
||||
def test_without_flag_the_original_finish_is_retained(self):
|
||||
result, actions = self.invoke(watchdog=False)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("ordinary-finish", actions)
|
||||
self.assertNotIn("write-mem", actions)
|
||||
self.assertNotIn("--after watchdog-reset", actions)
|
||||
|
||||
def test_runtime_reset_requires_its_own_consent_and_zero_arguments_before_tools(self):
|
||||
for options, message in (({}, "reset-runtime requires --allow-reset"),
|
||||
({"allow_reset": True, "operation_args": ["0x10000", str(self.image)]},
|
||||
"reset-runtime takes no arguments"),
|
||||
({"allow_reset": True, "watchdog": True},
|
||||
"--watchdog-finish requires write-flash")):
|
||||
with self.subTest(options=options):
|
||||
self.log.unlink(missing_ok=True)
|
||||
config = {"mode": "reset-runtime", "watchdog": False, "allow": False, **options}
|
||||
result, actions = self.invoke(**config)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn(message, result.stderr)
|
||||
self.assertEqual(actions, "")
|
||||
|
||||
def test_runtime_reset_requires_exact_mac_and_size_and_never_grants_flash_authority(self):
|
||||
for field in ("expected_mac", "flash_bytes"):
|
||||
with self.subTest(field=field):
|
||||
self.log.unlink(missing_ok=True)
|
||||
result, actions = self.invoke(mode="reset-runtime", watchdog=False,
|
||||
allow=False, allow_reset=True, **{field: ""})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("supply the verified expected MAC and flash bytes", result.stderr)
|
||||
self.assertEqual(actions, "")
|
||||
result, actions = self.invoke(mode="reset-runtime", watchdog=False,
|
||||
allow=False, allow_reset=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
phases = [" flash-id", "verify:S3 volatile forced-ROM bit clear",
|
||||
"write-mem 0x6000812c 0 0x1", "verify:S3 watchdog finish",
|
||||
"--after watchdog-reset --baud 115200 read-mac"]
|
||||
positions = [actions.index(phase) for phase in phases]
|
||||
self.assertEqual(positions, sorted(positions), actions)
|
||||
self.assertEqual(actions.count("--after watchdog-reset"), 1)
|
||||
for forbidden in ("write-flash", "erase-flash", "erase-region", "efuse",
|
||||
"reset-runtime", "ordinary-finish"):
|
||||
self.assertNotIn(forbidden, actions)
|
||||
|
||||
def test_runtime_reset_wrong_identity_chip_or_size_cannot_clear_or_watchdog(self):
|
||||
for environment, size in (({"SIM_ACTUAL_MAC": "112233445566"}, "16777216"),
|
||||
({"SIM_S3": "0"}, "16777216"),
|
||||
({"SIM_RESET_MODE": "hard-reset"}, "16777216"),
|
||||
({}, "8388608")):
|
||||
with self.subTest(environment=environment, size=size):
|
||||
self.log.unlink(missing_ok=True)
|
||||
result, actions = self.invoke(mode="reset-runtime", watchdog=False,
|
||||
allow=False, allow_reset=True, flash_bytes=size, environment=environment)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertNotIn("write-mem", actions)
|
||||
self.assertNotIn("--after watchdog-reset", actions)
|
||||
self.assertNotIn("ordinary-finish", actions)
|
||||
|
||||
def test_runtime_reset_rechecks_identity_and_fails_closed_without_fallback(self):
|
||||
for phase in ("S3 volatile forced-ROM bit clear", "volatile",
|
||||
"S3 watchdog finish", "reset"):
|
||||
with self.subTest(phase=phase):
|
||||
self.log.unlink(missing_ok=True)
|
||||
result, actions = self.invoke(mode="reset-runtime", watchdog=False,
|
||||
allow=False, allow_reset=True, environment={"SIM_FAIL_PHASE": phase})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(actions.count("--after watchdog-reset"), int(phase == "reset"))
|
||||
self.assertNotIn("ordinary-finish", actions)
|
||||
self.assertNotIn("write-flash", actions)
|
||||
self.assertNotIn("erase-flash", actions)
|
||||
|
||||
def test_runtime_reset_busy_owner_is_never_killed_or_reset(self):
|
||||
result, actions = self.invoke(mode="reset-runtime", watchdog=False,
|
||||
allow=False, allow_reset=True, environment={"SIM_BUSY": "1"})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("no owner will be killed", result.stderr)
|
||||
self.assertNotIn("write-mem", actions)
|
||||
self.assertNotIn("--after watchdog-reset", actions)
|
||||
self.assertNotIn("ordinary-finish", actions)
|
||||
|
||||
def test_runtime_reset_accepts_verified_eight_mib_without_write_or_erase_consent(self):
|
||||
result, actions = self.invoke(mode="reset-runtime", watchdog=False,
|
||||
allow=False, allow_reset=True, flash_bytes="8388608",
|
||||
environment={"SIM_FLASH_MB": "8"})
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertEqual(actions.count("--after watchdog-reset"), 1)
|
||||
self.assertNotIn("write-flash", actions)
|
||||
self.assertNotIn("erase-flash", actions)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Exercise application-only DFU adapter guards without any physical USB access.
|
||||
|
||||
Bash integration tests use a mock flasher, mock fuser and mock serial inventory.
|
||||
They run on native Linux/WSL; the real serial SDK and DFU tool are never invoked.
|
||||
Inventory/ZIP refusal tests also run on Windows without Bash dependencies.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOLS = ROOT / "tools/hil"
|
||||
SPEC = importlib.util.spec_from_file_location("verified_nrf_flash_adapter_test", TOOLS / "verified_nrf_flash.py")
|
||||
VERIFIER = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(VERIFIER)
|
||||
SERIAL = "SIMULATED123456"
|
||||
PORT = "/dev/ttyACM99"
|
||||
BOARD = "RAK4631"
|
||||
|
||||
|
||||
def make_package(path, extra_component=None):
|
||||
manifest = {"application": {"bin_file": "application.bin", "dat_file": "application.dat"}}
|
||||
if extra_component:
|
||||
manifest[extra_component] = {"bin_file": "application.bin", "dat_file": "application.dat"}
|
||||
with zipfile.ZipFile(path, "w") as package:
|
||||
package.writestr("manifest.json", json.dumps({"manifest": manifest}))
|
||||
package.writestr("application.bin", b"NOT-REAL-FIRMWARE")
|
||||
package.writestr("application.dat", b"NOT-A-REAL-INIT-PACKET")
|
||||
|
||||
|
||||
def inventory():
|
||||
return {"devices": {SERIAL: {"board": BOARD, "firmware_prefixes": ["RAK_4631"],
|
||||
"bootloader_prefixes": ["RAK_4631_bootloader"]}}}
|
||||
|
||||
|
||||
class MercerNrfAppPackageTest(unittest.TestCase):
|
||||
def test_unknown_physical_serial_cannot_select_an_image(self):
|
||||
with self.assertRaisesRegex(ValueError, "unrecorded USB serial"):
|
||||
VERIFIER.verify(inventory(), "UNREVIEWED123", BOARD, "RAK_4631_companion_test.zip")
|
||||
|
||||
def test_board_mismatch_cannot_reuse_the_reviewed_serial(self):
|
||||
with self.assertRaisesRegex(ValueError, "not WrongBoard"):
|
||||
VERIFIER.verify(inventory(), SERIAL, "WrongBoard", "RAK_4631_companion_test.zip")
|
||||
|
||||
def test_bootloader_and_softdevice_components_are_refused(self):
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-nrf-package-guard-") as directory:
|
||||
for component in ("bootloader", "softdevice", "softdevice_bootloader"):
|
||||
with self.subTest(component=component):
|
||||
path = Path(directory) / (component + ".zip")
|
||||
make_package(path, component)
|
||||
with self.assertRaisesRegex(ValueError, "forbids bootloader, SoftDevice"):
|
||||
VERIFIER.verify_application_zip(path)
|
||||
|
||||
|
||||
@unittest.skipUnless(os.name == "posix" and shutil.which("bash"), "native Bash required; run on Linux/WSL")
|
||||
class MercerNrfAppShellTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="meshcore-nrf-app-mock-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.work = Path(self.temporary.name)
|
||||
self.bin = self.work / "bin"
|
||||
self.bin.mkdir()
|
||||
self.adapter = self.work / "mercer_nrf_app_flash.sh"
|
||||
shutil.copyfile(TOOLS / "mercer_nrf_app_flash.sh", self.adapter)
|
||||
shutil.copyfile(TOOLS / "verified_nrf_flash.py", self.work / "verified_nrf_flash.py")
|
||||
self.flasher = self.work / "mock-mcfirmware.sh"
|
||||
self.package = self.work / "RAK_4631_companion_test.zip"
|
||||
make_package(self.package)
|
||||
self.inventory_file = self.work / "inventory.json"
|
||||
self.inventory_file.write_text(json.dumps(inventory()), encoding="utf-8")
|
||||
self.startup_marker = self.work / "STARTUP-WAS-SOURCED"
|
||||
self.dfu_marker = self.work / "MOCK-DFU-ONLY"
|
||||
self.env = dict(os.environ, SIM_STARTUP_MARKER=str(self.startup_marker),
|
||||
SIM_DFU_MARKER=str(self.dfu_marker))
|
||||
|
||||
def executable(name, text):
|
||||
path = self.bin / name
|
||||
path.write_text(text, encoding="utf-8")
|
||||
path.chmod(0o700)
|
||||
|
||||
# These commands cannot inspect, reset, open, or claim a USB endpoint.
|
||||
executable("fuser", "#!/bin/sh\nexit 1\n")
|
||||
executable("python3", "#!/bin/sh\nexec " + shlex.quote(sys.executable) + ' "$@"\n')
|
||||
for command in ("pipx", "udevadm", "socat", "stty"):
|
||||
executable(command, "#!/bin/sh\necho 'Unexpected external hardware/dependency call' >&2\nexit 89\n")
|
||||
for command in ("timeout", "stat", "perl", "unzip", "strings"):
|
||||
if not shutil.which(command):
|
||||
executable(command, "#!/bin/sh\nexit 89\n")
|
||||
self.env["PATH"] = str(self.bin) + os.pathsep + os.environ.get("PATH", "")
|
||||
|
||||
# A Python serial package exposing only a synthetic USB inventory.
|
||||
# It has no Serial constructor, making an accidental physical open fail.
|
||||
fake_modules = self.work / "python-mocks"
|
||||
serial_tools = fake_modules / "serial/tools"
|
||||
serial_tools.mkdir(parents=True)
|
||||
(serial_tools.parent / "__init__.py").write_text("", encoding="utf-8")
|
||||
(serial_tools / "__init__.py").write_text("", encoding="utf-8")
|
||||
(serial_tools / "list_ports.py").write_text(
|
||||
"from types import SimpleNamespace\n"
|
||||
f"def comports(): return [SimpleNamespace(device={PORT!r}, serial_number={SERIAL!r})]\n",
|
||||
encoding="utf-8")
|
||||
self.env["PYTHONPATH"] = str(fake_modules)
|
||||
functions = {
|
||||
"preferred_flash_serial_port": "printf '%s\\n' \"$1\"",
|
||||
"save_selected_serial_port": "return 0",
|
||||
"nrf52_validate_rak_board_pair": "return 0",
|
||||
"nrf52_selected_by_id_path": "printf '%s\\n' '/dev/serial/by-id/SIMULATED-ONLY'",
|
||||
"udev_device_property": f"if [[ \"$2\" == ID_SERIAL_SHORT ]]; then printf '%s\\n' {SERIAL}; else printf '%s\\n' 'SIMULATED-PATH'; fi",
|
||||
"nrf52_usb_path_stem": "printf '%s\\n' \"$1\"",
|
||||
"run_nrf52_dfu_package_buttonless": 'printf \'%s|%s|%s|%s\\n\' "$1" "$2" "$3" "$4" > "$SIM_DFU_MARKER"',
|
||||
}
|
||||
text = ('#!/usr/bin/env bash\n'
|
||||
'printf \'STARTUP MUST NEVER RUN\\n\' > "$SIM_STARTUP_MARKER"\n'
|
||||
'exit 93\n')
|
||||
for name, body in functions.items():
|
||||
text += f"{name}() {{\n {body}\n}}\n"
|
||||
for index in range(100):
|
||||
text += f"unused_mock_function_{index}() {{\n return 0\n}}\n"
|
||||
self.flasher.write_text(text, encoding="utf-8")
|
||||
|
||||
def invoke(self, overrides=None, *, consent=True):
|
||||
arguments = {
|
||||
"--flasher": str(self.flasher), "--port": PORT, "--workdir": str(self.work),
|
||||
"--inventory": str(self.inventory_file), "--serial": SERIAL, "--board": BOARD,
|
||||
"--artifact": str(self.package), "--sha256": hashlib.sha256(self.package.read_bytes()).hexdigest(),
|
||||
}
|
||||
arguments.update(overrides or {})
|
||||
command = [shutil.which("bash"), str(self.adapter)]
|
||||
for option, value in arguments.items():
|
||||
command.extend((option, value))
|
||||
if consent:
|
||||
command.append("--allow-write")
|
||||
result = subprocess.run(command, env=self.env, capture_output=True, text=True,
|
||||
timeout=15, check=False)
|
||||
self.assertFalse(self.startup_marker.exists(), "the flasher's startup code was sourced")
|
||||
return result
|
||||
|
||||
def assert_refused(self, result, reason):
|
||||
self.assertNotEqual(result.returncode, 0, result.stdout)
|
||||
self.assertIn(reason, result.stderr)
|
||||
self.assertFalse(self.dfu_marker.exists(), "DFU was called before all gates passed")
|
||||
|
||||
def test_missing_write_consent_fails_before_any_flasher_call(self):
|
||||
self.assert_refused(self.invoke(consent=False), "requires --allow-write")
|
||||
|
||||
def test_bad_endpoint_and_hash_syntax_fail_closed(self):
|
||||
for overrides, reason in (({"--port": "/dev/../ttyACM99"}, "local USB serial tty"),
|
||||
({"--port": "/dev/serial/by-id/anything"}, "local USB serial tty"),
|
||||
({"--sha256": "abc"}, "exactly 64 hex digits")):
|
||||
with self.subTest(overrides=overrides):
|
||||
self.assert_refused(self.invoke(overrides), reason)
|
||||
|
||||
def test_actual_artifact_hash_mismatch_prevents_dfu(self):
|
||||
self.assert_refused(self.invoke({"--sha256": "0" * 64}), "ZIP SHA256 mismatch")
|
||||
|
||||
def test_unreviewed_physical_serial_prevents_dfu(self):
|
||||
self.assert_refused(self.invoke({"--serial": "UNREVIEWED123"}), "unrecorded USB serial")
|
||||
|
||||
def test_bootloader_component_prevents_dfu_even_with_matching_hash(self):
|
||||
make_package(self.package, "bootloader")
|
||||
self.assert_refused(self.invoke(), "forbids bootloader, SoftDevice")
|
||||
|
||||
def test_definitions_only_source_reaches_only_mock_application_dfu(self):
|
||||
result = self.invoke()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertTrue(self.dfu_marker.exists())
|
||||
call = self.dfu_marker.read_text(encoding="utf-8").strip().split("|")
|
||||
self.assertEqual(call[1:], [PORT, "0", "0"])
|
||||
self.assertNotEqual(Path(call[0]), self.package)
|
||||
self.assertEqual(Path(call[0]).name, self.package.name)
|
||||
self.assertIn("Application-only DFU completed", result.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,672 @@
|
||||
"""Pure tests of the Meshtext RF runner, never its physical radio interfaces.
|
||||
|
||||
The simulated peer tests validate orchestration and truthful reporting only;
|
||||
they do not replace real RF, production codec, or stock-firmware tests.
|
||||
No PlatformIO, pyserial, stock SDK, or connected hardware is required.
|
||||
|
||||
Real hardware uses a stock SDK supporting SerialInterface(timeout=20), tested
|
||||
with 2.7.11. An older 2.7.3 environment rejected that constructor argument.
|
||||
"""
|
||||
|
||||
import base64
|
||||
from contextlib import ExitStack, redirect_stderr, redirect_stdout
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
from types import ModuleType, SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"meshtext_delivery_hil_under_test", ROOT / "tools/hil/meshtext_delivery.py")
|
||||
HIL = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(HIL)
|
||||
|
||||
|
||||
class FakeSerial:
|
||||
def __init__(self, chunks=(), short_write=False):
|
||||
self.chunks = list(chunks)
|
||||
self.short_write = short_write
|
||||
self.events = []
|
||||
|
||||
@property
|
||||
def rts(self):
|
||||
return False
|
||||
|
||||
@rts.setter
|
||||
def rts(self, value):
|
||||
self.events.append(("rts", value))
|
||||
|
||||
@property
|
||||
def dtr(self):
|
||||
return True
|
||||
|
||||
@dtr.setter
|
||||
def dtr(self, value):
|
||||
self.events.append(("dtr", value))
|
||||
|
||||
@property
|
||||
def in_waiting(self):
|
||||
return len(self.chunks[0]) if self.chunks else 0
|
||||
|
||||
def write(self, data):
|
||||
self.events.append(("write", data))
|
||||
return len(data) - int(self.short_write)
|
||||
|
||||
def flush(self):
|
||||
self.events.append(("flush",))
|
||||
|
||||
def read(self, count):
|
||||
self.events.append(("read", count))
|
||||
return self.chunks.pop(0) if self.chunks else b""
|
||||
|
||||
|
||||
class SimulatedRadios:
|
||||
"""Small state model for the runner's policies, not a codec/RF oracle."""
|
||||
|
||||
def __init__(self, *, missing_nodeinfo=False, duplicate_text=False,
|
||||
heard_echo=True, primary_frequency=909.5,
|
||||
stale_renamed_nodeinfo=False, drop_renamed_texts=0,
|
||||
missing_renamed_nodeinfo=False, duplicate_renamed_nodeinfo=False):
|
||||
self.missing_nodeinfo = missing_nodeinfo
|
||||
self.duplicate_text = duplicate_text
|
||||
self.heard_echo = heard_echo
|
||||
self.stale_renamed_nodeinfo = stale_renamed_nodeinfo
|
||||
self.drop_renamed_texts = drop_renamed_texts
|
||||
self.missing_renamed_nodeinfo = missing_renamed_nodeinfo
|
||||
self.duplicate_renamed_nodeinfo = duplicate_renamed_nodeinfo
|
||||
self.primary_frequency = primary_frequency
|
||||
self.events = []
|
||||
self.closed = []
|
||||
self.commands = []
|
||||
self.role = "CLIENT_MUTE"
|
||||
self.name = "Original HIL"
|
||||
self.radio2_writes = 0
|
||||
self.busy_reads = 0
|
||||
self.sequence = 0
|
||||
self.clock = 100.0
|
||||
owner = self
|
||||
|
||||
class Companion:
|
||||
def __init__(self, port):
|
||||
owner.companion = self
|
||||
self.max_channels = 3
|
||||
self.retry = self.heard = self.exhausted = self.tx = self.rx = 0
|
||||
self.count, self.hops = 2, 7
|
||||
self.announced = False
|
||||
|
||||
def start(self):
|
||||
return {"firmware": "SIMULATED-NOT-RF", "primary": {"node_name": owner.name}}
|
||||
|
||||
def close(self):
|
||||
owner.closed.append("companion")
|
||||
|
||||
def channel_name(self, slot):
|
||||
return ""
|
||||
|
||||
def mt_node(self):
|
||||
return 0x12345678
|
||||
|
||||
def cli(self, command):
|
||||
owner.commands.append(command)
|
||||
if command == "get radio":
|
||||
return f"> {owner.primary_frequency},500,5,5"
|
||||
if command == "get radio2":
|
||||
return "> 909.5,500,5,5,rxtx,32"
|
||||
if command == "get mt.status":
|
||||
status = "active"
|
||||
if owner.busy_reads:
|
||||
owner.busy_reads -= 1
|
||||
status = "publication busy"
|
||||
return (f"> Meshtext !12345678; {status}; manual radio2; "
|
||||
f"RX={self.rx} TX={self.tx} fail=0")
|
||||
if command == "get mt.retry":
|
||||
return (f"> retry={self.retry} heard={self.heard} exhausted={self.exhausted} "
|
||||
f"pending=0 count={self.count} advert=off")
|
||||
if command.startswith("set flood.retry.count "):
|
||||
self.count = int(command.split()[-1])
|
||||
if command.startswith("set mt.hops "):
|
||||
self.hops = int(command.split()[-1])
|
||||
if command.startswith("set radio2 "):
|
||||
owner.radio2_writes += 1
|
||||
if owner.radio2_writes > 1:
|
||||
owner.busy_reads = 2
|
||||
if command.startswith("set name "):
|
||||
name = command[len("set name "):]
|
||||
if name != owner.name:
|
||||
owner.name = name
|
||||
self.announced = False
|
||||
if command == "get name":
|
||||
return "> " + owner.name
|
||||
return "OK"
|
||||
|
||||
def send_text(self, slot, token):
|
||||
if not self.hops:
|
||||
self.tx += 1
|
||||
elif owner.role == "CLIENT" and owner.heard_echo:
|
||||
self.tx += 2
|
||||
self.retry += 1
|
||||
self.heard += 1
|
||||
else:
|
||||
self.tx += 1 + self.count
|
||||
self.retry += self.count
|
||||
self.exhausted += 1
|
||||
renamed = owner.name != "Original HIL"
|
||||
drop_text = renamed and owner.drop_renamed_texts > 0
|
||||
if drop_text:
|
||||
owner.drop_renamed_texts -= 1
|
||||
else:
|
||||
owner.append_packet(self.mt_node(), token.encode(), "TEXT_MESSAGE_APP")
|
||||
if owner.duplicate_text:
|
||||
owner.events.append(owner.events[-1])
|
||||
if not self.announced:
|
||||
self.announced = True
|
||||
self.tx += 1
|
||||
if not owner.missing_nodeinfo and not (renamed and owner.missing_renamed_nodeinfo):
|
||||
wire_name = ("Original HIL" if owner.stale_renamed_nodeinfo
|
||||
and owner.name != "Original HIL" else owner.name)
|
||||
owner.append_packet(self.mt_node(), b"simulated-user", "NODEINFO_APP", wire_name)
|
||||
if renamed and owner.duplicate_renamed_nodeinfo:
|
||||
self.tx += 1
|
||||
owner.append_packet(self.mt_node(), b"extra-user", "NODEINFO_APP", wire_name)
|
||||
|
||||
def wait_text(self, slot, sender, token, timeout):
|
||||
self.rx += 1
|
||||
return {"received": True}
|
||||
|
||||
class Stock:
|
||||
node = 0x87654321
|
||||
|
||||
def __init__(self, port):
|
||||
owner.stock = self
|
||||
self.iface = SimpleNamespace(isConnected=True,
|
||||
stream=SimpleNamespace(is_open=True))
|
||||
|
||||
def close(self):
|
||||
owner.closed.append("stock")
|
||||
|
||||
def configure_lab(self, key, role):
|
||||
owner.role = role
|
||||
return {"role": role, "rf": dict(HIL.RF)}
|
||||
|
||||
def packets_since(self, timestamp, sender):
|
||||
return [packet for when, packet in owner.events
|
||||
if when >= timestamp and packet["from"] == sender]
|
||||
|
||||
def wait_packet(self, sender, predicate, since, timeout):
|
||||
return next((packet for packet in self.packets_since(since, sender)
|
||||
if predicate(packet)), None)
|
||||
|
||||
def send_text(self, token, hops):
|
||||
return SimpleNamespace(id=123)
|
||||
|
||||
self.classes = Companion, Stock
|
||||
|
||||
def now(self):
|
||||
self.clock += 0.001
|
||||
return self.clock
|
||||
|
||||
def append_packet(self, sender, payload, port, user_name=None):
|
||||
self.sequence += 1
|
||||
self.events.append((self.now(), {"id": self.sequence, "from": sender,
|
||||
"simulated_long_name": user_name,
|
||||
"decoded": {"payload": payload, "portnum": port}}))
|
||||
|
||||
|
||||
class MeshtextDeliveryGuardrailTest(unittest.TestCase):
|
||||
def invoke_main(self, arguments):
|
||||
output, errors = io.StringIO(), io.StringIO()
|
||||
with mock.patch.object(sys, "argv", ["meshtext_delivery.py"] + arguments), \
|
||||
redirect_stdout(output), redirect_stderr(errors):
|
||||
try:
|
||||
code = HIL.main()
|
||||
except SystemExit as error:
|
||||
code = error.code
|
||||
return code, output.getvalue(), errors.getvalue()
|
||||
|
||||
def test_plan_does_not_import_hardware_dependencies_or_inspect_ports(self):
|
||||
with mock.patch.object(HIL, "dependencies", side_effect=AssertionError("dependency import")), \
|
||||
mock.patch.object(HIL, "require_idle_port", side_effect=AssertionError("port probe")):
|
||||
code, output, _ = self.invoke_main(["--plan"])
|
||||
self.assertEqual(code, 0)
|
||||
plan = json.loads(output)
|
||||
self.assertEqual(plan["rf"]["frequency_mhz"], 909.5)
|
||||
self.assertEqual(plan["rf"]["bandwidth_khz"], 500)
|
||||
self.assertEqual((plan["rf"]["sf"], plan["rf"]["cr"]), (5, 5))
|
||||
self.assertEqual(plan["echo_retry_budget"], 15)
|
||||
|
||||
def test_consent_is_required_before_run(self):
|
||||
with mock.patch.object(HIL, "run", side_effect=AssertionError("radio run")):
|
||||
code, _, error = self.invoke_main([])
|
||||
self.assertEqual(code, 2)
|
||||
self.assertIn("--allow-radio-changes is required", error)
|
||||
|
||||
def test_invalid_timing_and_selection_never_run_hardware(self):
|
||||
for arguments in (["--timeout", "0"], ["--timeout", "30.01"],
|
||||
["--quiet-seconds", "0"], ["--quiet-seconds", "31"],
|
||||
["--echo-attempts", "0"], ["--echo-attempts", "6"],
|
||||
["--case", "not-a-case"], ["--channel-slot", "256"]):
|
||||
with self.subTest(arguments=arguments), \
|
||||
mock.patch.object(HIL, "run", side_effect=AssertionError("radio run")):
|
||||
code, _, _ = self.invoke_main(["--allow-radio-changes"] + arguments)
|
||||
self.assertEqual(code, 2)
|
||||
|
||||
def test_same_port_and_existing_report_are_rejected(self):
|
||||
with tempfile.TemporaryDirectory(prefix="meshtext-hil-guard-") as directory:
|
||||
report = Path(directory) / "report.json"
|
||||
with mock.patch.object(HIL, "run", side_effect=AssertionError("radio run")):
|
||||
common = ["--allow-radio-changes", "--companion-port", "SIMULATED-A",
|
||||
"--stock-port", "SIMULATED-A", "--report", str(report)]
|
||||
code, _, error = self.invoke_main(common)
|
||||
self.assertEqual(code, 2)
|
||||
self.assertIn("ports must be distinct", error)
|
||||
report.write_text("preserve-me", encoding="utf-8")
|
||||
common[4] = "SIMULATED-B"
|
||||
code, _, error = self.invoke_main(common)
|
||||
self.assertEqual(code, 2)
|
||||
self.assertIn("fresh report", error)
|
||||
self.assertEqual(report.read_text(encoding="utf-8"), "preserve-me")
|
||||
|
||||
def test_secret_values_never_enter_cli_labels_or_rejection_reasons(self):
|
||||
for size in (16, 32):
|
||||
key = bytes(range(size)).hex()
|
||||
command = "set mt.channel 1 mt-labtest " + key
|
||||
self.assertEqual(HIL.cli_command_label(command), "set mt.channel")
|
||||
reply = HIL.safe_cli_reply(command, "Error: echoed " + command)
|
||||
self.assertNotIn(key, reply)
|
||||
self.assertIn("<redacted>", reply)
|
||||
self.assertEqual(HIL.cli_command_label("normalradio"), "normalradio")
|
||||
self.assertEqual(HIL.cli_command_label("set tempradio2 off"), "set tempradio2")
|
||||
self.assertEqual(HIL.safe_cli_reply("normalradio", "Error: invalid preamble"),
|
||||
"Error: invalid preamble")
|
||||
|
||||
def test_counter_parsing_rejects_missing_fields(self):
|
||||
self.assertEqual(HIL.retry_stats("> retry=2 heard=1 exhausted=0 pending=0 count=15 advert=off")["heard"], 1)
|
||||
self.assertEqual(HIL.tx_stats("RX=3 TX=4 fail=0"), {"rx": 3, "tx": 4, "fail": 0})
|
||||
for parser, reply in ((HIL.retry_stats, "retry=2 pending=0"),
|
||||
(HIL.tx_stats, "TX=4 fail=0")):
|
||||
with self.subTest(reply=reply), self.assertRaises(HIL.Failure):
|
||||
parser(reply)
|
||||
|
||||
def test_idle_wait_has_a_real_deadline(self):
|
||||
observed = {"delivery": {"pending": 1}}
|
||||
with mock.patch.object(HIL, "snapshot", return_value=observed) as snapshot, \
|
||||
mock.patch.object(HIL.time, "monotonic", side_effect=(0, 0.1, 0.2, 0.3)), \
|
||||
mock.patch.object(HIL.time, "sleep"):
|
||||
with self.assertRaisesRegex(HIL.Failure, "did not become idle"):
|
||||
HIL.wait_idle(object(), 0.25)
|
||||
self.assertEqual(snapshot.call_count, 2)
|
||||
|
||||
def test_publication_poll_is_read_only_and_time_bounded(self):
|
||||
companion = SimpleNamespace(cli=mock.Mock(return_value="> publication busy; RX=0 TX=0 fail=0"))
|
||||
with mock.patch.object(HIL.time, "monotonic", side_effect=(0, 0.1, 0.2, 0.3)), \
|
||||
mock.patch.object(HIL.time, "sleep"), \
|
||||
self.assertRaisesRegex(HIL.Failure, "did not become active"):
|
||||
HIL.wait_active(companion, 0.25)
|
||||
self.assertEqual(companion.cli.call_args_list, [mock.call("get mt.status")] * 2)
|
||||
|
||||
|
||||
class MeshtextDeliveryUsbModeTest(unittest.TestCase):
|
||||
def test_explicit_terminal_stop_uses_safe_line_order_and_drains_plaintext(self):
|
||||
port = FakeSerial((b"> +++MESHCORE-TERM-STOP\r\n", b"Binary mode\r\n"))
|
||||
with mock.patch.object(HIL.time, "sleep") as sleep:
|
||||
result = HIL.enter_binary_mode(port)
|
||||
self.assertEqual(port.events[:4], [("rts", False), ("dtr", True),
|
||||
("write", b"+++MESHCORE-TERM-STOP\r"), ("flush",)])
|
||||
sleep.assert_called_once_with(0.3)
|
||||
self.assertEqual(result["discarded_terminal_bytes"], 38)
|
||||
self.assertNotIn("Binary mode", str(result))
|
||||
|
||||
def test_already_binary_requires_no_ascii_acknowledgement(self):
|
||||
with mock.patch.object(HIL.time, "sleep"):
|
||||
self.assertEqual(HIL.enter_binary_mode(FakeSerial())["discarded_terminal_bytes"], 0)
|
||||
|
||||
def test_short_write_and_logging_owner_fail_explicitly(self):
|
||||
for port, reason in ((FakeSerial(short_write=True), "incomplete"),
|
||||
(FakeSerial((b"ERROR: set usb.logging off before Binary mode\r\n> ",)), "USB logging owns")):
|
||||
with self.subTest(reason=reason), mock.patch.object(HIL.time, "sleep"), \
|
||||
self.assertRaisesRegex(HIL.Failure, reason):
|
||||
HIL.enter_binary_mode(port)
|
||||
|
||||
def test_terminal_drain_is_byte_bounded(self):
|
||||
port = FakeSerial([b"x" * 4096] * 17)
|
||||
with mock.patch.object(HIL.time, "sleep"), \
|
||||
mock.patch.object(HIL.time, "monotonic", return_value=0), \
|
||||
self.assertRaisesRegex(HIL.Failure, "bounded negotiation drain"):
|
||||
HIL.enter_binary_mode(port)
|
||||
|
||||
def test_terminal_drain_is_time_bounded_even_with_continuous_output(self):
|
||||
port = FakeSerial([b"x"] * 20)
|
||||
with mock.patch.object(HIL.time, "sleep"), \
|
||||
mock.patch.object(HIL.time, "monotonic", side_effect=(0, 0.1, 0.5, 1.1)):
|
||||
result = HIL.enter_binary_mode(port)
|
||||
self.assertEqual(result["discarded_terminal_bytes"], 2)
|
||||
self.assertEqual(len(port.chunks), 18)
|
||||
|
||||
|
||||
class MeshtextDeliveryStockSettlingTest(unittest.TestCase):
|
||||
class Peer:
|
||||
def __init__(self, outcomes):
|
||||
self.outcomes = iter(outcomes)
|
||||
self.iface = None
|
||||
self.attempts = 0
|
||||
self.closed = 0
|
||||
|
||||
def close(self):
|
||||
self.closed += 1
|
||||
|
||||
def connect(self):
|
||||
self.attempts += 1
|
||||
outcome = next(self.outcomes)
|
||||
if isinstance(outcome, Exception):
|
||||
raise outcome
|
||||
self.iface = SimpleNamespace(localNode=outcome, close=self.close)
|
||||
|
||||
def test_stale_readback_reconnects_then_accepts_committed_settings(self):
|
||||
peer = self.Peer(["stale", "settled"])
|
||||
with mock.patch.object(HIL.time, "sleep") as sleep:
|
||||
result = HIL.reconnect_stock_readback(
|
||||
peer, lambda node: ["channel.private_key_match"] if node == "stale" else [])
|
||||
self.assertEqual(result, {"attempts": 2, "retry_history": [
|
||||
{"attempt": 1, "mismatched_fields": ["channel.private_key_match"]}]})
|
||||
self.assertEqual(peer.closed, 1)
|
||||
self.assertIsNotNone(peer.iface)
|
||||
sleep.assert_called_once_with(2)
|
||||
|
||||
def test_transient_connect_errors_are_retried_without_retaining_secret_text(self):
|
||||
key = bytes(range(16)).hex()
|
||||
peer = self.Peer([OSError("unrelated diagnostic " + key), "stale", "settled"])
|
||||
with mock.patch.object(HIL.time, "sleep") as sleep:
|
||||
result = HIL.reconnect_stock_readback(
|
||||
peer, lambda node: ["lora.override_frequency"] if node == "stale" else [])
|
||||
self.assertEqual(result["attempts"], 3)
|
||||
self.assertEqual(result["retry_history"][0]["mismatched_fields"],
|
||||
["connect/readback error: OSError"])
|
||||
self.assertNotIn(key, json.dumps(result))
|
||||
self.assertEqual(sleep.call_args_list, [mock.call(2), mock.call(2)])
|
||||
|
||||
def test_bad_settings_stop_after_three_attempts_with_only_field_names(self):
|
||||
peer = self.Peer(["wrong"] * 3)
|
||||
with mock.patch.object(HIL.time, "sleep") as sleep, \
|
||||
self.assertRaisesRegex(HIL.Failure, "three bounded reconnects.*lora.override_frequency"):
|
||||
HIL.reconnect_stock_readback(peer, lambda node: ["lora.override_frequency"])
|
||||
self.assertEqual(peer.attempts, 3)
|
||||
self.assertEqual(peer.closed, 3)
|
||||
self.assertIsNone(peer.iface)
|
||||
self.assertEqual(sleep.call_count, 2)
|
||||
|
||||
def test_old_sdk_constructor_error_is_not_reported_as_rf_success(self):
|
||||
peer = self.Peer([TypeError("SerialInterface got unexpected keyword argument timeout")] * 3)
|
||||
with mock.patch.object(HIL.time, "sleep"), \
|
||||
self.assertRaisesRegex(HIL.Failure, "connect/readback error: TypeError"):
|
||||
HIL.reconnect_stock_readback(peer, lambda node: [])
|
||||
self.assertEqual(peer.attempts, 3)
|
||||
|
||||
def test_quiet_requires_live_sdk_and_serial_indicators(self):
|
||||
event = mock.Mock()
|
||||
event.is_set.return_value = True
|
||||
peer = SimpleNamespace(iface=SimpleNamespace(isConnected=event,
|
||||
stream=SimpleNamespace(is_open=True)))
|
||||
self.assertEqual(HIL.require_stock_connected(peer),
|
||||
{"sdk_connected": True, "serial_open": True})
|
||||
event.is_set.return_value = False
|
||||
with self.assertRaisesRegex(HIL.Failure, "disconnected"):
|
||||
HIL.require_stock_connected(peer)
|
||||
event.is_set.return_value = True
|
||||
peer.iface.stream.is_open = False
|
||||
with self.assertRaisesRegex(HIL.Failure, "disconnected"):
|
||||
HIL.require_stock_connected(peer)
|
||||
|
||||
def test_missing_health_indicator_cannot_pass_as_quiet(self):
|
||||
with self.assertRaisesRegex(HIL.Failure, "no supported connection-health"):
|
||||
HIL.require_stock_connected(SimpleNamespace(iface=object()))
|
||||
with self.assertRaisesRegex(HIL.Failure, "disconnected"):
|
||||
HIL.require_stock_connected(SimpleNamespace(iface=None))
|
||||
|
||||
def test_real_configuration_method_waits_for_deferred_reboot_before_reconnect(self):
|
||||
# Execute the runner's real transaction/reconnect code with a tiny SDK
|
||||
# adapter. Any accidentally opened physical port raises immediately.
|
||||
events = []
|
||||
descriptor = SimpleNamespace(fields_by_name={})
|
||||
settings = SimpleNamespace(name="old", psk=b"old", uplink_enabled=True,
|
||||
downlink_enabled=True)
|
||||
node = SimpleNamespace(nodeNum=42,
|
||||
channels=[SimpleNamespace(role=1, settings=settings)],
|
||||
localConfig=SimpleNamespace(device=SimpleNamespace(DESCRIPTOR=descriptor),
|
||||
position=SimpleNamespace(DESCRIPTOR=descriptor), lora=SimpleNamespace()),
|
||||
moduleConfig=SimpleNamespace(telemetry=None),
|
||||
ensureSessionKey=mock.Mock(), beginSettingsTransaction=mock.Mock(),
|
||||
writeConfig=mock.Mock(), writeChannel=mock.Mock(),
|
||||
commitSettingsTransaction=lambda: events.append(("commit",)))
|
||||
|
||||
def interface():
|
||||
return SimpleNamespace(localNode=node,
|
||||
_getOrCreateByNum=lambda number: {"adminSessionPassKey": b"session-ready"},
|
||||
close=lambda: events.append(("close",)))
|
||||
|
||||
class StockAdapter:
|
||||
def __init__(self, port):
|
||||
self.iface = interface()
|
||||
|
||||
def connect(self):
|
||||
events.append(("connect",))
|
||||
self.iface = interface()
|
||||
|
||||
def identity(self):
|
||||
return {"node": "!0000002a"}
|
||||
|
||||
def module(name, **attributes):
|
||||
result = ModuleType(name)
|
||||
result.__dict__.update(attributes)
|
||||
return result
|
||||
|
||||
device_config = SimpleNamespace(Role=SimpleNamespace(Value=lambda name: {"CLIENT_MUTE": 1}[name]),
|
||||
RebroadcastMode=SimpleNamespace(Value=lambda name: {"ALL": 0}[name]))
|
||||
config = SimpleNamespace(Config=SimpleNamespace(DeviceConfig=device_config,
|
||||
LoRaConfig=SimpleNamespace(US=1)))
|
||||
channel = SimpleNamespace(Channel=SimpleNamespace(PRIMARY=1, DISABLED=0))
|
||||
hardware_forbidden = mock.Mock(side_effect=AssertionError("physical serial access"))
|
||||
modules = {
|
||||
"serial": module("serial", Serial=hardware_forbidden),
|
||||
"meshtext_auto_radio2": module("meshtext_auto_radio2", Companion=object, StockPeer=StockAdapter),
|
||||
"esp32_companion_serial_stress": module("esp32_companion_serial_stress",
|
||||
DeviceFrameReader=mock.Mock(), TransportCounters=mock.Mock()),
|
||||
"serial_session": module("serial_session", open_configured_session=hardware_forbidden),
|
||||
"meshtastic": module("meshtastic"),
|
||||
"meshtastic.protobuf": module("meshtastic.protobuf", channel_pb2=channel, config_pb2=config),
|
||||
"meshtastic.util": module("meshtastic.util", to_node_num=lambda value: value),
|
||||
}
|
||||
with mock.patch.dict(sys.modules, modules), \
|
||||
mock.patch.object(HIL.time, "sleep", side_effect=lambda seconds: events.append(("sleep", seconds))):
|
||||
_, Stock = HIL.dependencies()
|
||||
result = Stock("SIMULATED-ONLY").configure_lab(bytes(range(16)), "CLIENT_MUTE")
|
||||
hardware_forbidden.assert_not_called()
|
||||
committed = events.index(("commit",))
|
||||
self.assertEqual(events[committed + 1:committed + 4],
|
||||
[("sleep", 20), ("close",), ("connect",)])
|
||||
self.assertTrue(all(event[1] in (0.75, 20) for event in events if event[0] == "sleep"))
|
||||
self.assertEqual(result["readback"]["attempts"], 1)
|
||||
|
||||
|
||||
class MeshtextDeliveryMockFlowTest(unittest.TestCase):
|
||||
def run_simulation(self, radios, case="all", key_bits=128):
|
||||
key = bytes(range(key_bits // 8))
|
||||
with tempfile.TemporaryDirectory(prefix="meshtext-hil-simulated-") as directory, ExitStack() as stack:
|
||||
report = Path(directory) / "report.json"
|
||||
args = SimpleNamespace(case=case, key_bits=key_bits, report=report,
|
||||
companion_port="SIMULATED-DUT", stock_port="SIMULATED-STOCK", channel_slot=1,
|
||||
quiet_seconds=0.01, timeout=1, echo_attempts=3)
|
||||
stack.enter_context(mock.patch.object(HIL, "dependencies", return_value=radios.classes))
|
||||
stack.enter_context(mock.patch.object(HIL, "require_idle_port"))
|
||||
stack.enter_context(mock.patch.object(HIL.importlib.metadata, "version", return_value="SIMULATED"))
|
||||
stack.enter_context(mock.patch.object(HIL.secrets, "token_bytes", return_value=key))
|
||||
stack.enter_context(mock.patch.object(HIL.secrets, "token_hex", return_value="0123abcd"))
|
||||
stack.enter_context(mock.patch.object(HIL.time, "sleep"))
|
||||
stack.enter_context(mock.patch.object(HIL.time, "monotonic", side_effect=radios.now))
|
||||
stack.enter_context(mock.patch.object(HIL, "inspect_nodeinfo",
|
||||
side_effect=lambda packet, node: {"id": "!12345678",
|
||||
"long_name": packet["simulated_long_name"],
|
||||
"payload_type": "SIMULATED User; no protobuf/RF claim"}))
|
||||
stack.enter_context(redirect_stdout(io.StringIO()))
|
||||
result = HIL.run(args)
|
||||
saved = report.read_text(encoding="utf-8")
|
||||
self.assertEqual(result, json.loads(saved))
|
||||
self.assertNotIn(key.hex(), saved)
|
||||
self.assertNotIn(base64.b64encode(key).decode(), saved)
|
||||
return result
|
||||
|
||||
def test_all_cases_success_and_safe_setup_commands(self):
|
||||
for bits in (128, 256):
|
||||
with self.subTest(key_bits=bits):
|
||||
radios = SimulatedRadios()
|
||||
result = self.run_simulation(radios, key_bits=bits)
|
||||
self.assertEqual(result["result"], "PASS", result.get("failure"))
|
||||
self.assertEqual(len(result["cases"]), 9)
|
||||
self.assertTrue(all(case["result"] == "PASS" for case in result["cases"]))
|
||||
self.assertIn("normalradio", radios.commands)
|
||||
self.assertNotIn("set tempradio off", radios.commands)
|
||||
self.assertIn("set flood.retry.count 15", radios.commands)
|
||||
self.assertEqual(sorted(radios.closed), ["companion", "stock"])
|
||||
self.assertFalse(result["settings_restored"])
|
||||
self.assertEqual(radios.name, "Original HIL")
|
||||
|
||||
def test_quiet_only_never_sends_a_chat(self):
|
||||
radios = SimulatedRadios()
|
||||
result = self.run_simulation(radios, "quiet")
|
||||
self.assertEqual(result["result"], "PASS")
|
||||
self.assertEqual([case["name"] for case in result["cases"]], ["quiet"])
|
||||
self.assertEqual(radios.events, [])
|
||||
self.assertEqual(radios.companion.tx, 0)
|
||||
|
||||
def test_new_cases_work_as_a_subset_with_read_only_reactivation_and_name_restore(self):
|
||||
radios = SimulatedRadios()
|
||||
result = self.run_simulation(radios, "same-tuple,rename")
|
||||
self.assertEqual(result["result"], "PASS", result.get("failure"))
|
||||
self.assertEqual([case["name"] for case in result["cases"]], ["first-use",
|
||||
"same-tuple-publication-recovery", "rename-rearms-first-chat-nodeinfo"])
|
||||
same_tuple, rename = result["cases"][-2:]
|
||||
self.assertGreater(same_tuple["publication"]["polls"], 1)
|
||||
self.assertEqual(same_tuple["traffic_delta"]["tx"], 0)
|
||||
self.assertEqual(rename["traffic_delta"]["tx"], 2)
|
||||
self.assertEqual(rename["nodeinfo"]["long_name"], rename["test_name"])
|
||||
self.assertTrue(rename["original_name_restored"])
|
||||
self.assertEqual(rename["restore_traffic_delta"]["tx"], 0)
|
||||
self.assertEqual(radios.name, "Original HIL")
|
||||
self.assertEqual(radios.companion.hops, 7)
|
||||
|
||||
def test_rename_restores_original_name_even_when_wire_metadata_is_wrong(self):
|
||||
radios = SimulatedRadios(stale_renamed_nodeinfo=True)
|
||||
result = self.run_simulation(radios, "rename")
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertIn("old long name", result["failure"]["message"])
|
||||
rename = result["cases"][-1]
|
||||
self.assertEqual(rename["result"], "FAIL")
|
||||
self.assertTrue(rename["original_name_restored"])
|
||||
self.assertEqual(radios.name, "Original HIL")
|
||||
self.assertEqual(rename["restore_traffic_delta"]["tx"], 0)
|
||||
|
||||
def test_rename_records_first_chat_loss_and_accepts_its_one_nodeinfo(self):
|
||||
radios = SimulatedRadios(drop_renamed_texts=1)
|
||||
result = self.run_simulation(radios, "rename")
|
||||
self.assertEqual(result["result"], "PASS", result.get("failure"))
|
||||
rename = result["cases"][-1]
|
||||
self.assertEqual(rename["attempted_texts"], 2)
|
||||
self.assertEqual(rename["received_texts"], 1)
|
||||
self.assertEqual([probe["received"] for probe in rename["probes"]], [False, True])
|
||||
self.assertIsNone(rename["probes"][0]["packet_id"])
|
||||
self.assertIsNotNone(rename["probes"][1]["packet_id"])
|
||||
self.assertEqual(rename["decoded_nodeinfo_events"], 1)
|
||||
self.assertEqual(rename["packets"][0]["port"], "NODEINFO_APP")
|
||||
self.assertEqual(rename["traffic_delta"]["tx"], 3)
|
||||
self.assertTrue(rename["original_name_restored"])
|
||||
|
||||
def test_rename_all_three_chats_lost_is_still_a_failed_rf_test(self):
|
||||
radios = SimulatedRadios(drop_renamed_texts=3)
|
||||
result = self.run_simulation(radios, "rename")
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertIn("any of three", result["failure"]["message"])
|
||||
rename = result["cases"][-1]
|
||||
self.assertEqual(rename["attempted_texts"], 3)
|
||||
self.assertEqual(rename["received_texts"], 0)
|
||||
self.assertEqual(rename["decoded_nodeinfo_events"], 1)
|
||||
self.assertEqual(rename["traffic_delta"]["tx"], 4)
|
||||
self.assertTrue(rename["original_name_restored"])
|
||||
self.assertTrue(all(not probe["received"] for probe in rename["probes"]))
|
||||
|
||||
def test_rename_missing_nodeinfo_is_not_masked_by_extra_successful_chats(self):
|
||||
radios = SimulatedRadios(missing_renamed_nodeinfo=True)
|
||||
result = self.run_simulation(radios, "rename")
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertIn("exactly one observed", result["failure"]["message"])
|
||||
rename = result["cases"][-1]
|
||||
self.assertEqual(rename["attempted_texts"], 3)
|
||||
self.assertEqual(rename["received_texts"], 3)
|
||||
self.assertEqual(rename["decoded_nodeinfo_events"], 0)
|
||||
self.assertTrue(rename["original_name_restored"])
|
||||
|
||||
def test_rename_extra_nodeinfo_is_never_accepted_as_one_time_announcement(self):
|
||||
radios = SimulatedRadios(duplicate_renamed_nodeinfo=True)
|
||||
result = self.run_simulation(radios, "rename")
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertIn("exactly one observed", result["failure"]["message"])
|
||||
rename = result["cases"][-1]
|
||||
self.assertEqual(rename["decoded_nodeinfo_events"], 2)
|
||||
self.assertTrue(rename["original_name_restored"])
|
||||
|
||||
def test_missing_metadata_fails_and_saves_partial_report(self):
|
||||
radios = SimulatedRadios(missing_nodeinfo=True)
|
||||
result = self.run_simulation(radios, "first-use")
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertIn("automatic NodeInfo", result["failure"]["message"])
|
||||
self.assertEqual(result["cases"][-1]["result"], "FAIL")
|
||||
self.assertIn("finished_utc", result)
|
||||
self.assertEqual(sorted(radios.closed), ["companion", "stock"])
|
||||
|
||||
def test_duplicate_user_delivery_fails_exhaustion_case(self):
|
||||
result = self.run_simulation(SimulatedRadios(duplicate_text=True), "exhaustion")
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertIn("duplicate user text", result["failure"]["message"])
|
||||
self.assertEqual(result["cases"][-1]["decoded_text_events"], 2)
|
||||
|
||||
def test_received_chat_without_heard_echo_never_passes_cancellation(self):
|
||||
result = self.run_simulation(SimulatedRadios(heard_echo=False), "echo")
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
echo = result["cases"][-1]
|
||||
self.assertEqual(echo["name"], "heard-repeat-cancellation")
|
||||
self.assertEqual(len(echo["attempts"]), 3)
|
||||
self.assertTrue(all(attempt["received_by_stock"] for attempt in echo["attempts"]))
|
||||
self.assertTrue(all(attempt["delivery_delta"]["heard"] == 0 for attempt in echo["attempts"]))
|
||||
|
||||
def test_wrong_primary_is_rejected_before_any_setting_write(self):
|
||||
radios = SimulatedRadios(primary_frequency=910.525)
|
||||
result = self.run_simulation(radios)
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertIn("preconfigure primary", result["failure"]["message"])
|
||||
self.assertFalse(any(command.startswith(("set ", "delete ")) for command in radios.commands))
|
||||
self.assertEqual(radios.closed, ["companion"])
|
||||
|
||||
def test_failure_report_redacts_raw_key_bytes_hex_and_base64(self):
|
||||
key = bytes(range(16))
|
||||
message = f"bad setup {key.hex()} {key!r} {base64.b64encode(key).decode()}"
|
||||
with tempfile.TemporaryDirectory(prefix="meshtext-hil-secret-") as directory, \
|
||||
mock.patch.object(HIL.secrets, "token_bytes", return_value=key), \
|
||||
mock.patch.object(HIL.secrets, "token_hex", return_value="0123abcd"), \
|
||||
mock.patch.object(HIL, "dependencies", side_effect=RuntimeError(message)), \
|
||||
redirect_stdout(io.StringIO()):
|
||||
args = SimpleNamespace(case="all", key_bits=128, report=Path(directory) / "report.json")
|
||||
result = HIL.run(args)
|
||||
saved = args.report.read_text(encoding="utf-8")
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertNotIn(key.hex(), saved)
|
||||
self.assertNotIn(repr(key), result["failure"]["message"])
|
||||
self.assertNotIn(base64.b64encode(key).decode(), saved)
|
||||
self.assertIn("<redacted>", saved)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Compile actual timing policy with an opt-in Meshtext RF dwell experiment.
|
||||
|
||||
No PlatformIO or hardware is used. Default builds retain the measured 4.6-symbol
|
||||
policy; the HIL override changes only Meshtext, never MeshCore or Ethernet.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HARNESS = r'''
|
||||
#include <RadioProfiles.h>
|
||||
#include <cstdio>
|
||||
#include <initializer_list>
|
||||
|
||||
int main() {
|
||||
mesh::RadioProfileParams p;
|
||||
p.freq = 909.5f; p.bw = 500; p.sf = 5; p.cr = 5;
|
||||
for (auto protocol : {mesh::RadioProfileProtocol::MeshCore,
|
||||
mesh::RadioProfileProtocol::Meshtext,
|
||||
mesh::RadioProfileProtocol::Ethernet}) {
|
||||
p.protocol = protocol;
|
||||
std::printf("%lu %lu\n",
|
||||
static_cast<unsigned long>(mesh::RadioProfiles::minimumListenUs(p, false)),
|
||||
static_cast<unsigned long>(mesh::RadioProfiles::minimumListenUs(p, true)));
|
||||
}
|
||||
// Existing invalid-modem rejection must remain intact with the override.
|
||||
p.protocol = mesh::RadioProfileProtocol::Meshtext; p.bw = 0;
|
||||
std::printf("%lu\n", static_cast<unsigned long>(mesh::RadioProfiles::minimumListenUs(p)));
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class MeshtextListenHilTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not cls.compiler:
|
||||
raise unittest.SkipTest("a native C++17 compiler is required")
|
||||
|
||||
def compile_case(self, macro=None):
|
||||
temporary = tempfile.TemporaryDirectory(prefix="meshtext-listen-hil-")
|
||||
self.addCleanup(temporary.cleanup)
|
||||
folder = Path(temporary.name)
|
||||
source = folder / "listen.cpp"
|
||||
binary = folder / ("listen.exe" if os.name == "nt" else "listen")
|
||||
source.write_text(HARNESS, encoding="utf-8")
|
||||
command = [self.compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-I", str(ROOT / "src"), str(source), "-o", str(binary)]
|
||||
if macro is not None:
|
||||
command.append("-DMESH_HIL_MESHTEXT_LISTEN_SYMBOLS=" + str(macro))
|
||||
result = subprocess.run(command, text=True, capture_output=True, timeout=30, check=False)
|
||||
return result, binary
|
||||
|
||||
def run_case(self, macro=None):
|
||||
compiled, binary = self.compile_case(macro)
|
||||
self.assertEqual(compiled.returncode, 0, compiled.stdout + compiled.stderr)
|
||||
result = subprocess.run([str(binary)], text=True, capture_output=True, timeout=10, check=False)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return [tuple(map(int, line.split())) for line in result.stdout.splitlines()]
|
||||
|
||||
def test_default_keeps_all_protocols_at_4_6_symbols(self):
|
||||
# SF5/BW500 = 64 us/symbol; ceil(4.6 * 64) = 295 us.
|
||||
self.assertEqual(self.run_case(), [(295, 295), (295, 295), (295, 295), (0,)])
|
||||
|
||||
def test_twelve_symbol_hil_changes_only_meshtext_to_768_us(self):
|
||||
self.assertEqual(self.run_case(12), [(295, 295), (768, 768), (295, 295), (0,)])
|
||||
|
||||
def test_smaller_override_cannot_shorten_the_existing_listen_window(self):
|
||||
self.assertEqual(self.run_case(1), [(295, 295), (295, 295), (295, 295), (0,)])
|
||||
|
||||
def test_fractional_override_is_supported_and_does_not_change_other_protocols(self):
|
||||
self.assertEqual(self.run_case(8.5), [(295, 295), (544, 544), (295, 295), (0,)])
|
||||
|
||||
def test_upper_bound_is_accepted_for_meshtext_only(self):
|
||||
self.assertEqual(self.run_case(64), [(295, 295), (4096, 4096), (295, 295), (0,)])
|
||||
|
||||
def test_zero_negative_and_over_limit_macros_are_compile_time_errors(self):
|
||||
for macro in (0, -1, 65):
|
||||
with self.subTest(macro=macro):
|
||||
compiled, _ = self.compile_case(macro)
|
||||
self.assertNotEqual(compiled.returncode, 0)
|
||||
self.assertIn("MESH_HIL_MESHTEXT_LISTEN_SYMBOLS must be greater than 0 and at most 64",
|
||||
compiled.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,288 @@
|
||||
"""Offline benchmark policy/orchestration tests; never open a radio or SDK."""
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOLS = ROOT / "tools/hil"
|
||||
with mock.patch.object(sys, "path", [str(TOOLS), *sys.path]):
|
||||
SPEC = importlib.util.spec_from_file_location("meshtext_speed_under_test", TOOLS / "meshtext_speed.py")
|
||||
SPEED = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(SPEED)
|
||||
|
||||
|
||||
class Simulation:
|
||||
def __init__(self, *, guard=SPEED.GUARD, primary=910.525, primary_tx=0,
|
||||
stock_frequency=909.5, queue_stuck=False, drop_outbound=False, drop_inbound=False):
|
||||
self.now = 100.0
|
||||
self.guard, self.primary, self.primary_tx = guard, primary, primary_tx
|
||||
self.queue_stuck, self.drop_outbound, self.drop_inbound = queue_stuck, drop_outbound, drop_inbound
|
||||
self.commands, self.stock_writes, self.sent, self.closed = [], [], [], []
|
||||
self.frames, self.events, self.sf, self.name, self.announced = [], [], 5, "", False
|
||||
self.tx, self.rx, self.stock_sequence = 0, 0, 0
|
||||
owner = self
|
||||
|
||||
class Companion:
|
||||
max_channels = 2
|
||||
|
||||
def __init__(self, port):
|
||||
owner.companion = self
|
||||
|
||||
def start(self):
|
||||
return {"model": "SIMULATED", "primary": {"node_name": "Test"}}
|
||||
|
||||
def close(self):
|
||||
owner.closed.append("companion")
|
||||
|
||||
def channel_name(self, index):
|
||||
return owner.name if index == 1 else ""
|
||||
|
||||
def mt_node(self):
|
||||
return 0x12345678
|
||||
|
||||
def cli(self, command):
|
||||
owner.commands.append(command)
|
||||
if command == "get lab.tx":
|
||||
return "> " + owner.guard
|
||||
if command == "get radio":
|
||||
return f"> {owner.primary},62.5,7,5"
|
||||
if command == "get radio2.status":
|
||||
return f"> rxtx; RX=0,{owner.rx} TX={owner.primary_tx},{owner.tx} preamble=32,16"
|
||||
if command == "get radio2":
|
||||
return f"> 909.5,500,{owner.sf},5,rxtx,32"
|
||||
if command == "get mt.hops":
|
||||
return "> 0"
|
||||
if command == "get mt.status":
|
||||
return f"> Meshtext !12345678; active; RX={owner.rx} TX={owner.tx} fail=0"
|
||||
if command == "get mt.retry":
|
||||
return "> retry=0 heard=0 exhausted=0 pending=0 count=0 advert=off"
|
||||
if command.startswith("set radio2 "):
|
||||
owner.sf = int(command.split()[2].split(",")[2])
|
||||
if command.startswith("set mt.channel "):
|
||||
owner.name, owner.announced = "mt-labtest", False
|
||||
if command.startswith("delete mt.channel "):
|
||||
owner.name = ""
|
||||
return "OK"
|
||||
|
||||
def send_text(self, slot, token):
|
||||
assert 7 + len(token.encode()) <= 176, "Companion USB payload envelope overflow"
|
||||
owner.sent.append(("companion", token))
|
||||
owner.tx += 1
|
||||
if not owner.announced:
|
||||
owner.announced = True
|
||||
owner.tx += 1
|
||||
owner.events.append((owner.now, {"from": 0x12345678, "id": len(owner.sent),
|
||||
"decoded": {"payload": token.encode(), "portnum": "TEXT_MESSAGE_APP"}}))
|
||||
|
||||
def request(self, payload, expected, timeout):
|
||||
assert payload == b"\x0a"
|
||||
return owner.frames.pop(0) if owner.frames else b"\x0a"
|
||||
|
||||
class Node:
|
||||
def __init__(self):
|
||||
self.localConfig = SimpleNamespace(
|
||||
lora=SimpleNamespace(use_preset=False, override_frequency=stock_frequency,
|
||||
bandwidth=500, coding_rate=5, spread_factor=5, frequency_offset=0,
|
||||
hop_limit=0, tx_power=2, tx_enabled=True, channel_num=0),
|
||||
device=SimpleNamespace(role=1))
|
||||
self.channels = [SimpleNamespace(role=1, settings=SimpleNamespace(name="labtest", psk=b"a"*16))]
|
||||
|
||||
def beginSettingsTransaction(self):
|
||||
owner.stock_writes.append("begin")
|
||||
|
||||
def writeConfig(self, section):
|
||||
owner.stock_writes.append(section)
|
||||
|
||||
def commitSettingsTransaction(self):
|
||||
owner.stock_writes.append("commit")
|
||||
|
||||
class Interface:
|
||||
def __init__(self, node):
|
||||
self.localNode = node
|
||||
self.isConnected = True
|
||||
self.stream = SimpleNamespace(is_open=True)
|
||||
self.queue = {}
|
||||
self.queueStatus = SimpleNamespace(free=4, maxlen=4, res=0, mesh_packet_id=0)
|
||||
|
||||
def close(self):
|
||||
self.isConnected = False
|
||||
self.stream.is_open = False
|
||||
|
||||
class Stock:
|
||||
node = 0x11223344
|
||||
|
||||
def __init__(self, port):
|
||||
self.saved_node = Node()
|
||||
self.connect()
|
||||
owner.stock = self
|
||||
|
||||
def connect(self):
|
||||
self.iface = Interface(self.saved_node)
|
||||
|
||||
def close(self):
|
||||
owner.closed.append("stock")
|
||||
|
||||
def configure_lab(self, key, role):
|
||||
assert role == "CLIENT_MUTE"
|
||||
self.saved_node.channels[0].settings.psk = key
|
||||
owner.stock_writes.append("suppression")
|
||||
return {"role": role, "simulated": True}
|
||||
|
||||
def send_text(self, token, hops):
|
||||
assert hops == 0
|
||||
owner.sent.append(("stock", token))
|
||||
owner.stock_sequence += 1
|
||||
identity = owner.stock_sequence
|
||||
if owner.queue_stuck:
|
||||
self.iface.queue[identity] = object()
|
||||
self.iface.queueStatus.mesh_packet_id = identity
|
||||
if not owner.drop_inbound:
|
||||
prefix = b"!11223344: "
|
||||
text = (prefix + token.encode())[:165]
|
||||
owner.frames.append(bytes((17, 0, 0, 0, 1, 0, 0)) + struct.pack("<I", 0) + text)
|
||||
owner.rx += 1
|
||||
return SimpleNamespace(id=identity)
|
||||
|
||||
def wait_packet(self, sender, predicate, since, timeout):
|
||||
if not owner.drop_outbound:
|
||||
return next((packet for when, packet in owner.events
|
||||
if when >= since and packet["from"] == sender and predicate(packet)), None)
|
||||
owner.sleep(timeout)
|
||||
return None
|
||||
|
||||
self.classes = Companion, Stock
|
||||
|
||||
def sleep(self, duration):
|
||||
self.now += duration
|
||||
|
||||
|
||||
class MeshtextSpeedTest(unittest.TestCase):
|
||||
def run_simulated(self, simulation, extra=()):
|
||||
directory = tempfile.TemporaryDirectory(prefix="meshtext-speed-offline-")
|
||||
self.addCleanup(directory.cleanup)
|
||||
path = Path(directory.name) / "report.json"
|
||||
with mock.patch.object(SPEED.delivery, "dependencies", return_value=simulation.classes), \
|
||||
mock.patch.object(SPEED.delivery, "require_idle_port"), \
|
||||
mock.patch.object(sys, "path", [str(TOOLS), *sys.path]), \
|
||||
mock.patch.object(SPEED.time, "monotonic", side_effect=lambda: simulation.now), \
|
||||
mock.patch.object(SPEED.time, "sleep", side_effect=simulation.sleep), \
|
||||
redirect_stdout(io.StringIO()):
|
||||
status = SPEED.main(["--allow-radio-changes", "--companion-port", "/dev/FAKE-A",
|
||||
"--stock-port", "/dev/FAKE-B", "--report", str(path), "--sf", "7", "--count", "2", *extra])
|
||||
return status, json.loads(path.read_text())
|
||||
|
||||
def test_plan_has_no_dependencies_or_ports_and_never_uses_preset_frequencies(self):
|
||||
with mock.patch.object(SPEED.delivery, "dependencies") as deps, \
|
||||
mock.patch.object(SPEED.delivery, "require_idle_port") as ports, redirect_stdout(io.StringIO()) as output:
|
||||
self.assertEqual(SPEED.main(["--plan"]), 0)
|
||||
deps.assert_not_called()
|
||||
ports.assert_not_called()
|
||||
plan = json.loads(output.getvalue())
|
||||
self.assertEqual(plan["frequency_mhz"], 909.5)
|
||||
self.assertEqual(plan["spreading_factors"], [7, 9, 10])
|
||||
self.assertEqual(plan["preamble_symbols"], 16)
|
||||
|
||||
def test_consent_invalid_parameters_same_ports_and_existing_report_refuse_before_open(self):
|
||||
for arguments in ([], ["--plan", "--count", "0"], ["--plan", "--sf", "7", "7"],
|
||||
["--plan", "--gap", "0"], ["--plan", "--timeout", "31"],
|
||||
["--allow-radio-changes", "--companion-port", "same", "--stock-port", "same", "--report", "new.json"]):
|
||||
with self.subTest(arguments=arguments), mock.patch.object(SPEED.delivery, "dependencies") as deps, \
|
||||
redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||
SPEED.main(arguments)
|
||||
deps.assert_not_called()
|
||||
|
||||
def test_complete_run_measures_both_directions_and_truthful_truncation(self):
|
||||
simulation = Simulation()
|
||||
status, data = self.run_simulated(simulation, ["--sf", "7", "9", "10"])
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(data["result"], "MEASURED")
|
||||
self.assertEqual(len(data["cases"]), 12)
|
||||
self.assertEqual(set(data["stock_profiles"]), {"7", "9", "10"})
|
||||
self.assertEqual(simulation.stock_writes.count("suppression"), 1)
|
||||
for case in data["cases"]:
|
||||
self.assertEqual(case["measurement"]["received"], 2)
|
||||
self.assertEqual(case["measurement"]["loss_fraction"], 0)
|
||||
self.assertEqual(case["nominal_lora_kbps"], SPEED.nominal_kbps(case["sf"]))
|
||||
expected = 154 if case["direction"] == "stock-to-companion" and case["wire_bytes"] == 160 else case["wire_bytes"]
|
||||
self.assertEqual(case["measurement"]["application_bytes_delivered"], 2 * expected)
|
||||
self.assertEqual(case["safety_after"]["primary_tx"], 0)
|
||||
self.assertFalse(any(command.startswith(("set radio ", "advert", "reboot", "set freq ")) for command in simulation.commands))
|
||||
self.assertEqual(sorted(simulation.closed), ["companion", "stock"])
|
||||
|
||||
def test_guard_primary_and_counter_fail_before_any_configuration(self):
|
||||
for simulation in (Simulation(guard="HIL TX lock=909.500 MHz"), Simulation(primary=909.5), Simulation(primary_tx=1)):
|
||||
with self.subTest(simulation=simulation):
|
||||
status, data = self.run_simulated(simulation)
|
||||
self.assertEqual(status, 1)
|
||||
self.assertEqual(data["result"], "FAIL")
|
||||
self.assertFalse(simulation.stock_writes or simulation.sent)
|
||||
self.assertFalse(any(command.startswith("set ") for command in simulation.commands))
|
||||
|
||||
def test_wrong_initial_stock_frequency_is_not_reconfigured_or_transmitted(self):
|
||||
simulation = Simulation(stock_frequency=910.525)
|
||||
status, data = self.run_simulated(simulation)
|
||||
self.assertEqual(status, 1)
|
||||
self.assertFalse(simulation.stock_writes or simulation.sent)
|
||||
self.assertIn("stock must use custom 909.5", data["failure"]["message"])
|
||||
|
||||
def test_packet_id_queue_depletion_prevents_a_second_sdk_send(self):
|
||||
simulation = Simulation(queue_stuck=True)
|
||||
status, data = self.run_simulated(simulation)
|
||||
self.assertEqual(status, 1)
|
||||
self.assertEqual(sum(who == "stock" for who, _ in simulation.sent), 1)
|
||||
self.assertIn("TX completion uncertain", data["failure"]["message"])
|
||||
self.assertEqual(data["cases"][-1]["packets"][-1]["tx_completion"], "uncertain")
|
||||
|
||||
def test_loss_is_reported_not_promoted_to_successful_phy_transmission(self):
|
||||
status, data = self.run_simulated(Simulation(drop_outbound=True, drop_inbound=True))
|
||||
self.assertEqual(status, 0)
|
||||
for case in data["cases"]:
|
||||
self.assertEqual(case["measurement"]["received"], 0)
|
||||
self.assertEqual(case["measurement"]["measured_application_goodput_bps"], 0)
|
||||
if case["direction"] == "stock-to-companion":
|
||||
self.assertTrue(all("uncertain" in packet["tx_completion"] for packet in case["packets"]))
|
||||
|
||||
def test_sdk_ack_and_empty_queue_are_not_claimed_as_rf_completion(self):
|
||||
simulation = Simulation()
|
||||
stock = simulation.classes[1]("not-a-port")
|
||||
stock.iface.queueStatus.mesh_packet_id = 99
|
||||
with mock.patch.object(SPEED.time, "monotonic", side_effect=lambda: simulation.now), \
|
||||
mock.patch.object(SPEED.time, "sleep", side_effect=simulation.sleep):
|
||||
result = SPEED.wait_stock_queue(stock, 1, 99)
|
||||
self.assertTrue(result["packet_id_depleted"])
|
||||
self.assertIn("RF completion unconfirmed", result["meaning"])
|
||||
stock.iface.queue = None
|
||||
with self.assertRaisesRegex(SPEED.delivery.Failure, "no observable packet queue"):
|
||||
SPEED.wait_stock_queue(stock, 1, 99)
|
||||
|
||||
def test_stale_empty_sdk_queue_cannot_prove_an_unseen_packet_id(self):
|
||||
simulation = Simulation()
|
||||
stock = simulation.classes[1]("not-a-port")
|
||||
with mock.patch.object(SPEED.time, "monotonic", side_effect=lambda: simulation.now), \
|
||||
mock.patch.object(SPEED.time, "sleep", side_effect=simulation.sleep):
|
||||
with self.assertRaisesRegex(SPEED.delivery.Failure, "TX completion uncertain"):
|
||||
SPEED.wait_stock_queue(stock, 1, 99)
|
||||
|
||||
def test_unique_tokens_differ_between_sizes_directions_and_packets(self):
|
||||
tokens = {SPEED.token_for("12345678", sf, direction, index, size)
|
||||
for sf in SPEED.SFS for size in SPEED.SIZES for direction in ("companion", "stock") for index in range(5)}
|
||||
self.assertEqual(len(tokens), 60)
|
||||
self.assertTrue(all(len(token) in SPEED.SIZES for token in tokens))
|
||||
|
||||
def test_nominal_bitrate_is_not_the_measured_goodput(self):
|
||||
self.assertEqual([SPEED.nominal_kbps(sf) for sf in SPEED.SFS], [21.875, 7.03125, 3.90625])
|
||||
measured = SPEED.summary([{"received": True, "wire_bytes": 180, "application_bytes": 154, "truncated": True}], 2)
|
||||
self.assertEqual(measured["measured_application_goodput_bps"], 616)
|
||||
self.assertEqual(measured["application_bytes_delivered"], 154)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Offline guarded four-node transfer controller tests; no serial/RF/PIO."""
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SPEC = importlib.util.spec_from_file_location("chain_under_test", ROOT / "tools/hil/mota_espnow_chain.py")
|
||||
CHAIN = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(CHAIN)
|
||||
MID = "ee375e77"
|
||||
|
||||
|
||||
class Simulation:
|
||||
def __init__(self, *, off_leak=False, midpoint_leak=False, instantly_done=False, bad_guard=False):
|
||||
self.now, self.have, self.total = 100.0, 0, 9
|
||||
self.off_leak, self.midpoint_leak = off_leak, midpoint_leak
|
||||
self.instantly_done, self.bad_guard = instantly_done, bad_guard
|
||||
self.bridge_on, self.active, self.done = True, False, False
|
||||
self.commands, self.reports, self.resets = [], [], 0
|
||||
owner = self
|
||||
|
||||
class Node:
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
def command(self, text, timeout=15):
|
||||
owner.commands.append((self.name, text))
|
||||
frequency = 909.5 if self.name == "a" else 908.5
|
||||
if text == "get lab.tx":
|
||||
value = ("bad" if owner.bad_guard else f"HIL TX lock={frequency:.3f} MHz; off-frequency TX blocked; primary RX-only when off-frequency")
|
||||
elif text == "get tempradio":
|
||||
value = f"> {frequency:.3f},500.000,5,5,128"
|
||||
elif text in ("get radio2", "get tempradio2"):
|
||||
value = "> off"
|
||||
elif text == "get repeat":
|
||||
value = "> on"
|
||||
elif text in ("get espnow.enabled", "get espnow.running"):
|
||||
value = "> " + ("on" if self.name == "a" or owner.bridge_on else "off")
|
||||
elif text.startswith("set espnow.enabled "):
|
||||
owner.bridge_on = text.endswith(" on")
|
||||
value = "OK"
|
||||
elif text == "ota self":
|
||||
value = "self body=540000 image=540912 base_hash=AB0CA97D3E4D11FE abi=3 codecs=0x5"
|
||||
elif text.startswith("ota config "):
|
||||
value = "OK saved"
|
||||
elif text == "ota config":
|
||||
value = "ota config: speed=1.1x autofetch=off autoinstall=off hops=3"
|
||||
elif text == "ota ls":
|
||||
value = "Catalogue:\n1) EE375E77 target=abcd codec2\n2) DEADBEEF ignored"
|
||||
elif text == "ota cancel":
|
||||
owner.have, owner.active, owner.done = 0, False, False
|
||||
owner.resets += 1
|
||||
value = "OK dropped session"
|
||||
elif text == "ota pull " + MID + " flash":
|
||||
owner.active = True
|
||||
value = "OK pulling mid=EE375E77 -> flash (primary traffic)"
|
||||
elif text == "ota stats":
|
||||
if not owner.active:
|
||||
value = "OTA | fw v1 id=deadbeef | fetch idle | af=off hops=3"
|
||||
else:
|
||||
if owner.bridge_on:
|
||||
owner.have = owner.total if owner.instantly_done else min(owner.total, owner.have + 1)
|
||||
elif owner.off_leak or (owner.midpoint_leak and owner.have):
|
||||
owner.have = min(owner.total, owner.have + 1)
|
||||
state = "done" if owner.have == owner.total else "dl"
|
||||
value = f"OTA | fw v1 id=deadbeef | fetch {state} {owner.have}/{owner.total} 0% id=EE375E77 3s | af=off hops=3"
|
||||
elif text == "ota dev verify":
|
||||
value = "verify parsed=1 root=1 payload=1 img=1 signed=0 sig=0 trust=0 | ok=1 auto=0"
|
||||
else:
|
||||
raise AssertionError("unexpected command " + text)
|
||||
# Deliberately truncated echo matches the observed3401 path.
|
||||
return "o\r\n -> " + value.replace("\n", "\r\n") + "\r\n> "
|
||||
|
||||
self.nodes = {name: Node(name) for name in ("a", "b", "target")}
|
||||
|
||||
def sleep(self, seconds):
|
||||
self.now += seconds
|
||||
|
||||
def monotonic(self):
|
||||
return self.now
|
||||
|
||||
def run(self):
|
||||
with mock.patch.object(CHAIN.time, "monotonic", self.monotonic), mock.patch.object(CHAIN.time, "sleep", self.sleep):
|
||||
return CHAIN.run_chain(self.nodes, MID, timeout=30, outage=8, poll=.25,
|
||||
persist=lambda report: self.reports.append(report["result"]))
|
||||
|
||||
|
||||
class ChainTests(unittest.TestCase):
|
||||
def test_plan_and_consent_open_no_hardware(self):
|
||||
output = io.StringIO()
|
||||
with redirect_stdout(output), mock.patch.object(CHAIN, "serial_node_factory", side_effect=AssertionError):
|
||||
self.assertEqual(CHAIN.main(["--plan"]), 0)
|
||||
plan = json.loads(output.getvalue())
|
||||
self.assertFalse(plan["source_port_opened"])
|
||||
self.assertFalse(plan["install_commands"])
|
||||
with redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||
CHAIN.main([])
|
||||
|
||||
def test_multiline_reply_and_truncated_echo_accepted(self):
|
||||
value = CHAIN.reply("o\r\n -> catalogue:\r\n1) EE375E77\r\n2) DEADBEEF\r\n> ")
|
||||
self.assertEqual(value, "catalogue:\n1) EE375E77\n2) DEADBEEF")
|
||||
with self.assertRaises(CHAIN.Failure):
|
||||
CHAIN.reply("ota stats\n> ")
|
||||
|
||||
def test_ambiguous_arrows_fail_closed_with_safe_bounded_history(self):
|
||||
raw = "o\r\n -> stale\r\n -> actual\r\n"
|
||||
with self.assertRaisesRegex(CHAIN.Failure, "ambiguous"):
|
||||
CHAIN.reply(raw)
|
||||
node = SimpleNamespace(commands=[{"command": "ota stats", "reply": "old"}] * 3 +
|
||||
[{"command": "ota stats", "reply": raw}])
|
||||
history = CHAIN.failure_history({"target": node})["target"]
|
||||
self.assertEqual(len(history), 3)
|
||||
self.assertEqual(history[-1]["arrow_markers"], 2)
|
||||
self.assertEqual(history[-1]["reply"], raw)
|
||||
secret = "aa" * 32
|
||||
record = CHAIN.diagnostic_record("ota stats", " -> " + secret + "x" * 4000)
|
||||
self.assertLess(len(record["reply"]), 1600)
|
||||
self.assertNotIn(secret, record["reply"])
|
||||
self.assertNotIn("reply", CHAIN.diagnostic_record("get prv.key", secret))
|
||||
|
||||
def test_fresh_marker_reader_does_not_require_echo(self):
|
||||
simulation = Simulation()
|
||||
|
||||
class Port:
|
||||
fragments = [b"o\r\n -> fetch", b" dl 1/9\r\n", b"> "]
|
||||
in_waiting = 1
|
||||
|
||||
def read(self, count):
|
||||
simulation.now += .01
|
||||
return self.fragments.pop(0) if self.fragments else b""
|
||||
|
||||
with mock.patch.object(CHAIN.time, "monotonic", simulation.monotonic):
|
||||
self.assertIn("fetch dl 1/9", CHAIN.read_fresh_reply(Port(), 1))
|
||||
|
||||
def test_classic_no_prompt_truncated_echo_multiline_quiet(self):
|
||||
simulation = Simulation()
|
||||
|
||||
class Port:
|
||||
fragments = [b"o\r\n -> catalogue:\r\n", b"1) EE375E77\r\n", b"2) DEADBEEF\r\n"]
|
||||
in_waiting = 1
|
||||
|
||||
def read(self, count):
|
||||
simulation.now += .04
|
||||
return self.fragments.pop(0) if self.fragments else b""
|
||||
|
||||
with mock.patch.object(CHAIN.time, "monotonic", simulation.monotonic):
|
||||
text = CHAIN.read_fresh_reply(Port(), 2)
|
||||
self.assertEqual(CHAIN.reply(text), "catalogue:\n1) EE375E77\n2) DEADBEEF")
|
||||
|
||||
def test_classic_open_no_term_tokens_lf_ignored_cr_executes(self):
|
||||
simulation = Simulation()
|
||||
|
||||
class Port:
|
||||
def __init__(self, **kwargs):
|
||||
self.writes, self.line, self.incoming, self.executed = [], bytearray(), bytearray(), []
|
||||
self.closed, self.dtr, self.rts = False, False, False
|
||||
|
||||
@property
|
||||
def in_waiting(self):
|
||||
return len(self.incoming)
|
||||
|
||||
def write(self, value):
|
||||
self.writes.append(value)
|
||||
for byte in value:
|
||||
if byte == 10:
|
||||
continue
|
||||
if byte == 13:
|
||||
text = self.line.decode()
|
||||
self.line.clear()
|
||||
if text:
|
||||
self.executed.append(text)
|
||||
self.incoming.extend(b"o\r\n -> answer\r\n")
|
||||
else:
|
||||
self.line.append(byte)
|
||||
return len(value)
|
||||
|
||||
def read(self, count):
|
||||
simulation.now += .04
|
||||
value = bytes(self.incoming[:count])
|
||||
del self.incoming[:count]
|
||||
return value
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
class Base:
|
||||
def __init__(self, path):
|
||||
raise AssertionError("Companion constructor must never run")
|
||||
|
||||
def read(self, timeout, quiet):
|
||||
simulation.now += timeout
|
||||
result = bytes(self.port.incoming)
|
||||
self.port.incoming.clear()
|
||||
return result.decode()
|
||||
|
||||
modules = {name: ModuleType(name) for name in ("serial", "serial.tools", "serial.tools.list_ports",
|
||||
"serial_session", "ethernet_primary_probe")}
|
||||
modules["serial"].Serial = Port
|
||||
modules["serial.tools"].list_ports = modules["serial.tools.list_ports"]
|
||||
modules["serial.tools.list_ports"].comports = lambda: [SimpleNamespace(device="/dev/test", serial_number="exact",
|
||||
vid=0x1a86, pid=0x7523, location="physical")]
|
||||
modules["serial_session"].assert_port_idle = lambda path: None
|
||||
modules["serial_session"].open_configured_session = lambda port: None
|
||||
modules["ethernet_primary_probe"].SerialNode = Base
|
||||
with mock.patch.dict(sys.modules, modules), mock.patch.object(CHAIN.time, "monotonic", simulation.monotonic):
|
||||
node = CHAIN.serial_node_factory()("/dev/test")
|
||||
self.assertEqual(node.port.writes, [b"\r"])
|
||||
self.assertFalse(node.port.dtr)
|
||||
self.assertFalse(node.port.rts)
|
||||
self.assertEqual(CHAIN.reply(node.command("get lab.tx")), "answer")
|
||||
self.assertEqual(node.port.executed, ["get lab.tx"])
|
||||
self.assertEqual(node.port.writes[-1], b"get lab.tx\r")
|
||||
node.close()
|
||||
self.assertFalse(any(b"MESHCORE-TERM" in value for value in node.port.writes))
|
||||
self.assertTrue(node.port.closed)
|
||||
|
||||
def test_full_counterfactual_midpoint_resume_hash_and_integrity_proof(self):
|
||||
simulation = Simulation()
|
||||
result = simulation.run()
|
||||
self.assertEqual(result["result"], "PASS", result.get("failure"))
|
||||
self.assertTrue(result["initial_off_no_completed_blocks"])
|
||||
self.assertGreater(result["midpoint_off_stalled"]["retained_blocks"], 0)
|
||||
self.assertTrue(result["bridge_b_restored"])
|
||||
self.assertEqual(result["final_progress"]["have"], 9)
|
||||
self.assertEqual(result["running_before"], result["running_after"])
|
||||
self.assertFalse(result["rf_capture_independent"])
|
||||
self.assertFalse(any(command.startswith(("ota install", "ota rescue", "ota dev apply")) for _, command in simulation.commands))
|
||||
self.assertTrue(all(not command.startswith(("set radio", "tempradio ", "reboot")) for _, command in simulation.commands))
|
||||
|
||||
def test_off_path_data_fails_and_restores_bridge(self):
|
||||
simulation = Simulation(off_leak=True)
|
||||
result = simulation.run()
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertIn("while required bridge", result["failure"]["message"])
|
||||
self.assertTrue(result["bridge_b_restored"])
|
||||
|
||||
def test_instant_complete_is_not_claimed_midpoint_pass_retries_once(self):
|
||||
simulation = Simulation(instantly_done=True)
|
||||
result = simulation.run()
|
||||
self.assertEqual(result["result"], "TRANSFER_VERIFIED_MIDPOINT_NOT_PROVEN", result.get("failure"))
|
||||
self.assertEqual(simulation.resets, 2)
|
||||
self.assertNotIn("midpoint_off_stalled", result)
|
||||
self.assertTrue(result["bridge_b_restored"])
|
||||
|
||||
def test_failed_guard_no_setters_or_stage_clear(self):
|
||||
simulation = Simulation(bad_guard=True)
|
||||
result = simulation.run()
|
||||
self.assertEqual(result["result"], "FAIL")
|
||||
self.assertTrue(all(command.startswith("get ") for _, command in simulation.commands))
|
||||
self.assertEqual(simulation.resets, 0)
|
||||
|
||||
def test_progress_rejects_other_mid_truncated_and_invalid_counts(self):
|
||||
class Node:
|
||||
value = ""
|
||||
|
||||
def command(self, command, timeout):
|
||||
return "o\n -> " + self.value + "\n> "
|
||||
|
||||
node = Node()
|
||||
for value in ("fetch dl 1/9 0% id=DEADBEEF", "fetch dl 1/9 0% id=EE37", "fetch dl 10/9 0% id=EE375E77"):
|
||||
node.value = value
|
||||
with self.assertRaises(CHAIN.Failure):
|
||||
CHAIN.progress(node, MID)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Offline tests for the existing-protocol USB mOTA adapter; no radio access."""
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOLS = ROOT / "tools/hil"
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
SPEC = importlib.util.spec_from_file_location("mota_usb_under_test", TOOLS / "mota_usb_seeder.py")
|
||||
USB = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(USB)
|
||||
|
||||
|
||||
def request(op, args=b""):
|
||||
return b"MS" + bytes([op]) + args + bytes([USB.xor(bytes([op]) + args)])
|
||||
|
||||
|
||||
def stats():
|
||||
return {"requests": {}, "usb_received_bytes": 0, "usb_sent_bytes": 0,
|
||||
"error_responses": 0, "discarded_serial_bytes": 0,
|
||||
"bad_request_checksums": 0, "detach_sent": False}
|
||||
|
||||
|
||||
class Clock:
|
||||
now = 100.0
|
||||
|
||||
def monotonic(self):
|
||||
return self.now
|
||||
|
||||
def sleep(self, seconds):
|
||||
self.now += seconds
|
||||
|
||||
|
||||
class MotaUsbTests(unittest.TestCase):
|
||||
def test_plan_without_dependencies_or_ports(self):
|
||||
output = io.StringIO()
|
||||
with redirect_stdout(output), mock.patch.object(USB, "prepare_catalog", side_effect=AssertionError):
|
||||
self.assertEqual(USB.main(["--plan"]), 0)
|
||||
report = json.loads(output.getvalue())
|
||||
self.assertFalse(report["install_commands"])
|
||||
self.assertEqual(report["zopfli_iterations"], 1000)
|
||||
|
||||
def test_consent_and_fresh_report_required(self):
|
||||
with redirect_stderr(io.StringIO()), mock.patch.object(USB, "prepare_catalog", side_effect=AssertionError):
|
||||
with self.assertRaises(SystemExit):
|
||||
USB.main([])
|
||||
with self.assertRaises(SystemExit):
|
||||
USB.main(["--plan", "--duration", "nan"])
|
||||
|
||||
def test_fragmented_resynchronization_exact_four_wire_requests(self):
|
||||
parser = USB.RequestParser()
|
||||
frames = [request(1), request(2, b"\x00"), request(3, b"\x00" + struct.pack("<IH", 8, 192)),
|
||||
request(9, b"\x00" + struct.pack("<HHH", 19, 0, 0))]
|
||||
result = []
|
||||
for byte in b"hello\r\nM" + b"".join(frames):
|
||||
result += parser.feed(bytes([byte]))
|
||||
self.assertEqual(result, frames)
|
||||
self.assertLessEqual(len(parser.buffer), 11)
|
||||
|
||||
def test_bad_checksum_resync_and_no_storage_write_support(self):
|
||||
parser = USB.RequestParser()
|
||||
self.assertEqual(parser.feed(b"MS\x01\x00" + request(1)), [request(1)])
|
||||
self.assertEqual(parser.bad_checksum, 1)
|
||||
with self.assertRaisesRegex(USB.Failure, "storage/write"):
|
||||
parser.feed(b"MS\x06")
|
||||
with self.assertRaises(USB.Failure):
|
||||
USB.RequestParser().feed(b"a" * 4097)
|
||||
|
||||
def test_noise_budget_bounded(self):
|
||||
parser = USB.RequestParser()
|
||||
with self.assertRaisesRegex(USB.Failure, "budget"):
|
||||
for _ in range(18):
|
||||
parser.feed(b"a" * 4096)
|
||||
|
||||
def test_cached_snapshot_retains_more_than16_blocks_without_recompression(self):
|
||||
offset, raw, count = 205, bytes(range(64)) * 20, 20
|
||||
descriptor = bytearray(38)
|
||||
struct.pack_into("<III", descriptor, 22, count, offset, len(raw))
|
||||
descriptor[34] = 6
|
||||
blob = b"h" * offset + raw + b"vk496"
|
||||
calls = []
|
||||
|
||||
def compress(value, *, numiterations):
|
||||
calls.append(numiterations)
|
||||
return zlib.compress(value)[2:-4]
|
||||
|
||||
cached = USB.CachedFile(blob, bytes(descriptor), compress)
|
||||
self.assertEqual(len(cached.blocks), 20)
|
||||
for index in (0, 19, 0, 18, 0):
|
||||
cached.deflated_block(index)
|
||||
self.assertEqual(calls, [1000] * 20)
|
||||
self.assertEqual(cached.path.open("rb").read(), blob)
|
||||
with self.assertRaises(USB.Failure):
|
||||
cached.path.open("wb")
|
||||
|
||||
def test_real_catalog_golden_requests_verifies_and_ignores_mutated_original(self):
|
||||
sys.path.insert(0, str(ROOT / "tools/mota"))
|
||||
import motalib
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "fixture.mota"
|
||||
raw = b"USB source transport fixture. " * 40
|
||||
manifest = motalib.build_manifest(target_id=0x12345678, fw_version=0x01120001,
|
||||
image_size=len(raw), payload=raw, block_size=64, image_hash=motalib.mh32(raw),
|
||||
codec_id=motalib.CODEC_FULL, is_full=True)
|
||||
blob = motalib.build_container(manifest, raw)
|
||||
path.write_bytes(blob)
|
||||
catalog, details = USB.prepare_catalog(path)
|
||||
self.assertGreater(details["blocks"], 16)
|
||||
self.assertEqual(details["zopfli_iterations"], 1000)
|
||||
path.write_bytes(b"broken same-source replacement")
|
||||
count = catalog.handle_request(request(1))
|
||||
self.assertEqual(count, b"ms\x01\x00\x01" + bytes([USB.xor(b"ms\x01\x00\x01")]))
|
||||
desc = catalog.handle_request(request(2, b"\x00"))
|
||||
self.assertEqual(len(desc), 43)
|
||||
response = catalog.handle_request(request(3, b"\x00" + struct.pack("<IH", 0, 192)))
|
||||
self.assertEqual(response[4:-1], blob[:192])
|
||||
self.assertEqual(USB.xor(response), 0)
|
||||
# Every block is retained, so revisiting first after block19 is RAM-only.
|
||||
last = catalog.handle_request(request(9, b"\x00" + struct.pack("<HHH", details["blocks"] - 1, 0, 0)))
|
||||
first = catalog.handle_request(request(9, b"\x00" + struct.pack("<HHH", 0, 0, 0)))
|
||||
self.assertEqual(last[3], 0)
|
||||
self.assertEqual(first[3], 0)
|
||||
|
||||
def test_invalid_container_refuses_before_usb(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "bad.mota"
|
||||
path.write_bytes(b"mOTA invalid")
|
||||
with self.assertRaises((ValueError, USB.Failure)):
|
||||
USB.prepare_catalog(path)
|
||||
|
||||
def test_guard_live_primary_and_lease_all_fail_closed_without_setters(self):
|
||||
class Node:
|
||||
guard = USB.GUARD
|
||||
live = "> TempRadio active: 909.500,500.00,5,5 100s left,preamble=32"
|
||||
|
||||
def __init__(self):
|
||||
self.commands = []
|
||||
|
||||
def cli(self, command):
|
||||
self.commands.append(command)
|
||||
return {"get lab.tx": self.guard, "get tempradio": self.live,
|
||||
"get radio": "910.525,62.5,7,5", "get radio2.status": "TX=0,0"}[command]
|
||||
|
||||
node = Node()
|
||||
self.assertEqual(USB.source_safety(node, 60)["lease_seconds"], 100)
|
||||
for guard, live in (("unlocked", node.live), (USB.GUARD, "TempRadio pending: 909.5,500,5,5"),
|
||||
(USB.GUARD, "TempRadio active: 910.525,500,5,5 100s left"),
|
||||
(USB.GUARD, "TempRadio active: 909.5,500,7,5 100s left"),
|
||||
(USB.GUARD, "TempRadio active: 909.5,500,5,5 89s left")):
|
||||
node.guard, node.live = guard, live
|
||||
with self.assertRaises(USB.Failure):
|
||||
USB.source_safety(node, 60)
|
||||
self.assertTrue(all(command.startswith("get ") for command in node.commands))
|
||||
|
||||
def test_attach_services_count_before_ack_then_serves_and_detaches(self):
|
||||
clock, state = Clock(), stats()
|
||||
|
||||
class Catalog:
|
||||
def handle_request(self, frame):
|
||||
self.frame = frame
|
||||
return b"ms\x01\x00\x01\x1f"
|
||||
|
||||
class Port:
|
||||
def __init__(self):
|
||||
self.incoming, self.writes = bytearray(), []
|
||||
|
||||
@property
|
||||
def in_waiting(self):
|
||||
return len(self.incoming)
|
||||
|
||||
def write(self, value):
|
||||
self.writes.append(value)
|
||||
if value.startswith(b"ota folder on"):
|
||||
self.incoming.extend(request(1))
|
||||
elif value.startswith(b"ms"):
|
||||
self.incoming.extend(b"\r\nOK folder attached (serial): advertising1/1\r\n")
|
||||
return len(value)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
def read(self, count):
|
||||
clock.now += .01
|
||||
value = bytes(self.incoming[:count])
|
||||
del self.incoming[:count]
|
||||
return value
|
||||
|
||||
node = SimpleNamespace(port=Port())
|
||||
with mock.patch.object(USB.time, "monotonic", clock.monotonic), mock.patch.object(USB.time, "sleep", clock.sleep), redirect_stdout(io.StringIO()):
|
||||
USB.serve(node, Catalog(), .1, state)
|
||||
self.assertEqual(state["requests"], {"1": 1})
|
||||
self.assertTrue(state["detach_sent"])
|
||||
self.assertEqual(node.port.writes[0], b"+++MESHCORE-TERM-START\r")
|
||||
self.assertEqual(node.port.writes[-1], b"ota folder off\r\n")
|
||||
self.assertNotIn(b"install", b"".join(node.port.writes))
|
||||
|
||||
def test_no_attach_ack_times_out_and_still_detaches(self):
|
||||
clock = Clock()
|
||||
|
||||
class Port:
|
||||
in_waiting = 0
|
||||
writes = []
|
||||
|
||||
def read(self, count):
|
||||
clock.now += .1
|
||||
return b""
|
||||
|
||||
def write(self, value):
|
||||
self.writes.append(value)
|
||||
return len(value)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
with mock.patch.object(USB.time, "monotonic", clock.monotonic), mock.patch.object(USB.time, "sleep", clock.sleep):
|
||||
with self.assertRaisesRegex(USB.Failure, "attach timed out"):
|
||||
USB.serve(SimpleNamespace(port=Port()), None, .1, stats())
|
||||
self.assertEqual(Port.writes[-1], b"ota folder off\r\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user