Files
tthandClaude Opus 5.5 e2d3c72ba2 1.1.0: default interval 8 h, minimum 1 h
A repeater's battery, temperature and noise do not change by the hour, and
every reading is airtime on a channel everyone shares. The dashboard window
follows: 24 h by default (2-3x the interval), staleness thresholds too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:41:54 +01:00

164 lines
5.6 KiB
Python

"""Configuration and parsing -- no radio, no network."""
import os
import subprocess
import sys
from pathlib import Path
import pytest
import meshcore_exporter as mx
ROOT = Path(__file__).resolve().parent.parent
def settings(argv, monkeypatch, env=None):
for k in [k for k in os.environ if k.startswith("MC_")]:
monkeypatch.delenv(k)
for k, v in (env or {}).items():
monkeypatch.setenv(k, v)
return mx.resolve(mx.build_parser().parse_args(argv))
def test_targets_syntax():
t = mx.parse_targets("a, b=ABCD, c=ef01@5361, d@6162", "pw")
assert [(x.name, x.pubkey, x.path, x.password) for x in t] == [
("a", "", "", "pw"),
("b", "abcd", "", "pw"),
("c", "ef01", "5361", "pw"),
("d", "", "6162", "pw"),
]
def test_cli_minimal(monkeypatch):
s = settings(["--serial", "/dev/x", "--repeaters", "rpt", "--password", "pw"], monkeypatch)
assert s.serial == "/dev/x" and s.interval == mx.DEFAULT_INTERVAL and s.port == 9200
assert s.targets[0].password == "pw" and s.path_hash_bytes is None
def test_env_twins(monkeypatch):
s = settings(
[], monkeypatch, {"MC_TCP": "h:5000", "MC_REPEATERS": "rpt", "MC_INTERVAL": "7200", "MC_PATH_HASH_BYTES": "2"}
)
assert s.tcp == "h:5000" and s.interval == 7200 and s.path_hash_bytes == 2
def test_interval_floor(monkeypatch):
s = settings(["--serial", "/dev/x", "--repeaters", "r", "--interval", "10"], monkeypatch)
assert s.interval == mx.MIN_INTERVAL
@pytest.mark.parametrize(
"argv",
[
["--repeaters", "r"], # no companion
["--serial", "/dev/x", "--tcp", "h:1", "--repeaters", "r"], # two companions
["--serial", "/dev/x"], # no repeater
],
)
def test_bad_setup(argv, monkeypatch):
with pytest.raises(ValueError):
settings(argv, monkeypatch)
def test_toml(tmp_path, monkeypatch):
f = tmp_path / "r.toml"
f.write_text(
'serial = "/dev/y"\ninterval = 7200\npassword = "common"\n'
'[[repeater]]\nname = "one"\n'
'[[repeater]]\nname = "two"\npassword = "own"\npath = "5361"\n'
)
s = settings(["--config", str(f)], monkeypatch)
assert s.serial == "/dev/y" and s.interval == 7200
assert [(t.name, t.password, t.path) for t in s.targets] == [("one", "common", ""), ("two", "own", "5361")]
# the command line wins over the file
s = settings(["--config", str(f), "--interval", "10800"], monkeypatch)
assert s.interval == 10800
def test_example_toml_loads(monkeypatch):
s = settings(["--config", str(ROOT / "repeaters.example.toml")], monkeypatch)
assert s.targets
def test_status_extension():
pytest.importorskip("meshcore")
import meshcore.parsing as parsing
mx.extend_status_parser()
frame = bytes(8) + bytes(56) + (7).to_bytes(4, "little") + (3).to_bytes(4, "little")
res = parsing.parse_status(frame)
assert (res["tx_start_fail"], res["tx_timeout"]) == (7, 3)
assert parsing.parse_status(bytes(8) + bytes(56))["tx_timeout"] is None
def test_help_without_dependencies():
# --help must work before meshcore/prometheus_client are installed
code = (
"import sys, builtins; real = builtins.__import__\n"
"def imp(n, *a, **k):\n"
" if n.split('.')[0] in ('meshcore', 'prometheus_client'): raise ImportError(n)\n"
" return real(n, *a, **k)\n"
"builtins.__import__ = imp; sys.argv = ['x', '--help']\n"
"import runpy; runpy.run_path('meshcore_exporter.py', run_name='__main__')"
)
r = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True)
assert r.returncode == 0 and "--repeaters" in r.stdout
def test_round_returns_failed_targets(monkeypatch):
import asyncio
s = settings(["--serial", "/dev/x", "--repeaters", "good,bad"], monkeypatch)
ex = mx.Exporter(s, None)
async def read(mc, t):
if t.name == "bad":
raise RuntimeError("login failed")
return {"bat": 4100.0}
monkeypatch.setattr(ex, "read", read)
failed = asyncio.run(ex.round(None))
assert [t.name for t in failed] == ["bad"]
assert asyncio.run(ex.round(None, failed)) == failed
def test_contacts_fetched_once_per_round(monkeypatch):
import asyncio
from types import SimpleNamespace
pytest.importorskip("meshcore")
from meshcore import EventType
calls = []
async def get_contacts(timeout=5):
calls.append(timeout)
payload = {"a": {"adv_name": "one", "public_key": "aa" * 32}, "b": {"adv_name": "two", "public_key": "bb" * 32}}
return SimpleNamespace(type=EventType.CONTACTS, payload=payload)
mc = SimpleNamespace(commands=SimpleNamespace(get_contacts=get_contacts))
s = settings(["--serial", "/dev/x", "--repeaters", "one,two=bbbb"], monkeypatch)
ex = mx.Exporter(s, None)
ex._contact_list = None
for t in s.targets:
assert asyncio.run(ex.contact(mc, t))["adv_name"] == t.name
assert calls == [mx.CONTACTS_TIMEOUT]
def test_list_ports_skips_non_usb(monkeypatch, capsys):
from types import SimpleNamespace
pytest.importorskip("serial")
from serial.tools import list_ports
fake = [
SimpleNamespace(device="/dev/ttyS0", description="n/a", vid=None, pid=None, serial_number=None),
SimpleNamespace(device="COM7", description="XIAO nRF52840", vid=0x2886, pid=0x8044, serial_number="AB12"),
]
monkeypatch.setattr(list_ports, "comports", lambda: fake)
assert mx.list_ports() == 0
out = capsys.readouterr().out
assert "COM7" in out and "2886:8044" in out and "AB12" in out and "/dev/ttyS0" not in out
assert "1 non-USB" in out