Spaces:
Running

Virtual-LPU / tests /test_08_desktop.py
iparaco's picture
Upload 118 files
e59bd9d verified
Raw History Blame Contribute Delete
11.4 kB
"""Test 08 — Native desktop app (V7.1.1).
Covers everything testable headless:
- server-thread lifecycle (start -> ready -> /api/status -> clean stop)
- attach detection (is_lpu_server_running true/false, non-LPU port skip)
- port finding (free port picked; LPU port reused for attach; foreign port
skipped without hijacking)
- fallback routing: without pywebview, launch_desktop resolves to
browser-fallback and NEVER fabricates a native window
- V7.1.1: window-creation failure (pywebview present but create_window
raises) degrades to browser-fallback with the reason printed
- V7.1.1: fallback serve loop unwinds via request_shutdown() in-process
- V7.1.1: fallback opens the dashboard even when ATTACHED to an
already-running accelerator (previously exited silently)
- V7.1.1: .cmd launchers exist and call python.exe explicitly (the
Electron/VS Code .py-association fix)
- run_lpu.py --desktop wiring (argparse routing, no window needed)
The native window itself (WebView2) is hardware/OS-gated: exercised on the
rig per docs/INSTALL_WINDOWS.md.
"""
from __future__ import annotations
import socket
import sys
import threading
import time
import urllib.request
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import desktop_app
from desktop_app import (ServerThread, _get_status, _pywebview,
find_port, is_lpu_server_running)
from server.app import create_app
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
@pytest.fixture()
def lpu_server(config):
# the desktop app always boots the full stack -> autostart the service
cfg = dict(config)
cfg["accelerator"] = {**cfg["accelerator"], "autostart": True}
cfg["monitoring"] = {**cfg.get("monitoring", {}), "autostart": True}
app = create_app(cfg)
port = _free_port()
st = ServerThread(app, "127.0.0.1", port)
assert st.start(timeout=15.0) is True
yield st, port
st.stop()
assert not st.thread.is_alive(), "server thread must exit cleanly"
def test_server_thread_lifecycle(lpu_server):
st, port = lpu_server
status = _get_status("127.0.0.1", port)
assert status is not None
assert status["runtime_version"].startswith("7.")
assert status["accelerator_status"] == "running"
def test_stop_never_leaves_thread(lpu_server):
st, _ = lpu_server
st.stop()
assert not st.thread.is_alive()
# port actually released (bindable again; OS may hold it briefly)
deadline = time.time() + 5
while True:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# SO_REUSEADDR mirrors what a real restart would set; without
# it, TIME_WAIT connections of the old listener block the bind
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", st.port))
return
except OSError:
if time.time() > deadline:
raise
time.sleep(0.2)
def test_attach_detection(lpu_server):
st, port = lpu_server
assert is_lpu_server_running("127.0.0.1", port) is True
assert is_lpu_server_running("127.0.0.1", _free_port()) is False
def test_find_port_attaches_to_running_lpu(lpu_server):
st, port = lpu_server
# when the accelerator already owns a port in the range, find_port
# must return exactly that port (attach, no duplicate server)
assert find_port("127.0.0.1", port) == port
def test_find_port_skips_foreign_ports():
# occupy a port with a NON-LPU listener
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 0))
port = srv.getsockname()[1]
srv.listen(1)
def _accept_later():
try:
srv.accept()
except OSError:
pass
threading.Thread(target=_accept_later, daemon=True).start()
chosen = find_port("127.0.0.1", port)
assert chosen != port, "a foreign service's port must be skipped, not hijacked"
srv.close()
def test_pywebview_absent_here_is_honest():
webview = _pywebview()
if webview is not None:
pytest.skip("pywebview present in this environment")
# no fabrication: absence is reported, never a fake native window
assert _pywebview() is None
def test_launch_desktop_fallback_unwinds_via_request_shutdown(config,
monkeypatch):
"""V7.1.1 core fix: the fallback serve loop must unwind when
request_shutdown() is called (in-process, no thread killing), with the
server cleanly stopped afterwards."""
if _pywebview() is not None:
pytest.skip("pywebview present in this environment")
port = _free_port()
result = {}
monkeypatch.setattr("webbrowser.open", lambda url: None,
raising=False)
th = threading.Thread(
target=lambda: result.update(
desktop_app.launch_desktop(config, host="127.0.0.1",
start_port=port,
fallback_open_browser=True)),
daemon=True)
th.start()
# wait for the server to be serving, then trigger in-process shutdown
deadline = time.time() + 15
while time.time() < deadline:
if _get_status("127.0.0.1", port):
break
time.sleep(0.2)
assert _get_status("127.0.0.1", port) is not None, \
"fallback must still serve the dashboard"
desktop_app.request_shutdown()
th.join(timeout=10)
assert not th.is_alive(), "serve loop must unwind after request_shutdown()"
assert result.get("mode") == "browser-fallback"
assert result.get("port") == port
def test_launch_desktop_window_failure_falls_back(config, monkeypatch):
"""V7.1.1: pywebview present but create_window raises -> honest
browser-fallback with the reason printed, never a silent exit."""
port = _free_port()
result = {}
printed = []
monkeypatch.setattr("webbrowser.open", lambda url: None, raising=False)
monkeypatch.setattr(desktop_app, "_pywebview",
lambda: _FakeWebview(raise_at="start"))
monkeypatch.setattr(builtins_print_target(), "print", lambda *a, **k:
printed.append(" ".join(str(x) for x in a))
if a and ("pywebview" in str(a[0])
or "native window" in str(a[0])
or "Accelerator server" in str(a[0])
or "stopped" in str(a[0])) else None)
th = threading.Thread(
target=lambda: result.update(
desktop_app.launch_desktop(config, host="127.0.0.1",
start_port=port,
fallback_open_browser=True)),
daemon=True)
th.start()
deadline = time.time() + 15
while time.time() < deadline:
if _get_status("127.0.0.1", port):
break
time.sleep(0.2)
assert _get_status("127.0.0.1", port) is not None, \
"window-failure fallback must still serve the dashboard"
desktop_app.request_shutdown()
th.join(timeout=10)
assert not th.is_alive()
assert result.get("mode") == "browser-fallback", \
"window failure must degrade to browser-fallback, not crash"
reason = " ".join(printed)
assert "native window unavailable" in reason, \
"the failure reason must be printed honestly"
def test_launch_desktop_attached_fallback_opens_dashboard(lpu_server,
monkeypatch):
"""V7.1.1: attach + no pywebview -> the ALREADY-RUNNING accelerator's
dashboard opens in the browser; previously this exited silently."""
st, port = lpu_server
opened = []
monkeypatch.setattr("webbrowser.open", lambda url: opened.append(url),
raising=False)
if _pywebview() is not None:
pytest.skip("pywebview present in this environment")
# attached session: nothing to stop, returns immediately after opening
result = desktop_app.launch_desktop({}, host="127.0.0.1",
start_port=port,
fallback_open_browser=True)
assert result["mode"] == "browser-fallback"
assert result["port"] == port
assert opened == [f"http://127.0.0.1:{port}"], \
"attached fallback must open the running accelerator's dashboard"
def test_run_lpu_desktop_flag_routes(monkeypatch, config):
"""`run_lpu.py --desktop` must call desktop_app.main with the CLI args."""
called = {}
def _fake_main(argv):
called["argv"] = argv
return 0
monkeypatch.setattr("desktop_app.main", _fake_main)
import run_lpu
monkeypatch.setattr(sys, "argv", ["run_lpu.py", "--desktop",
"--port", "8712"])
rc = run_lpu.main()
assert rc == 0
assert called["argv"][0] == "--host"
assert "--desktop" not in called["argv"]
def test_desktop_entry_module_imports():
spec_path = Path(__file__).resolve().parent.parent / "run_lpu_desktop.py"
assert spec_path.exists()
compile(spec_path.read_text(encoding="utf-8"), str(spec_path), "exec")
def test_cmd_launchers_call_python_explicitly():
"""V7.1.1: the .cmd launchers must exist and invoke python.exe directly
(the Electron/VS Code .py-association fix)."""
root = Path(__file__).resolve().parent.parent
for name, needle in (("LPU_Desktop.cmd", "--desktop"),
("LPU_Server.cmd", "run_lpu.py"),
("LPU_Check.cmd", "--check")):
path = root / name
assert path.exists(), f"{name} missing"
body = path.read_text(encoding="utf-8", errors="replace")
assert "python.exe" in body, \
f"{name} must call python.exe explicitly"
assert needle in body, f"{name} must pass {needle}"
# launcher must never rely on the .py association: no bare '.\\run_lpu.py'
assert "py -3" in body or "%PY%" in body
def test_native_mode_needs_display_or_pywebview():
"""Honest gating: the native window can only be created where a GUI
backend exists; the rig run exercises it for real."""
if _pywebview() is not None:
pytest.skip("pywebview available - native mode runnable here")
pytest.skip("hardware-gated: native WebView2 window needs the rig "
"(pywebview + display); everything else tested for real")
# --- helpers -----------------------------------------------------------
class _FakeWebview:
"""Callable stub simulating a pywebview module whose window creation
fails (e.g. no WebView2 runtime / no display)."""
def __init__(self, raise_at: str):
self._raise_at = raise_at
def create_window(self, *a, **k):
if self._raise_at == "create":
raise RuntimeError("no WebView2 runtime found")
return object()
def start(self):
if self._raise_at == "start":
raise RuntimeError("GUI backend failed to start")
raise RuntimeError("unreachable in tests")
def builtins_print_target():
import builtins
return builtins