Files
meshcore-exporter/tests/test_config.py
T
tthandClaude Opus 5.5 2a9126e258
ci / test (push) Successful in 1m12s
image / build (arm64) (push) Successful in 1m52s
image / build (amd64) (push) Successful in 2m1s
image / release (push) Successful in 9s
meshcore-exporter 1.0.0
Prometheus exporter for MeshCore repeaters, read over the mesh: a companion
(USB, BLE, or a companion identity in openHop over TCP) logs in to each
repeater, asks for status and telemetry with direct packets and serves
battery, temperature/humidity, noise floor, RSSI/SNR, packet counters,
airtime and uptime on :9200/metrics.

- meshcore_exporter.py: command line, MC_* environment or a TOML file with
  a password per repeater; --check reads every repeater once and exits;
  interval 1 h (min 15 min); a failed repeater is retried once after 3 min;
  contacts fetched once per round.
- dashboards/: the Grafana dashboard, generated from generate.py
  (datasource, job and the rate window are variables; TX drawn above zero,
  RX below).
- stack/: Docker Compose with Prometheus and Grafana provisioned, for a USB
  companion, or on the host network for openHop on the same machine.
- systemd/: running without Docker.
- README.md (Czech) and AGENTS.md for setting it up with an AI agent.
- CI: lint and tests, gitleaks; PR check builds the image; single-platform
  images per architecture behind a Trivy gate (latest-<arch>, and X.Y.Z-<arch>
  with a release on tag vX.Y.Z); dependencies by Renovate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:52:21 +01:00

147 lines
4.9 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": "1800", "MC_PATH_HASH_BYTES": "2"}
)
assert s.tcp == "h:5000" and s.interval == 1800 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 = 1800\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 == 1800
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", "2400"], monkeypatch)
assert s.interval == 2400
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]