Clean project references and separate optional bench tooling
Remove unrelated ecosystem comparisons and software citations while retaining hardware links, measured model names, and required license notices. Preserve stock-peer runners and tests in a verified local validation package. Keep shared Companion USB transport in the firmware repository for the raw-radio sweep and OTA seeder, with focused CI coverage. Restore missing hosted documentation links.
This commit is contained in:
1 parent
adf91beb9c
commit
a3d77a9a76
38 files changed
+472
-3227
No files matched your search
@@ -0,0 +1,270 @@
|
||||
"""Exercise the shared local USB transport without opening a real device."""
|
||||
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOLS = ROOT / "tools/hil"
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
import companion_serial as HIL
|
||||
|
||||
|
||||
def device_frame(payload):
|
||||
return b">" + struct.pack("<H", len(payload)) + payload
|
||||
|
||||
|
||||
def self_info():
|
||||
result = bytearray(58)
|
||||
result[:2] = b"\x05\x01"
|
||||
result[4:36] = bytes(range(1, 33))
|
||||
struct.pack_into("<II", result, 48, 910525, 62500)
|
||||
result[56:58] = bytes((7, 5))
|
||||
return bytes(result) + b"USB fixture"
|
||||
|
||||
|
||||
def device_info():
|
||||
result = bytearray(82)
|
||||
result[:4] = bytes((13, 14, 0, 3))
|
||||
result[20:27] = b"Fixture"
|
||||
result[60:67] = b"1.2.3.4"
|
||||
return bytes(result)
|
||||
|
||||
|
||||
class FakeSerial:
|
||||
def __init__(self, **options):
|
||||
self.options = options
|
||||
self.events = []
|
||||
self._dtr, self._rts, self._dsrdtr = True, True, False
|
||||
self.port = None
|
||||
self.is_open = False
|
||||
self.chunks = deque()
|
||||
self.responses = deque()
|
||||
self.negotiation = b"> Binary mode\r\n"
|
||||
self.fail_open = False
|
||||
self.short_write = False
|
||||
|
||||
def _line(name):
|
||||
def get(self):
|
||||
return getattr(self, "_" + name)
|
||||
|
||||
def set(self, value):
|
||||
setattr(self, "_" + name, value)
|
||||
self.events.append((name, value))
|
||||
return property(get, set)
|
||||
|
||||
dtr = _line("dtr")
|
||||
rts = _line("rts")
|
||||
dsrdtr = _line("dsrdtr")
|
||||
|
||||
@property
|
||||
def in_waiting(self):
|
||||
return len(self.chunks[0]) if self.chunks else 0
|
||||
|
||||
def open(self):
|
||||
self.events.append(("open", self.dtr, self.rts, self.dsrdtr))
|
||||
if self.fail_open:
|
||||
raise OSError("fixture open failure")
|
||||
self.is_open = True
|
||||
|
||||
def close(self):
|
||||
self.events.append(("close",))
|
||||
self.is_open = False
|
||||
|
||||
def write(self, data):
|
||||
self.events.append(("write", data))
|
||||
if data == b"+++MESHCORE-TERM-STOP\r":
|
||||
if self.negotiation:
|
||||
self.chunks.append(self.negotiation)
|
||||
elif data.startswith(b"<") and self.responses:
|
||||
# Fragmentation and a push frame exercise the actual shared reader.
|
||||
reply = device_frame(b"\x80notice") + device_frame(self.responses.popleft())
|
||||
self.chunks.extend((reply[:2], reply[2:7], reply[7:]))
|
||||
return len(data) - int(self.short_write)
|
||||
|
||||
def flush(self):
|
||||
self.events.append(("flush",))
|
||||
|
||||
def read(self, count):
|
||||
if not self.chunks:
|
||||
return b""
|
||||
chunk = self.chunks.popleft()
|
||||
if len(chunk) > count:
|
||||
self.chunks.appendleft(chunk[count:])
|
||||
return chunk[:count]
|
||||
|
||||
|
||||
class CompanionSerialTests(unittest.TestCase):
|
||||
def connect(self, port=None):
|
||||
port = port or FakeSerial()
|
||||
module = ModuleType("serial")
|
||||
module.Serial = mock.Mock(return_value=port)
|
||||
with mock.patch.dict(sys.modules, {"serial": module}):
|
||||
node = HIL.Companion("/dev/fake-local")
|
||||
self.assertEqual(module.Serial.call_args.kwargs,
|
||||
{"port": None, "baudrate": 115200, "timeout": 0.05,
|
||||
"write_timeout": 2, "exclusive": True})
|
||||
return node, port
|
||||
|
||||
def test_clean_import_has_no_serial_dependency_or_port_access(self):
|
||||
script = (
|
||||
"import sys; sys.path.insert(0, " + repr(str(TOOLS)) + "); "
|
||||
"import companion_serial, companion_raw_radio2_sweep, mota_usb_seeder; "
|
||||
"assert 'serial' not in sys.modules"
|
||||
)
|
||||
result = subprocess.run([sys.executable, "-S", "-B", "-c", script],
|
||||
cwd="/tmp", capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_safe_configured_open_and_close_do_not_pulse_reset_lines(self):
|
||||
node, port = self.connect()
|
||||
self.assertEqual(port.events[:2], [("dtr", False), ("rts", False)])
|
||||
opened = next(event for event in port.events if event[0] == "open")
|
||||
self.assertEqual(opened[1:3], (False, False))
|
||||
if os.name == "posix":
|
||||
self.assertTrue(opened[3])
|
||||
self.assertEqual(port.events[-3:], [("rts", False), ("dtr", False), ("dsrdtr", False)])
|
||||
self.assertFalse(port.dsrdtr)
|
||||
self.assertFalse(any(event in (("dtr", True), ("rts", True)) for event in port.events))
|
||||
node.close()
|
||||
self.assertFalse(port.is_open)
|
||||
|
||||
def test_failed_open_closes_the_handle_and_restores_handshake(self):
|
||||
port = FakeSerial()
|
||||
port.fail_open = True
|
||||
with self.assertRaisesRegex(OSError, "fixture open failure"):
|
||||
self.connect(port)
|
||||
self.assertIn(("close",), port.events)
|
||||
self.assertFalse(port.dsrdtr)
|
||||
self.assertFalse(port.is_open)
|
||||
|
||||
def test_start_negotiates_then_validates_actual_fragmented_frames(self):
|
||||
node, port = self.connect()
|
||||
stale_reader = node.reader
|
||||
stale_reader._buffer.extend(device_frame(b"\x01\x05"))
|
||||
port.responses.extend((device_info(), self_info()))
|
||||
with mock.patch.object(HIL.time, "sleep"):
|
||||
result = node.start()
|
||||
self.assertIsNot(node.reader, stale_reader)
|
||||
self.assertEqual(result["protocol"], 14)
|
||||
self.assertEqual(result["max_channels"], 3)
|
||||
self.assertEqual(node.max_channels, 3)
|
||||
self.assertEqual(result["primary"]["node_name"], "USB fixture")
|
||||
self.assertEqual(result["model"], "Fixture")
|
||||
self.assertEqual(result["firmware"], "1.2.3.4")
|
||||
self.assertEqual(result["usb_binary_negotiation"],
|
||||
{"explicit_stop_token": True,
|
||||
"discarded_terminal_bytes": len(port.negotiation), "dtr": True})
|
||||
writes = [event[1] for event in port.events if event[0] == "write"]
|
||||
self.assertEqual(writes, [b"+++MESHCORE-TERM-STOP\r",
|
||||
HIL.encode_host_frame(bytes((22, 14))),
|
||||
HIL.encode_host_frame(HIL.make_app_start_spec("Meshtext-Auto-HIL").payload)])
|
||||
stop = port.events.index(("write", writes[0]))
|
||||
self.assertEqual(port.events[stop - 2:stop], [("rts", False), ("dtr", True)])
|
||||
|
||||
def test_start_rejects_logging_owner_before_any_framed_request(self):
|
||||
node, port = self.connect()
|
||||
port.negotiation = b"Error: set usb.logging off before Binary mode\r\n"
|
||||
with mock.patch.object(HIL.time, "sleep"), self.assertRaisesRegex(HIL.Failure, "USB logging owns"):
|
||||
node.start()
|
||||
self.assertEqual([event[1] for event in port.events if event[0] == "write"],
|
||||
[b"+++MESHCORE-TERM-STOP\r"])
|
||||
|
||||
def test_start_rejects_truncated_device_and_invalid_primary_information(self):
|
||||
for replies, reason in (((b"\x0d",), "truncated Companion device info"),
|
||||
((device_info(), b"\x05"), "SELF_INFO length")):
|
||||
with self.subTest(reason=reason):
|
||||
node, port = self.connect()
|
||||
port.responses.extend(replies)
|
||||
with mock.patch.object(HIL.time, "sleep"), self.assertRaisesRegex(RuntimeError, reason):
|
||||
node.start()
|
||||
|
||||
def test_cli_retains_exact_retry_error_and_redacts_keys(self):
|
||||
node, port = self.connect()
|
||||
port.responses.append(b"\x1dError: radio busy or TX power rejected")
|
||||
with self.assertRaisesRegex(HIL.Failure,
|
||||
"^Companion CLI set tx rejected: Error: radio busy or TX power rejected$"):
|
||||
node.cli("set tx 2")
|
||||
key = "private-channel-key"
|
||||
port.responses.append(("\x1dError: echoed " + key).encode())
|
||||
with self.assertRaises(HIL.Failure) as rejected:
|
||||
node.cli("set mt.channel 1 mt-lab " + key)
|
||||
self.assertNotIn(key, str(rejected.exception))
|
||||
self.assertIn("set mt.channel rejected: Error: echoed <redacted>", str(rejected.exception))
|
||||
secret = "a1" * 16
|
||||
with mock.patch.object(node, "request", side_effect=RuntimeError("diagnostic " + secret)):
|
||||
with self.assertRaises(HIL.Failure) as failed:
|
||||
node.cli("set mt.channel 1 mt-lab " + secret)
|
||||
self.assertNotIn(secret, str(failed.exception))
|
||||
self.assertIn("<redacted>", str(failed.exception))
|
||||
|
||||
def test_request_rejects_partial_write_device_error_and_wrong_response(self):
|
||||
node, port = self.connect()
|
||||
port.short_write = True
|
||||
with self.assertRaisesRegex(HIL.Failure, "incomplete Companion write"):
|
||||
node.request(b"\x16\x0e", (13,))
|
||||
port.short_write = False
|
||||
for reply, reason in ((b"\x01\x09", "command rejected, error 09"),
|
||||
(b"\x0a", "unexpected Companion response 10")):
|
||||
with self.subTest(reason=reason):
|
||||
port.responses.append(reply)
|
||||
with self.assertRaisesRegex(HIL.Failure, reason):
|
||||
node.request(b"\x16\x0e", (13,))
|
||||
|
||||
def test_request_retries_frame_timeout_with_a_bounded_deadline(self):
|
||||
node, _ = self.connect()
|
||||
with mock.patch.object(node.reader, "read_frame", side_effect=HIL.FrameTimeout("fixture")) as read, \
|
||||
mock.patch.object(HIL.time, "monotonic", side_effect=(0, 0.1, 0.2, 5.1)):
|
||||
with self.assertRaisesRegex(HIL.Failure, "response timeout for command 22"):
|
||||
node.request(b"\x16\x0e", (13,))
|
||||
read.assert_called_once()
|
||||
|
||||
def test_channel_name_uses_existing_request_and_minimum_size(self):
|
||||
node, port = self.connect()
|
||||
reply = bytearray(50)
|
||||
reply[0] = 18
|
||||
reply[2:7] = b"Local"
|
||||
port.responses.append(bytes(reply))
|
||||
self.assertEqual(node.channel_name(2), "Local")
|
||||
self.assertIn(("write", HIL.encode_host_frame(bytes((31, 2)))), port.events)
|
||||
port.responses.append(b"\x12")
|
||||
with self.assertRaisesRegex(HIL.Failure, "truncated channel info"):
|
||||
node.channel_name(2)
|
||||
|
||||
def test_negotiation_drain_is_bounded_by_bytes_and_time(self):
|
||||
port = FakeSerial()
|
||||
port.negotiation = b"x" * 65537
|
||||
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)
|
||||
port = FakeSerial()
|
||||
port.negotiation = b"x" * 20000
|
||||
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"], 8192)
|
||||
self.assertTrue(port.chunks)
|
||||
|
||||
def test_port_ownership_guard_preserves_fail_closed_statuses(self):
|
||||
with mock.patch.object(HIL.sys, "platform", "linux"), \
|
||||
mock.patch.object(HIL.shutil, "which", return_value="/bin/fuser"), \
|
||||
mock.patch.object(HIL.subprocess, "run") as inspect:
|
||||
inspect.return_value = SimpleNamespace(returncode=1)
|
||||
HIL.require_idle_port("/dev/fake-local")
|
||||
inspect.assert_called_with(["/bin/fuser", os.path.realpath("/dev/fake-local")],
|
||||
capture_output=True, timeout=3)
|
||||
for status in (0, 2):
|
||||
inspect.return_value = SimpleNamespace(returncode=status)
|
||||
with self.assertRaisesRegex(HIL.Failure, "busy or ownership inspection failed"):
|
||||
HIL.require_idle_port("/dev/fake-local")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,234 +0,0 @@
|
||||
"""Host-only checks of the preset sweep; never opens a hardware port."""
|
||||
import contextlib
|
||||
import io
|
||||
import pathlib
|
||||
import random
|
||||
import struct
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "tools" / "hil"))
|
||||
import meshtext_auto_radio2 as hil
|
||||
|
||||
|
||||
class SweepPlanTests(unittest.TestCase):
|
||||
def test_meshtext_help_exposes_stock_peer_port_without_opening_hardware(self):
|
||||
output = io.StringIO()
|
||||
with patch.object(sys, "argv", ["meshtext_auto_radio2.py", "--help"]), \
|
||||
patch.object(hil, "Companion") as companion, \
|
||||
patch.object(hil, "StockPeer") as stock, \
|
||||
contextlib.redirect_stdout(output), self.assertRaises(SystemExit) as exit_result:
|
||||
hil.main()
|
||||
self.assertEqual(exit_result.exception.code, 0)
|
||||
self.assertIn("Meshtext Companion / stock-peer", output.getvalue())
|
||||
self.assertIn("--stock-port", output.getvalue())
|
||||
self.assertNotIn("meshtastic", output.getvalue().lower())
|
||||
companion.assert_not_called()
|
||||
stock.assert_not_called()
|
||||
|
||||
def test_us_centers_and_native_stable_presets(self):
|
||||
expected = {
|
||||
"LongFast": 906.875, "ShortTurbo": 926.75,
|
||||
"ShortFast": 918.875, "ShortSlow": 920.625,
|
||||
"MediumFast": 913.125, "MediumSlow": 914.875,
|
||||
"LongTurbo": 908.75, "LongMod": 902.6875,
|
||||
"LongSlow": 905.3125, "MediumTurbo": 925.25,
|
||||
}
|
||||
self.assertEqual(sum(p.stock_enum is not None for p in hil.PRESETS), 9)
|
||||
for preset in hil.PRESETS:
|
||||
self.assertEqual(preset.frequency, expected[preset.name])
|
||||
self.assertEqual(preset.describe()["preamble"], 16)
|
||||
|
||||
def test_alias_selection_and_rejections(self):
|
||||
self.assertEqual(hil.choose_presets("long_moderate")[0].name, "LongMod")
|
||||
for value in ("", "longfast,longfast", "not-a-preset"):
|
||||
with self.assertRaises(hil.TestFailure):
|
||||
hil.choose_presets(value)
|
||||
|
||||
def test_auto_profile_readback(self):
|
||||
profile = hil.parse_profile("> 906.875,250.000,11,5,rxtx,16; auto-owned")
|
||||
self.assertEqual(profile, (906.875, 250, 11, 5, "rxtx", 16))
|
||||
with self.assertRaises(hil.TestFailure):
|
||||
hil.parse_profile("> off")
|
||||
|
||||
def test_queue_envelopes(self):
|
||||
body = bytes((1, 0, 0)) + struct.pack("<I", 123456) + b"!12345678: test"
|
||||
for packet in (b"\x08" + body, b"\x11\x00\x00\x00" + body):
|
||||
value = hil.decode_channel_frame(packet)
|
||||
self.assertEqual(value["channel"], 1)
|
||||
self.assertEqual(value["timestamp"], 123456)
|
||||
self.assertEqual(value["text"], b"!12345678: test")
|
||||
self.assertIsNone(hil.decode_channel_frame(b"\x0a"))
|
||||
with self.assertRaises(hil.TestFailure):
|
||||
hil.decode_channel_frame(b"\x08")
|
||||
|
||||
def test_temporary_profile_status_dialects(self):
|
||||
for value in ("> off", "off", "TempRadio inactive"):
|
||||
self.assertTrue(hil.temporary_off(value))
|
||||
for value in ("> 1 min left", "TempRadio active", "TempRadio inactive; scheduled"):
|
||||
self.assertFalse(hil.temporary_off(value))
|
||||
|
||||
|
||||
class SweepPolicyTests(unittest.TestCase):
|
||||
def test_traffic_counts_preserve_the_configured_threshold(self):
|
||||
case = {"v4_to_v3": [{"received": True}] * 3,
|
||||
"v3_to_v4": [{"received": True}, {"received": False}, {"received": True}]}
|
||||
self.assertEqual(hil.assess_traffic(case, 3), [
|
||||
{"direction": "v3_to_v4", "received": 2, "attempted": 3, "required": 3}])
|
||||
self.assertEqual(case["traffic_counts"]["v4_to_v3"], {"received": 3, "attempted": 3})
|
||||
self.assertFalse(hil.assess_traffic(case, 2))
|
||||
|
||||
def test_seeded_gap_jitter_is_reproducible_and_zero_is_unchanged(self):
|
||||
gaps = []
|
||||
with patch.object(hil.time, "sleep") as sleep:
|
||||
for _ in range(2):
|
||||
rng = random.Random(0x12345678)
|
||||
packets = [{} for _ in range(4)]
|
||||
for packet in packets:
|
||||
hil.pause_after_packet(packet, 1, 0.5, rng)
|
||||
gaps.append([packet["gap_after_seconds"] for packet in packets])
|
||||
self.assertEqual(gaps[0], gaps[1])
|
||||
self.assertTrue(all(1 <= gap <= 1.5 for gap in gaps[0]))
|
||||
rng = Mock()
|
||||
packet = {}
|
||||
hil.pause_after_packet(packet, 1, 0, rng)
|
||||
rng.uniform.assert_not_called()
|
||||
sleep.assert_called_with(1)
|
||||
self.assertEqual(packet["gap_after_seconds"], 1)
|
||||
|
||||
def run_fake(self, *, continue_on_loss=False, lose_first=True, reboot=False,
|
||||
reboot_loss=False, auto_clear=False):
|
||||
presets = [hil.PRESETS[1], hil.PRESETS[0]]
|
||||
state = SimpleNamespace(alias="", rebooted=False, configured=[], commands=[])
|
||||
|
||||
class FakeCompanion:
|
||||
max_channels = 2
|
||||
|
||||
def __init__(self, port):
|
||||
self.port = SimpleNamespace(write=self.write, flush=lambda: None)
|
||||
|
||||
def write(self, frame):
|
||||
state.rebooted = True
|
||||
return len(frame)
|
||||
|
||||
def start(self):
|
||||
return {"primary": {"public_key_prefix": "unchanged"}}
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def channel_name(self, slot):
|
||||
return "normal"
|
||||
|
||||
def cli(self, command):
|
||||
state.commands.append(command)
|
||||
if command.startswith("set mt.channel "):
|
||||
state.alias = command.split()[3]
|
||||
elif command.startswith("delete mt.channel "):
|
||||
state.alias = ""
|
||||
if command in ("get tempradio", "get tempradio2"):
|
||||
return "> off"
|
||||
if command == "get radio":
|
||||
return "unchanged-primary"
|
||||
if command == "get mt.status":
|
||||
return "> Meshtext; active; TX=0 RX=0 fail=0" if state.alias else "> Meshtext; no Meshtext channels; TX=0 RX=0 fail=0"
|
||||
if command == "get radio2":
|
||||
return "auto-owned" if state.alias else "> off (automatic allowed)"
|
||||
return "> diagnostic"
|
||||
|
||||
def mt_node(self):
|
||||
return 0x12345678
|
||||
|
||||
def wait_auto(self, preset):
|
||||
return {"radio2": "auto-owned", "status": "active"}
|
||||
|
||||
def send_text(self, slot, token):
|
||||
pass
|
||||
|
||||
def wait_text(self, slot, from_node, token, timeout):
|
||||
lost = ((lose_first and state.alias == presets[0].alias and not state.rebooted)
|
||||
or (reboot_loss and state.rebooted))
|
||||
return {"received": not lost}
|
||||
|
||||
class FakeStock:
|
||||
node = 0x87654321
|
||||
|
||||
def __init__(self, port):
|
||||
pass
|
||||
|
||||
def configure(self, preset, key, tx, hops):
|
||||
state.configured.append(preset.name)
|
||||
return {"readback": {"use_preset": True, "channel_num": 0, "bandwidth": preset.bandwidth,
|
||||
"spread_factor": preset.sf, "coding_rate": preset.cr,
|
||||
"tx_power": tx, "hop_limit": hops}}
|
||||
|
||||
def packets_since(self, timestamp, sender):
|
||||
return []
|
||||
|
||||
def wait_packet(self, sender, predicate, since, timeout):
|
||||
return {"id": 1}
|
||||
|
||||
def send_text(self, token, hops):
|
||||
return SimpleNamespace(id=1)
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
args = SimpleNamespace(key_bits=128, region="auto", tx_power=-9, hops=7,
|
||||
minimum_received=3, messages_per_direction=3,
|
||||
continue_on_loss=continue_on_loss, gap_seconds=1, gap_jitter_seconds=0.5,
|
||||
companion_port="fake-v4", stock_port="fake-v3", channel_slot=1,
|
||||
quiet_seconds=1, timeout=15, nodeinfo=False, reboot=reboot,
|
||||
auto_clear=auto_clear, output=pathlib.Path("unused-mocked-report.json"))
|
||||
with patch.object(hil, "Companion", FakeCompanion), patch.object(hil, "StockPeer", FakeStock), \
|
||||
patch.object(hil.time, "sleep"), patch.object(hil, "write_report") as writer, \
|
||||
patch.object(hil.importlib.metadata, "version", return_value="mock"), \
|
||||
patch.object(hil.secrets, "token_hex", return_value="12345678"), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
report = hil.run(args, presets)
|
||||
writer.assert_called_once_with(args.output, report)
|
||||
return report, state
|
||||
|
||||
def test_default_loss_policy_is_failfast_with_diagnostics(self):
|
||||
report, state = self.run_fake()
|
||||
self.assertEqual(state.configured, ["ShortTurbo"])
|
||||
self.assertEqual(report["result"], "FAIL")
|
||||
self.assertEqual(report["failed_cases"], ["ShortTurbo"])
|
||||
case = report["cases"][0]
|
||||
self.assertEqual(case["traffic_counts"]["v3_to_v4"]["received"], 0)
|
||||
for name in ("status_after_traffic", "radio2_after_traffic",
|
||||
"radio2_status_after_traffic", "radio2_scan_after_traffic"):
|
||||
self.assertIn(name, case)
|
||||
|
||||
def test_continue_on_loss_collects_both_cases_but_still_fails(self):
|
||||
report, state = self.run_fake(continue_on_loss=True)
|
||||
self.assertEqual(state.configured, ["ShortTurbo", "LongFast"])
|
||||
self.assertEqual([case["result"] for case in report["cases"]], ["FAIL", "PASS"])
|
||||
self.assertEqual(report["result"], "FAIL")
|
||||
self.assertIn("ShortTurbo", report["failure"]["message"])
|
||||
self.assertEqual(report["gap_jitter_seed"], 0x12345678)
|
||||
for case in report["cases"]:
|
||||
for direction in ("v4_to_v3", "v3_to_v4"):
|
||||
self.assertTrue(all(1 <= packet["gap_after_seconds"] <= 1.5 for packet in case[direction]))
|
||||
|
||||
def test_continued_loss_does_not_skip_reboot_and_reboot_loss_is_strict(self):
|
||||
report, state = self.run_fake(continue_on_loss=True, reboot=True, reboot_loss=True)
|
||||
self.assertTrue(state.rebooted)
|
||||
self.assertEqual(report["reboot_persistence"]["result"], "FAIL")
|
||||
self.assertEqual(report["result"], "FAIL")
|
||||
self.assertIn("after reboot in v3_to_v4", report["failure"]["message"])
|
||||
|
||||
def test_successful_reboot_and_auto_clear_leave_final_profile_readded(self):
|
||||
report, state = self.run_fake(continue_on_loss=True, lose_first=False, reboot=True, auto_clear=True)
|
||||
self.assertEqual(report["result"], "PASS")
|
||||
self.assertEqual(report["reboot_persistence"]["result"], "PASS")
|
||||
self.assertEqual(report["auto_clear"]["result"], "PASS")
|
||||
self.assertIn("no Meshtext channels", report["auto_clear"]["removed"]["mt_status"])
|
||||
self.assertEqual(state.alias, "mt-longfast")
|
||||
self.assertEqual(report["failed_cases"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,175 +0,0 @@
|
||||
"""Host-only stock SDK/boot-readback contracts; no SDK installation or serial IO."""
|
||||
|
||||
import copy
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "hil"))
|
||||
import meshtext_auto_radio2 as hil
|
||||
|
||||
|
||||
class MeshInterfaceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PresetEnum:
|
||||
values = {p.stock_enum: index for index, p in enumerate(hil.PRESETS) if p.stock_enum}
|
||||
|
||||
@classmethod
|
||||
def keys(cls):
|
||||
return cls.values.keys()
|
||||
|
||||
@classmethod
|
||||
def Value(cls, name):
|
||||
return cls.values[name]
|
||||
|
||||
|
||||
def fake_sdk():
|
||||
package = ModuleType("meshtastic")
|
||||
package.__path__ = []
|
||||
protobuf = ModuleType("meshtastic.protobuf")
|
||||
protobuf.__path__ = []
|
||||
channel = ModuleType("meshtastic.protobuf.channel_pb2")
|
||||
channel.Channel = SimpleNamespace(PRIMARY=1)
|
||||
config = ModuleType("meshtastic.protobuf.config_pb2")
|
||||
config.Config = SimpleNamespace(DeviceConfig=SimpleNamespace(CLIENT_MUTE=1),
|
||||
LoRaConfig=SimpleNamespace(US=1, ModemPreset=PresetEnum))
|
||||
interface = ModuleType("meshtastic.mesh_interface")
|
||||
interface.MeshInterface = SimpleNamespace(MeshInterfaceError=MeshInterfaceError)
|
||||
util = ModuleType("meshtastic.util")
|
||||
util.to_node_num = int
|
||||
package.protobuf, package.mesh_interface = protobuf, interface
|
||||
protobuf.channel_pb2, protobuf.config_pb2 = channel, config
|
||||
return {module.__name__: module for module in (package, protobuf, channel, config, interface, util)}
|
||||
|
||||
|
||||
class Node:
|
||||
def __init__(self):
|
||||
self.localConfig = SimpleNamespace(device=SimpleNamespace(role=0),
|
||||
lora=SimpleNamespace(modem_preset=0))
|
||||
self.channels = [SimpleNamespace(role=0, settings=SimpleNamespace(
|
||||
name="before", psk=b"old", uplink_enabled=True, downlink_enabled=True))]
|
||||
self.calls = []
|
||||
self.written_lora = None
|
||||
self.nodeNum = 0x12345678
|
||||
|
||||
def ensureSessionKey(self):
|
||||
self.calls.append("session")
|
||||
|
||||
def beginSettingsTransaction(self):
|
||||
self.calls.append("begin")
|
||||
|
||||
def writeChannel(self, index):
|
||||
self.calls.append(("channel", index))
|
||||
|
||||
def writeConfig(self, name):
|
||||
self.calls.append(("config", name))
|
||||
if name == "lora":
|
||||
self.written_lora = copy.deepcopy(self.localConfig.lora)
|
||||
|
||||
def commitSettingsTransaction(self):
|
||||
self.calls.append("commit")
|
||||
|
||||
|
||||
class StockConfigurationTests(unittest.TestCase):
|
||||
def configure(self, preset, *, normalized=False, handshake_misses=0, session_misses=0,
|
||||
readback_cr=None):
|
||||
node = Node()
|
||||
session_reads = []
|
||||
|
||||
def session_node(node_num):
|
||||
self.assertEqual(node_num, node.nodeNum)
|
||||
session_reads.append(True)
|
||||
return {} if len(session_reads) <= session_misses else {"adminSessionPassKey": b"mock-key"}
|
||||
|
||||
iface = SimpleNamespace(localNode=node, myInfo=SimpleNamespace(my_node_num=0x12345678),
|
||||
metadata=SimpleNamespace(firmware_version="mock-stable"), close=lambda: None,
|
||||
_getOrCreateByNum=session_node)
|
||||
stock = hil.StockPeer.__new__(hil.StockPeer)
|
||||
stock.iface = iface
|
||||
attempts = []
|
||||
|
||||
def connect():
|
||||
attempts.append(True)
|
||||
if len(attempts) <= handshake_misses:
|
||||
raise MeshInterfaceError("transient simulated boot handshake")
|
||||
# The official stock boot helper derives BW/SF from the preset.
|
||||
if normalized and preset.stock_enum:
|
||||
node.localConfig.lora.bandwidth = preset.bandwidth
|
||||
node.localConfig.lora.spread_factor = preset.sf
|
||||
if readback_cr is not None:
|
||||
node.localConfig.lora.coding_rate = readback_cr
|
||||
stock.iface = iface
|
||||
|
||||
stock.connect = connect
|
||||
with patch.dict(sys.modules, fake_sdk()), patch.object(hil.time, "sleep"), \
|
||||
patch.object(hil.time, "monotonic", side_effect=range(1, 250)):
|
||||
result = stock.configure(preset, bytes(range(16)), -9, 7)
|
||||
return node, result, attempts
|
||||
|
||||
def test_nine_native_presets_clear_bw_sf_and_keep_native_cr_with_hash_slot(self):
|
||||
for preset in hil.PRESETS:
|
||||
if not preset.stock_enum:
|
||||
continue
|
||||
with self.subTest(preset=preset.name):
|
||||
node, result, _ = self.configure(preset)
|
||||
lora = node.written_lora
|
||||
self.assertTrue(lora.use_preset)
|
||||
self.assertEqual(lora.modem_preset, PresetEnum.Value(preset.stock_enum))
|
||||
# Stock clamps a zero CR to 5 instead of selecting preset CR.
|
||||
self.assertEqual((lora.bandwidth, lora.spread_factor, lora.coding_rate), (0, 0, preset.cr))
|
||||
self.assertEqual((lora.channel_num, lora.override_frequency, lora.frequency_offset), (0, 0, 0))
|
||||
self.assertEqual((lora.region, lora.tx_power, lora.hop_limit), (1, -9, 7))
|
||||
self.assertTrue(lora.tx_enabled and lora.ignore_mqtt)
|
||||
self.assertFalse(lora.config_ok_to_mqtt)
|
||||
self.assertEqual(node.calls, ["session", "begin", ("config", "device"),
|
||||
("config", "lora"), ("channel", 0), "commit"])
|
||||
self.assertEqual(node.channels[0].settings.name, preset.name)
|
||||
self.assertEqual(node.channels[0].settings.psk, bytes(range(16)))
|
||||
self.assertFalse(node.channels[0].settings.uplink_enabled)
|
||||
self.assertFalse(node.channels[0].settings.downlink_enabled)
|
||||
self.assertEqual(result["node"], "!12345678")
|
||||
|
||||
def test_native_stock_boot_normalization_is_not_a_readback_failure(self):
|
||||
for preset in hil.PRESETS:
|
||||
if preset.stock_enum:
|
||||
with self.subTest(preset=preset.name):
|
||||
node, _, _ = self.configure(preset, normalized=True)
|
||||
self.assertEqual(node.written_lora.bandwidth, 0)
|
||||
self.assertEqual(node.written_lora.spread_factor, 0)
|
||||
self.assertEqual(node.localConfig.lora.bandwidth, preset.bandwidth)
|
||||
|
||||
def test_custom_mediumturbo_tuple_and_explicit_calculated_slot(self):
|
||||
preset = next(p for p in hil.PRESETS if p.name == "MediumTurbo")
|
||||
node, _, _ = self.configure(preset)
|
||||
lora = node.written_lora
|
||||
self.assertFalse(lora.use_preset)
|
||||
self.assertEqual((lora.bandwidth, lora.spread_factor, lora.coding_rate), (500, 9, 5))
|
||||
self.assertEqual(lora.channel_num, 47)
|
||||
self.assertEqual(node.channels[0].settings.name, "MediumTurbo")
|
||||
|
||||
def test_transient_meshinterface_handshake_error_retries(self):
|
||||
_, _, attempts = self.configure(hil.PRESETS[0], handshake_misses=1)
|
||||
self.assertEqual(len(attempts), 2)
|
||||
|
||||
def test_async_admin_session_is_ready_before_writes(self):
|
||||
node, _, _ = self.configure(hil.PRESETS[0], session_misses=3)
|
||||
self.assertEqual(node.calls[0:2], ["session", "begin"])
|
||||
|
||||
def test_missing_admin_session_aborts_without_writing(self):
|
||||
with self.assertRaisesRegex(hil.TestFailure, "admin session setup timed out"):
|
||||
self.configure(hil.PRESETS[0], session_misses=100)
|
||||
|
||||
def test_zero_or_wrong_cr_is_not_accepted_as_native_readback(self):
|
||||
for preset_name, observed_cr in (("LongFast", 0), ("LongSlow", 5)):
|
||||
preset = next(p for p in hil.PRESETS if p.name == preset_name)
|
||||
with self.subTest(preset=preset_name, cr=observed_cr):
|
||||
with self.assertRaisesRegex(hil.TestFailure, "configuration readback did not match"):
|
||||
self.configure(preset, readback_cr=observed_cr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,672 +0,0 @@
|
||||
"""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()
|
||||
@@ -1,288 +0,0 @@
|
||||
"""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()
|
||||
Reference in new issue
Block a user