Files
xenia-pos-local/local_backend/tests/test_lan_ip.py
T
bonaminandClaude Opus 5.5 f00c99fd36 test: unit tests for licensing, LAN IP, TLS identity and rediscovery
- local_backend/tests (pytest, 48 tests, <1s): license token verify/evaluate
  (tamper, other site/key, offline, grace, workday deferral, clock, transition),
  netinfo detection on fake sysfs (VPN/tunnel/WiFi/link-local), LAN-IP
  resolver priority + mismatch + staleness + override validation, TLS
  identity create/restart/renew-same-key/foreign cert (+ openssl pin check)
- waiter_pwa/tests (node --test, 7 tests): subnet candidates, scan picks only
  this venue, early stop, progress
- requirements-dev.txt (pytest), npm test, .pytest_cache ignored

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:33:16 +03:00

104 lines
4.7 KiB
Python

"""Which LAN IP phones get: netinfo detection (fake sysfs) + resolver priority (services/lan_ip.py)."""
import json
import os
from datetime import datetime, timedelta, timezone
import pytest
from services.lan_ip import read_detected, resolve_lan_ip, validate_lan_ip
from services.netinfo_helper import detect
ADDRS = {"eth0": "10.98.20.70", "wlan0": "192.168.1.44", "wg0": "10.9.9.2", "docker0": "172.17.0.1",
"tailscale0": "100.101.1.2", "enp3s0": "169.254.10.1"}
def fake_host(tmp_path, physical, default_if):
"""sysfs where only `physical` interfaces have a device/ entry, and a route table."""
sysnet = tmp_path / "net"
for name in ["lo", "docker0", "wg0", "tailscale0"]:
(sysnet / name).mkdir(parents=True)
for name in physical:
(sysnet / name / "device").mkdir(parents=True)
route = tmp_path / "route"
lines = ["Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask"]
if default_if:
lines.append(f"{default_if}\t00000000\t0114620A\t0003\t0\t0\t100\t00000000")
route.write_text("\n".join(lines) + "\n")
return str(sysnet), str(route)
# ── netinfo detection: physical NIC only, never a VPN ────────────────────────
@pytest.mark.parametrize("physical,default_if,want", [
(["eth0"], "eth0", "10.98.20.70"), # wg-quick full tunnel: main default via eth0
(["eth0"], "wg0", "10.98.20.70"), # tunnel owns the default route
(["eth0"], "tailscale0", "10.98.20.70"),
(["eth0"], None, "10.98.20.70"), # offline LAN-only box
(["wlan0"], "wlan0", "192.168.1.44"), # WiFi-only server
(["eth0", "wlan0"], "wlan0", "192.168.1.44"), # two NICs: the default-route one wins
(["enp3s0", "wlan0"], None, "192.168.1.44"), # link-local address ignored
([], "wg0", None), # no physical NIC → nothing (never the VPN)
])
def test_detect_physical_nic(tmp_path, physical, default_if, want):
sysnet, route = fake_host(tmp_path, physical, default_if)
assert detect(sysnet, route, ipv4=ADDRS.get)["ip"] == want
# ── resolver priority + mismatch ─────────────────────────────────────────────
FRESH = {"ip": "10.98.20.70", "candidates": [{"iface": "eth0", "ip": "10.98.20.70"}], "stale": False}
def test_detected_beats_stale_host_ip():
r = resolve_lan_ip(override=None, detected=FRESH, env="10.98.20.99")
assert (r["effective"], r["source"]) == ("10.98.20.70", "detected")
def test_override_wins_and_flags_mismatch():
r = resolve_lan_ip(override="192.168.1.50", detected=FRESH, env=None)
assert (r["effective"], r["source"], r["mismatch"]) == ("192.168.1.50", "override", True)
def test_override_matching_nic_no_mismatch():
assert resolve_lan_ip(override="10.98.20.70", detected=FRESH, env=None)["mismatch"] is False
def test_docker_desktop_falls_back_to_host_ip():
r = resolve_lan_ip(override=None, detected={"ip": None, "unsupported": "docker-desktop", "candidates": [], "stale": False},
env="10.98.20.70")
assert (r["effective"], r["source"], r["detection"]) == ("10.98.20.70", "env", "unsupported")
def test_stale_detection_ignored():
r = resolve_lan_ip(override=None, detected={**FRESH, "stale": True}, env="10.98.20.70")
assert (r["source"], r["detection"]) == ("env", "stale")
def test_nothing_known():
r = resolve_lan_ip(override=None, detected=None, env=None)
assert (r["effective"], r["source"], r["detection"]) == (None, None, "unavailable")
def test_read_detected_staleness(tmp_path):
f = tmp_path / "host_ip.json"
now = datetime.now(timezone.utc)
f.write_text(json.dumps({"ip": "10.98.20.70", "candidates": [], "detected_at": (now - timedelta(seconds=30)).isoformat()}))
assert read_detected(str(f), now)["stale"] is False
f.write_text(json.dumps({"ip": "10.98.20.70", "candidates": [], "detected_at": (now - timedelta(minutes=10)).isoformat()}))
assert read_detected(str(f), now)["stale"] is True
assert read_detected(os.path.join(tmp_path, "missing.json"), now) is None
# ── override validation ──────────────────────────────────────────────────────
@pytest.mark.parametrize("ip,ok", [
("192.168.1.50", True), (" 10.0.0.5 ", True), ("172.16.4.4", True),
("8.8.8.8", False), ("127.0.0.1", False), ("169.254.1.1", False), ("fd00::1", False), ("abc", False),
])
def test_validate_lan_ip(ip, ok):
if ok:
validate_lan_ip(ip)
else:
with pytest.raises(ValueError):
validate_lan_ip(ip)