Fix auto-path traces, harden contacts retrieval, add device config tooling
Trace: - Auto-path now ends every route at the target's own hash (verified on hardware: a trace only replies when its destination is the final hop), so direct neighbors and learned multi-hop routes both resolve correctly. - Retry the transient "no event received during contacts retrieval" blip and surface a clean DeviceCommandError instead of a raw traceback. - Route summary annotates each node with its hash at the command's path-hash width, wrapping after an arrow when the line is too long. - Default trace count changed from 5 to 3. Also includes the in-progress device-config feature (config_io, device_config, config tool, config editor UI, tests) and related supporting edits. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
43353f83a9
commit
421781f13d
19 files changed
+3081
-108
No files matched your search
@@ -0,0 +1,193 @@
|
||||
"""Tests for the device-configuration registry, backup/restore, and safety gating.
|
||||
|
||||
All run against :class:`MockDevice` — no hardware required.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import typer
|
||||
|
||||
from meshtools.core.config_io import backup_config, plan_restore, read_backup
|
||||
from meshtools.core.connection import MockDevice
|
||||
from meshtools.core.device_config import (
|
||||
RADIO_PRESETS,
|
||||
DeviceConfigError,
|
||||
build_snapshot,
|
||||
format_value,
|
||||
get_spec,
|
||||
parse_value,
|
||||
)
|
||||
from meshtools.tools.config import _require_yes
|
||||
|
||||
|
||||
async def _connected_mock() -> MockDevice:
|
||||
"""Return a connected MockDevice."""
|
||||
device = MockDevice()
|
||||
await device.connect()
|
||||
return device
|
||||
|
||||
|
||||
# -- parsing / formatting ------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_value_types() -> None:
|
||||
"""Each value type coerces from string correctly."""
|
||||
assert parse_value(get_spec("name"), "Node-7") == "Node-7"
|
||||
assert parse_value(get_spec("radio_sf"), "9") == 9
|
||||
assert parse_value(get_spec("radio_freq"), "868.0") == 868.0
|
||||
assert parse_value(get_spec("manual_add_contacts"), "yes") is True
|
||||
assert parse_value(get_spec("manual_add_contacts"), "off") is False
|
||||
|
||||
|
||||
def test_parse_value_range_and_enum_errors() -> None:
|
||||
"""Out-of-range and invalid enum values raise DeviceConfigError."""
|
||||
with pytest.raises(DeviceConfigError, match="<= 12"):
|
||||
parse_value(get_spec("radio_sf"), "99")
|
||||
with pytest.raises(DeviceConfigError, match=">= 5"):
|
||||
parse_value(get_spec("radio_cr"), "1")
|
||||
with pytest.raises(DeviceConfigError, match="one of"):
|
||||
parse_value(get_spec("telemetry_mode_base"), "7")
|
||||
with pytest.raises(DeviceConfigError, match="boolean"):
|
||||
parse_value(get_spec("manual_add_contacts"), "maybe")
|
||||
|
||||
|
||||
def test_format_value() -> None:
|
||||
"""Formatting renders booleans, enums, and unknowns readably."""
|
||||
assert format_value(get_spec("manual_add_contacts"), True) == "true"
|
||||
assert format_value(get_spec("telemetry_mode_base"), 1) == "1 (always)"
|
||||
assert format_value(get_spec("name"), None) == "?"
|
||||
|
||||
|
||||
def test_path_hash_mode_is_strict_enum() -> None:
|
||||
"""path_hash_mode accepts its four modes and rejects anything else."""
|
||||
assert parse_value(get_spec("path_hash_mode"), "3") == 3
|
||||
assert format_value(get_spec("path_hash_mode"), 0) == "0 (1-byte hashes (default))"
|
||||
with pytest.raises(DeviceConfigError, match="one of"):
|
||||
parse_value(get_spec("path_hash_mode"), "4")
|
||||
|
||||
|
||||
def test_non_strict_enum_accepts_unlisted_value() -> None:
|
||||
"""multi_acks/adv_loc_policy list common values but still accept other ints."""
|
||||
spec = get_spec("multi_acks")
|
||||
assert spec.value_type == "enum" and not spec.strict_choices
|
||||
assert parse_value(spec, "5") == 5 # not in choices, but >= minimum: accepted
|
||||
with pytest.raises(DeviceConfigError, match=">= 0"):
|
||||
parse_value(spec, "-1") # still range-checked
|
||||
|
||||
|
||||
def test_radio_presets_map_to_radio_settings() -> None:
|
||||
"""Every preset exposes the four radio fields by their registry keys."""
|
||||
assert RADIO_PRESETS, "expected at least one standard radio preset"
|
||||
for preset in RADIO_PRESETS:
|
||||
settings = preset.as_settings()
|
||||
assert set(settings) == {"radio_freq", "radio_bw", "radio_sf", "radio_cr"}
|
||||
# Each value parses cleanly through its setting spec.
|
||||
for key, value in settings.items():
|
||||
assert parse_value(get_spec(key), value) == value
|
||||
|
||||
|
||||
def test_get_spec_unknown_raises() -> None:
|
||||
"""An unknown key produces a helpful error listing valid keys."""
|
||||
with pytest.raises(DeviceConfigError, match="unknown setting"):
|
||||
get_spec("not_a_setting")
|
||||
|
||||
|
||||
# -- apply against the mock device ---------------------------------------------
|
||||
|
||||
|
||||
async def test_apply_simple_setting() -> None:
|
||||
"""Setting the node name round-trips through the device."""
|
||||
device = await _connected_mock()
|
||||
spec = get_spec("name")
|
||||
await spec.apply(device, parse_value(spec, "Yagi-Hub"), await build_snapshot(device))
|
||||
assert (await device.get_self_info())["name"] == "Yagi-Hub"
|
||||
|
||||
|
||||
async def test_apply_coupled_radio_field_preserves_others() -> None:
|
||||
"""Changing one radio field rebuilds set_radio from the current snapshot."""
|
||||
device = await _connected_mock()
|
||||
spec = get_spec("radio_sf")
|
||||
await spec.apply(device, 9, await build_snapshot(device))
|
||||
info = await device.get_self_info()
|
||||
assert info["radio_sf"] == 9
|
||||
assert info["radio_freq"] == 869.525 # unchanged
|
||||
assert info["radio_bw"] == 250.0
|
||||
assert info["radio_cr"] == 5
|
||||
|
||||
|
||||
async def test_apply_telemetry_mode_preserves_siblings() -> None:
|
||||
"""Editing one telemetry mode leaves the other two intact."""
|
||||
device = await _connected_mock()
|
||||
spec = get_spec("telemetry_mode_loc")
|
||||
await spec.apply(device, 2, await build_snapshot(device))
|
||||
info = await device.get_self_info()
|
||||
assert info["telemetry_mode_loc"] == 2
|
||||
assert info["telemetry_mode_base"] == 0
|
||||
assert info["telemetry_mode_env"] == 0
|
||||
|
||||
|
||||
async def test_custom_var_round_trip() -> None:
|
||||
"""Custom variables persist on the device."""
|
||||
device = await _connected_mock()
|
||||
await device.set_custom_var("exp_flag", "1")
|
||||
assert (await device.get_custom_vars())["exp_flag"] == "1"
|
||||
|
||||
|
||||
# -- backup / restore ----------------------------------------------------------
|
||||
|
||||
|
||||
async def test_backup_and_read_round_trip(tmp_path: Path) -> None:
|
||||
"""A backup writes all settings, custom vars, and channels and reads back."""
|
||||
device = await _connected_mock()
|
||||
await device.set_name("Foo")
|
||||
await device.set_channel(0, "Public", b"\x01" * 16)
|
||||
snapshot = await build_snapshot(device)
|
||||
path = backup_config(tmp_path / "cfg.toml", snapshot, {"exp": "1"}, await _channels(device))
|
||||
|
||||
backup = read_backup(path)
|
||||
assert backup.settings["name"] == "Foo"
|
||||
assert backup.settings["radio_sf"] == 11
|
||||
assert backup.custom["exp"] == "1"
|
||||
assert backup.channels[0]["name"] == "Public"
|
||||
assert backup.channels[0]["secret"] == ("01" * 16)
|
||||
|
||||
|
||||
async def test_plan_restore_emits_only_differences(tmp_path: Path) -> None:
|
||||
"""The restore planner returns ops only for values that differ from the device."""
|
||||
source = await _connected_mock()
|
||||
await source.set_name("Foo")
|
||||
path = backup_config(
|
||||
tmp_path / "cfg.toml", await build_snapshot(source), {"exp": "1"}, []
|
||||
)
|
||||
backup = read_backup(path)
|
||||
|
||||
target = await _connected_mock() # fresh device: name still "MockCompanion"
|
||||
ops = plan_restore(backup, await build_snapshot(target), await target.get_custom_vars())
|
||||
|
||||
assert ("set", "name", "Foo") in ops
|
||||
assert ("set_custom", "exp", "1") in ops
|
||||
# Unchanged values (e.g. radio_sf 11 == 11) are not re-applied.
|
||||
assert "radio_sf" not in [op[1] for op in ops if op[0] == "set"]
|
||||
|
||||
|
||||
# -- safety gating -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_require_yes_blocks_without_confirmation() -> None:
|
||||
"""Destructive CLI commands abort unless --yes is passed."""
|
||||
with pytest.raises(typer.Exit):
|
||||
_require_yes(False, "factory reset erases all data")
|
||||
_require_yes(True, "factory reset erases all data") # does not raise
|
||||
|
||||
|
||||
async def _channels(device: MockDevice) -> list[dict]:
|
||||
"""Collect the mock's configured channels for backup."""
|
||||
channels = []
|
||||
for idx in range(8):
|
||||
ch = await device.get_channel(idx)
|
||||
if ch:
|
||||
channels.append(ch)
|
||||
return channels
|
||||
+343
-1
@@ -10,7 +10,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from meshtools.core.connection import MockDevice, clamp_tx_power
|
||||
from meshtools.core.models import TraceResult, TraceStats
|
||||
from meshtools.core.models import Contact, TraceResult, TraceStats
|
||||
from meshtools.persistence.repository import Repository
|
||||
from meshtools.services import trace_runner
|
||||
|
||||
@@ -38,6 +38,163 @@ def test_trace_stats_aggregation() -> None:
|
||||
assert stats.median_min_snr == pytest.approx(-1.0) # median of [-2.0, 0.0]
|
||||
|
||||
|
||||
def test_parse_trace_path_mixes_names_and_hex() -> None:
|
||||
"""Names and hex mix; the hex width is preserved and names truncate to match."""
|
||||
contacts = [Contact(name="Alice", key_prefix="d4e5f6a7")]
|
||||
# 1-byte hops: hex, a contact name (case-insensitively), hex again
|
||||
assert trace_runner.parse_trace_path("3d, alice ,f2", contacts) == "3d,d4,f2"
|
||||
# the width comes from the hex tokens you type — no truncation to 1 byte
|
||||
assert trace_runner.parse_trace_path("a1b2c3", contacts) == "a1b2c3"
|
||||
|
||||
|
||||
def test_parse_trace_path_preserves_three_byte_width() -> None:
|
||||
"""A 3-byte (6 hex) width is kept, and names truncate to that width."""
|
||||
contacts = [Contact(name="Alice", key_prefix="d4e5f6a7b8c9")]
|
||||
assert (
|
||||
trace_runner.parse_trace_path("3d5f7a,Alice,f2a1b3", contacts)
|
||||
== "3d5f7a,d4e5f6,f2a1b3"
|
||||
)
|
||||
|
||||
|
||||
def test_parse_trace_path_rejects_mixed_widths() -> None:
|
||||
"""Hex hops must all use the same number of bytes."""
|
||||
with pytest.raises(ValueError):
|
||||
trace_runner.parse_trace_path("3d,a1b2c3", contacts=[])
|
||||
|
||||
|
||||
def test_path_hash_flags_power_of_two_only() -> None:
|
||||
"""Trace flags encode the hash width as 1 << s, so only 1/2/4/8 bytes map."""
|
||||
assert trace_runner.path_hash_flags(1) == 0
|
||||
assert trace_runner.path_hash_flags(2) == 1
|
||||
assert trace_runner.path_hash_flags(4) == 2
|
||||
assert trace_runner.path_hash_flags(8) == 3
|
||||
assert trace_runner.path_hash_flags(3) is None
|
||||
|
||||
|
||||
def test_parse_trace_hops_reads_path_snr() -> None:
|
||||
"""Per-hop SNR comes from payload['path'] dicts; the final hash-less node counts."""
|
||||
from meshtools.core.connection import parse_trace_hops
|
||||
|
||||
payload = {
|
||||
"path": [
|
||||
{"hash": "3d", "snr": 4.5},
|
||||
{"hash": "f2", "snr": -2.0},
|
||||
{"snr": 1.25}, # final node: our device, no hash
|
||||
]
|
||||
}
|
||||
hops = parse_trace_hops(payload)
|
||||
assert [h.node for h in hops] == ["3d", "f2", None]
|
||||
assert [h.snr for h in hops] == [4.5, -2.0, 1.25]
|
||||
assert [h.index for h in hops] == [0, 1, 2]
|
||||
|
||||
|
||||
def test_parse_trace_hops_empty_without_path() -> None:
|
||||
"""A reply with no parsed path yields no hops (SNR shows as n/a)."""
|
||||
from meshtools.core.connection import parse_trace_hops
|
||||
|
||||
assert parse_trace_hops({}) == []
|
||||
|
||||
|
||||
def test_route_text_annotates_nodes_with_command_width_hash() -> None:
|
||||
"""The route shows each node's hash at the command's path-hash width."""
|
||||
from meshtools.core.models import Hop
|
||||
from meshtools.ui.widgets import _route_text
|
||||
|
||||
resolve = trace_runner.make_node_resolver(
|
||||
[Contact(name="Alice", public_key="3d63c6" + "00" * 26, key_prefix="3d63c6429436")]
|
||||
)
|
||||
# Known node (resolves to Alice) then the reply returning to our device (node=None).
|
||||
result = TraceResult(
|
||||
target="Alice",
|
||||
success=True,
|
||||
hops=[Hop(0, "3d63c6", 12.0), Hop(1, None, 12.0)],
|
||||
path_hash_bytes=2, # command used 2-byte hashes
|
||||
)
|
||||
plain = _route_text(result, "Me", resolve).plain
|
||||
assert "Alice" in plain
|
||||
assert "(3d63)" in plain # truncated to 2 bytes, not the full 3d63c6
|
||||
assert "3d63c6" not in plain
|
||||
assert plain.count("Me") == 2 # our device at both ends, carrying no hash
|
||||
assert "Me (" not in plain.replace(" ", " ") # device never annotated
|
||||
|
||||
|
||||
def test_route_text_unknown_node_shows_hash_only() -> None:
|
||||
"""An unresolved node shows just its hash, truncated to the command width."""
|
||||
from meshtools.core.models import Hop
|
||||
from meshtools.ui.widgets import _route_text
|
||||
|
||||
result = TraceResult(
|
||||
target="x",
|
||||
success=True,
|
||||
hops=[Hop(0, "aa11bb", 12.0), Hop(1, None, 12.0)],
|
||||
path_hash_bytes=1, # 1-byte width
|
||||
)
|
||||
plain = _route_text(result, "Me").plain.replace(" ", " ")
|
||||
assert "→ aa →" in plain # 1-byte hash, no name, no parens
|
||||
assert "aa11bb" not in plain
|
||||
|
||||
|
||||
def test_parse_trace_path_rejects_unknown_token() -> None:
|
||||
"""A token that is neither a known contact nor valid hex is an error."""
|
||||
with pytest.raises(ValueError):
|
||||
trace_runner.parse_trace_path("nope", contacts=[])
|
||||
with pytest.raises(ValueError):
|
||||
trace_runner.parse_trace_path(" ", contacts=[])
|
||||
|
||||
|
||||
async def test_mock_device_honors_forced_path() -> None:
|
||||
"""A forced path drives the repeater hops; a return-to-us hop is appended."""
|
||||
device = MockDevice()
|
||||
await device.connect()
|
||||
result = await device.run_trace("Alice", path="3d,f2,3d")
|
||||
# Three forced repeater hops, plus the hash-less hop for the reply returning to us.
|
||||
assert result.hop_count == 4
|
||||
assert [h.node for h in result.hops] == ["3d", "f2", "3d", None]
|
||||
|
||||
|
||||
async def test_mock_device_blank_path_traces() -> None:
|
||||
"""A blank/auto path still produces a successful, non-empty trace."""
|
||||
device = MockDevice()
|
||||
await device.connect()
|
||||
# Try several times since the simulator drops very weak links occasionally.
|
||||
results = [await device.run_trace("Alice") for _ in range(10)]
|
||||
assert any(r.success and r.hops for r in results)
|
||||
|
||||
|
||||
def test_trace_edges_endpoints_are_our_device() -> None:
|
||||
"""The first edge originates at us and the last edge returns to us (#3/#4)."""
|
||||
from meshtools.core.models import Hop
|
||||
|
||||
result = TraceResult(
|
||||
target="Alice",
|
||||
success=True,
|
||||
hops=[Hop(0, "3d", 5.0), Hop(1, "f2", 1.0), Hop(2, None, -1.0)],
|
||||
)
|
||||
edges = result.edges(device_label="us")
|
||||
assert [(e.origin, e.destination) for e in edges] == [
|
||||
("us", "3d"),
|
||||
("3d", "f2"),
|
||||
("f2", "us"),
|
||||
]
|
||||
assert [e.snr for e in edges] == [5.0, 1.0, -1.0]
|
||||
|
||||
|
||||
def test_trace_stats_reports_per_hop_medians() -> None:
|
||||
"""Aggregation yields a median SNR for every hop position (#5)."""
|
||||
from meshtools.core.models import Hop
|
||||
|
||||
traces = [
|
||||
TraceResult(target="x", success=True, hops=[Hop(0, "a", 4.0), Hop(1, None, 0.0)]),
|
||||
TraceResult(target="x", success=True, hops=[Hop(0, "a", 8.0), Hop(1, None, 2.0)]),
|
||||
]
|
||||
stats = TraceStats.from_traces("x", traces)
|
||||
# Node identities are raw (None = our device) so a label is applied at render time.
|
||||
assert [(h.origin, h.destination, h.median_snr) for h in stats.hop_snrs] == [
|
||||
(None, "a", 6.0),
|
||||
("a", None, 1.0),
|
||||
]
|
||||
|
||||
|
||||
async def test_mock_device_trace_is_unimodal_in_tx() -> None:
|
||||
"""The simulator peaks near its optimal TX power (averaged over noise)."""
|
||||
device = MockDevice(optimal_tx=14)
|
||||
@@ -91,6 +248,191 @@ def test_tx_plot_writes_html(tmp_path: Path) -> None:
|
||||
assert path.stat().st_size > 1000 # plotly.js inlined → non-trivial size
|
||||
|
||||
|
||||
class _Event:
|
||||
def __init__(self, payload: dict) -> None:
|
||||
self.payload = payload
|
||||
|
||||
def is_error(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _mc_with(contacts: dict, path_hash_mode: int = 2):
|
||||
"""Build a minimal mock ``MeshCore`` client exposing the trace commands used."""
|
||||
|
||||
class _Commands:
|
||||
async def get_contacts(self) -> _Event:
|
||||
return _Event(contacts)
|
||||
|
||||
async def get_path_hash_mode(self) -> int:
|
||||
return path_hash_mode
|
||||
|
||||
class _MC:
|
||||
commands = _Commands()
|
||||
|
||||
return _MC()
|
||||
|
||||
|
||||
async def test_three_byte_route_appends_destination_hash() -> None:
|
||||
"""A learned multi-hop route walks the repeaters then ends at the target (#1).
|
||||
|
||||
Two things matter for a non-power-of-two region (3-byte hashes): each 3-byte
|
||||
routing hash collapses to its leading 2 bytes (the widest representable trace
|
||||
width), and the destination's own hash is appended as the final hop — a trace
|
||||
only replies when its destination is the last hop.
|
||||
"""
|
||||
from meshtools.core.connection import MeshCoreDevice
|
||||
|
||||
mc = _mc_with(
|
||||
{
|
||||
"Repeater": {
|
||||
"adv_name": "Repeater",
|
||||
"public_key": "aabbcc" + "00" * 29,
|
||||
# Two hops, each a 3-byte routing hash (mode 2 => size 3).
|
||||
"out_path": "112233445566",
|
||||
"out_path_len": 2,
|
||||
"out_path_hash_mode": 2,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
device = MeshCoreDevice(port="COM-test")
|
||||
resolved = await device._trace_path_to_contact(mc, "Repeater")
|
||||
assert resolved is not None
|
||||
path_bytes, flags = resolved
|
||||
# Two repeater hops collapsed to 2 bytes, then the target's own 2-byte hash.
|
||||
assert path_bytes == bytes.fromhex("1122" "4455" "aabb")
|
||||
assert flags == trace_runner.path_hash_flags(2) # 2-byte width
|
||||
|
||||
|
||||
async def test_direct_neighbor_resolves_to_destination_hash() -> None:
|
||||
"""A direct neighbor (no learned route) resolves to a single destination hop.
|
||||
|
||||
Verified on hardware: these contacts report ``out_path_len == -1`` (no stored
|
||||
route) yet answer a single-hop trace addressed to their own hash. With the
|
||||
contact's mode unknown (-1) the region's path-hash mode (3-byte) sets the width,
|
||||
collapsed to the representable 2 bytes.
|
||||
"""
|
||||
from meshtools.core.connection import MeshCoreDevice
|
||||
|
||||
mc = _mc_with(
|
||||
{
|
||||
"Neighbor": {
|
||||
"adv_name": "Neighbor",
|
||||
"public_key": "3d63c6" + "00" * 29,
|
||||
# Direct neighbor as the firmware reports it: no learned route.
|
||||
"out_path": "",
|
||||
"out_path_len": -1,
|
||||
"out_path_hash_mode": -1,
|
||||
}
|
||||
},
|
||||
path_hash_mode=2,
|
||||
)
|
||||
|
||||
device = MeshCoreDevice(port="COM-test")
|
||||
resolved = await device._trace_path_to_contact(mc, "Neighbor")
|
||||
assert resolved is not None
|
||||
path_bytes, flags = resolved
|
||||
# Just the target's own hash, region width 3 collapsed to a 2-byte trace hop.
|
||||
assert path_bytes == bytes.fromhex("3d63")
|
||||
assert flags == trace_runner.path_hash_flags(2)
|
||||
|
||||
|
||||
async def test_unknown_contact_resolves_to_none() -> None:
|
||||
"""An unrecognized target yields ``None`` so the trace can fall back to path-less."""
|
||||
from meshtools.core.connection import MeshCoreDevice
|
||||
|
||||
mc = _mc_with(
|
||||
{
|
||||
"Somebody": {
|
||||
"adv_name": "Somebody",
|
||||
"public_key": "abcdef" + "00" * 29,
|
||||
"out_path": "",
|
||||
"out_path_len": -1,
|
||||
"out_path_hash_mode": -1,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
device = MeshCoreDevice(port="COM-test")
|
||||
resolved = await device._trace_path_to_contact(mc, "Nobody")
|
||||
assert resolved is None
|
||||
|
||||
|
||||
async def test_contacts_payload_retries_transient_error() -> None:
|
||||
"""A transient 'no event received' on contacts retrieval is retried, not fatal."""
|
||||
from meshtools.core.connection import MeshCoreDevice
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
class _Err:
|
||||
payload = {"reason": "no event received during contacts retrieval"}
|
||||
|
||||
def is_error(self) -> bool:
|
||||
return True
|
||||
|
||||
class _Ok:
|
||||
payload = {"Repeater": {"adv_name": "Repeater", "public_key": "aabbcc" + "00" * 29}}
|
||||
|
||||
def is_error(self) -> bool:
|
||||
return False
|
||||
|
||||
class _Commands:
|
||||
async def get_contacts(self): # noqa: ANN202
|
||||
calls["n"] += 1
|
||||
return _Err() if calls["n"] < 3 else _Ok()
|
||||
|
||||
class _MC:
|
||||
commands = _Commands()
|
||||
|
||||
device = MeshCoreDevice(port="COM-test")
|
||||
payload = await device._contacts_payload(_MC(), retries=3, delay=0)
|
||||
assert "Repeater" in payload
|
||||
assert calls["n"] == 3 # failed twice, succeeded on the third attempt
|
||||
|
||||
|
||||
async def test_contacts_payload_raises_clean_error_after_retries() -> None:
|
||||
"""Persistent contacts-retrieval failure raises a clean, actionable error."""
|
||||
from meshtools.core.connection import DeviceCommandError, MeshCoreDevice
|
||||
|
||||
class _Err:
|
||||
payload = {"reason": "no event received during contacts retrieval"}
|
||||
|
||||
def is_error(self) -> bool:
|
||||
return True
|
||||
|
||||
class _Commands:
|
||||
async def get_contacts(self): # noqa: ANN202
|
||||
return _Err()
|
||||
|
||||
class _MC:
|
||||
commands = _Commands()
|
||||
|
||||
device = MeshCoreDevice(port="COM-test")
|
||||
with pytest.raises(DeviceCommandError) as exc:
|
||||
await device._contacts_payload(_MC(), retries=2, delay=0)
|
||||
assert "no event received" in str(exc.value)
|
||||
|
||||
|
||||
async def test_latest_trace_returns_previous_run(tmp_path: Path) -> None:
|
||||
"""latest_trace rehydrates the most recent stored trace, excluding a given run."""
|
||||
from meshtools.core.models import Hop
|
||||
|
||||
repo = Repository(tmp_path / "prev.db")
|
||||
old_run = repo.start_run("trace", {"target": "Alice"})
|
||||
repo.record_trace(
|
||||
old_run,
|
||||
TraceResult(target="Alice", success=True, hops=[Hop(0, "3d", 4.0), Hop(1, None, 1.0)]),
|
||||
)
|
||||
new_run = repo.start_run("trace", {"target": "Alice"})
|
||||
|
||||
prev = repo.latest_trace("Alice", exclude_run_id=new_run)
|
||||
assert prev is not None
|
||||
assert [h.node for h in prev.hops] == ["3d", None]
|
||||
assert prev.edges("us")[-1].destination == "us"
|
||||
assert repo.latest_trace("Nobody") is None
|
||||
repo.close()
|
||||
|
||||
|
||||
async def test_repository_round_trip(tmp_path: Path) -> None:
|
||||
"""A run and its traces persist and read back."""
|
||||
repo = Repository(tmp_path / "test.db")
|
||||
|
||||
Reference in new issue
Block a user