feat: stream startup stages to the launcher over a progress socket

This commit is contained in:
wyzula_j authored and Klaus Wakonig committed 2026-08-25 13:45:27 +02:00
1 parent a00b0c40e3
commit d6e523eea4
11 files changed
+482 -1

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
"""Unit tests for the GUI-server startup handshake wiring in companion_app."""
from __future__ import annotations
from types import SimpleNamespace
from bec_widgets.applications import companion_app
def _server(**overrides):
args = SimpleNamespace(
config=None, id="test", gui_class=None, gui_class_id="bec", hide=False, **overrides
)
return companion_app.GUIServer(args)
def test_notify_server_ready_resolves_launcher(monkeypatch):
calls = []
monkeypatch.setattr(
"bec_widgets.utils.launcher_ready.notify_launcher_ready",
lambda app_name, window: calls.append((app_name, window)) or True,
)
marks = []
monkeypatch.setattr(
companion_app.startup_profiler, "mark", lambda stage, **kw: marks.append((stage, kw))
)
server = _server()
sentinel_window = object()
server.launcher_window = sentinel_window
server._notify_server_ready()
# The GUI-server path sends the ready edge itself (safety net for launches with no
# auto-launched gui_class window) and records the final startup stage.
assert calls == [("bec-gui-server", sentinel_window)]
assert ("interactive", {"final": True}) in marks
+128
View File
@@ -0,0 +1,128 @@
"""Unit tests for the launch-progress socket client (child side)."""
from __future__ import annotations
import json
import os
import socket
import pytest
from bec_widgets.utils import launch_progress as lp
def _short_socket_path(suffix: str = "") -> str:
# AF_UNIX paths are length-limited (~104 on macOS); keep it short and under /tmp.
return f"/tmp/bec-lp-{os.getpid()}-{suffix or 'x'}.sock"
class _Server:
"""Minimal single-connection AF_UNIX server for assertions."""
def __init__(self, path: str):
self.path = path
self._srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._srv.settimeout(2.0)
self._srv.bind(path)
self._srv.listen(1)
self._conn: socket.socket | None = None
def read_lines(self) -> list[dict]:
if self._conn is None:
self._conn, _ = self._srv.accept()
self._conn.settimeout(2.0)
chunks = b""
while True:
try:
data = self._conn.recv(65536)
except socket.timeout:
break
if not data:
break
chunks += data
# Heuristic: stop once we have drained what's buffered.
if len(data) < 65536:
break
return [json.loads(line) for line in chunks.decode().splitlines() if line.strip()]
def close(self) -> None:
for sock in (self._conn, self._srv):
if sock is not None:
try:
sock.close()
except OSError:
pass
try:
os.unlink(self.path)
except OSError:
pass
@pytest.fixture
def server():
srv = _Server(_short_socket_path("srv"))
try:
yield srv
finally:
srv.close()
def _client_env(monkeypatch, path: str, token: str = "tok-123", app: str = "bec-app"):
monkeypatch.setenv(lp.SOCKET_ENV, path)
monkeypatch.setenv(lp.TOKEN_ENV, token)
monkeypatch.setenv(lp.APP_ENV, app)
def test_client_is_noop_without_env(monkeypatch):
monkeypatch.delenv(lp.SOCKET_ENV, raising=False)
monkeypatch.delenv(lp.TOKEN_ENV, raising=False)
client = lp.LaunchProgressClient()
assert client.enabled is False
assert client.emit_stage("module imports", 10, 10) is False
assert client.emit_ready() is False
def test_client_streams_hello_stage_and_ready(monkeypatch, server):
_client_env(monkeypatch, server.path, token="tok-abc", app="bec-app")
client = lp.LaunchProgressClient()
assert client.enabled is True
assert client.emit_stage("module imports", 6210.4, 6210.4) is True
assert client.emit_stage("BEC connection", 18400.0, 24610.4) is True
assert client.emit_ready(27710.0) is True
messages = server.read_lines()
assert messages[0]["t"] == "hello"
assert messages[0]["token"] == "tok-abc"
assert messages[0]["app"] == "bec-app"
assert messages[0]["pid"] == os.getpid()
stages = [m for m in messages if m["t"] == "stage"]
assert [s["name"] for s in stages] == ["module imports", "BEC connection"]
assert stages[0]["delta_ms"] == 6210.4
assert stages[0]["total_ms"] == 6210.4
ready = [m for m in messages if m["t"] == "ready"]
assert ready and ready[0]["total_ms"] == 27710.0
def test_client_never_raises_on_bad_socket(monkeypatch):
_client_env(monkeypatch, _short_socket_path("nonexistent"))
client = lp.LaunchProgressClient()
# No server is listening at the path -> connect fails, but nothing raises.
assert client.emit_stage("module imports", 1, 1) is False
assert client.enabled is False # disabled after the failed connect
assert client.emit_ready() is False
def test_client_disables_after_server_disconnect(monkeypatch, server):
_client_env(monkeypatch, server.path)
client = lp.LaunchProgressClient()
assert client.emit_stage("first", 1, 1) is True
# Force the server to drop the connection.
server.read_lines()
server.close()
# Subsequent sends eventually fail and disable the client without raising.
for _ in range(5):
client.emit_stage("later", 2, 2)
assert client.emit_ready() is False
+16
View File
@@ -131,6 +131,22 @@ def test_open_dock_area_with_start_empty_option_calls_launch(bec_launch_window):
mock_launch.assert_called_once_with("dock_area", startup_profile=None)
def test_launch_window_notifies_launcher_ready(qtbot, bec_launch_window, monkeypatch):
calls = []
monkeypatch.setattr(
"bec_widgets.utils.launcher_ready.notify_launcher_ready",
lambda app_name, window: calls.append((app_name, window)) or True,
)
window = QWidget()
qtbot.addWidget(window)
window.show()
bec_launch_window._notify_launcher_ready(window)
qtbot.wait(10)
assert calls == [("bec-gui-server", window)]
@pytest.mark.parametrize(
"connection_names, hide",
[
+50
View File
@@ -0,0 +1,50 @@
"""Unit tests for ``notify_launcher_ready`` (routes the ready edge over the socket)."""
from __future__ import annotations
import os
import socket
from bec_widgets.utils import launcher_ready
from bec_widgets.utils.launch_progress import LaunchProgressClient
def _short_socket_path() -> str:
return f"/tmp/bec-ready-{os.getpid()}.sock"
def test_notify_launcher_ready_noops_without_env(monkeypatch):
monkeypatch.delenv("BEC_LAUNCH_PROGRESS_SOCKET", raising=False)
monkeypatch.delenv("BEC_LAUNCH_PROGRESS_TOKEN", raising=False)
# A freshly-built client with no configured socket is disabled -> notify no-ops.
monkeypatch.setattr(launcher_ready, "launch_progress", LaunchProgressClient())
assert launcher_ready.notify_launcher_ready("bec-app") is False
def test_notify_launcher_ready_sends_ready(monkeypatch):
path = _short_socket_path()
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
srv.settimeout(2.0)
srv.bind(path)
srv.listen(1)
try:
monkeypatch.setenv("BEC_LAUNCH_PROGRESS_SOCKET", path)
monkeypatch.setenv("BEC_LAUNCH_PROGRESS_TOKEN", "tok-xyz")
monkeypatch.setattr(launcher_ready, "launch_progress", LaunchProgressClient())
assert launcher_ready.notify_launcher_ready("bec-app") is True
conn, _ = srv.accept()
conn.settimeout(2.0)
data = conn.recv(65536).decode()
conn.close()
assert '"t":"hello"' in data
assert '"token":"tok-xyz"' in data
assert '"t":"ready"' in data
finally:
srv.close()
try:
os.unlink(path)
except OSError:
pass
+16
View File
@@ -77,6 +77,22 @@ def test_viewbase_initializes(viewbase):
assert viewbase.on_exit() is True
def test_main_app_notifies_launcher_ready_after_show(qtbot, mocked_client, monkeypatch):
calls = []
monkeypatch.setattr(
"bec_widgets.applications.main_app.notify_launcher_ready",
lambda app_name, window: calls.append((app_name, window)) or True,
)
app = BECMainApp(client=mocked_client, anim_duration=ANIM_TEST_DURATION, show_examples=False)
qtbot.addWidget(app)
app.show()
qtbot.waitExposed(app)
qtbot.wait(10)
assert calls == [("bec-app", app)]
def test_on_enter_and_on_exit_are_called_on_switch(app_with_spies, qtbot):
app, v1, v2, _ = app_with_spies