feat(phase-8): implement operational web dashboard, rest api, and telemetry data provider

This commit is contained in:
2026-10-21 13:14:00 +05:30
parent 630855252b
commit be37f15432
15 changed files with 2770 additions and 15 deletions
+121
View File
@@ -0,0 +1,121 @@
"""Unit tests for dashboard data provider and telemetry parser."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from warehouse_twin.dashboard.data_provider import DashboardDataProvider
def test_list_experiments(tmp_path: Path):
"""Verify scanning and listing of experiment runs."""
exp_dir = tmp_path / "experiments"
exp_dir.mkdir(parents=True)
# Empty experiment dir
dp = DashboardDataProvider(tmp_path)
assert dp.list_experiments() == []
# Valid experiment 1
e1 = exp_dir / "exp_alpha"
e1.mkdir()
(e1 / "config.json").write_text(json.dumps({
"name": "Alpha Run", "duration": 1800.0, "seed": 10, "fleet_size": 2, "dispatch_policy": "nearest_idle"
}), encoding="utf-8")
(e1 / "kpi_summary.json").write_text(json.dumps({
"throughput": {"completed_per_hour": 45.0}
}), encoding="utf-8")
# Valid experiment 2
e2 = exp_dir / "baseline_1hr"
e2.mkdir()
(e2 / "config.json").write_text(json.dumps({
"name": "Baseline 1-Hour", "duration": 3600.0, "seed": 42, "fleet_size": 4
}), encoding="utf-8")
(e2 / "kpi_summary.json").write_text(json.dumps({
"throughput": {"completed_per_hour": 85.0}
}), encoding="utf-8")
exps = dp.list_experiments()
assert len(exps) == 2
# baseline_1hr is sorted first
assert exps[0]["id"] == "baseline_1hr"
assert exps[0]["throughput"] == 85.0
assert exps[1]["id"] == "exp_alpha"
assert exps[1]["throughput"] == 45.0
def test_get_experiment_detail_and_csv_parsing(tmp_path: Path):
"""Verify detailed telemetry parsing including robots and tasks CSVs."""
exp_dir = tmp_path / "experiments" / "test_run"
exp_dir.mkdir(parents=True)
(exp_dir / "config.json").write_text(json.dumps({"name": "Test Run"}), encoding="utf-8")
(exp_dir / "kpi_summary.json").write_text(json.dumps({"fleet_size": 2, "turnaround_time": {"p50": 75.0}}), encoding="utf-8")
# Mock robots.csv
robots_csv_content = (
"robot_id,robot_type,current_state,battery_percent,utilization_pct,total_distance_m,loaded_distance_m,empty_distance_m,energy_consumed_kwh,charging_sessions\n"
"amr_1,light_amr,IDLE,98.5,45.0,300.0,180.0,120.0,0.12,1\n"
"amr_2,heavy_amr,LOADED_TRANSIT,95.0,60.0,400.0,250.0,150.0,0.25,2\n"
)
(exp_dir / "robots.csv").write_text(robots_csv_content, encoding="utf-8")
# Mock tasks.csv
tasks_csv_content = (
"task_id,task_type,status,is_overdue\n"
"t1,ORDER_PICK,COMPLETED,False\n"
"t2,ORDER_PICK,COMPLETED,True\n"
"t3,PRODUCTION_LINE_FEED,IN_PROGRESS,False\n"
"t4,REPLENISHMENT,PENDING,False\n"
)
(exp_dir / "tasks.csv").write_text(tasks_csv_content, encoding="utf-8")
# Mock aisle_congestion.csv
aisle_csv_content = (
"u,v,traversals,conflicts,wait_time_sec,congestion_score,recommendation\n"
"N1,N2,50,5,12.5,0.75,Designate one-way corridor\n"
"N3,N4,20,1,2.0,0.25,Normal flow\n"
)
(exp_dir / "aisle_congestion.csv").write_text(aisle_csv_content, encoding="utf-8")
dp = DashboardDataProvider(tmp_path)
detail = dp.get_experiment_detail("test_run")
assert detail is not None
assert detail["id"] == "test_run"
assert len(detail["robots"]) == 2
assert detail["robots"][0]["robot_id"] == "amr_1"
assert detail["robots"][0]["battery_percent"] == 98.5
sum_tasks = detail["tasks_summary"]
assert sum_tasks["total"] == 4
assert sum_tasks["completed"] == 2
assert sum_tasks["on_time"] == 1
assert sum_tasks["late"] == 1
assert sum_tasks["in_progress"] == 1
assert sum_tasks["pending"] == 1
assert len(detail["bottlenecks"]) == 2
assert detail["bottlenecks"][0]["edge"] == "N1 -> N2"
assert detail["bottlenecks"][0]["severity"] == "CRITICAL"
assert detail["bottlenecks"][1]["severity"] == "INFO"
def test_markdown_table_parsing():
"""Verify parsing of Markdown comparison tables."""
table_md = """
# Scenario Comparison
| Metric | 2 AMRs | 4 AMRs | 6 AMRs |
| :--- | :---: | :---: | :---: |
| **Throughput (tasks/hr)** | 77.00 | 85.00 | 85.00 |
| **Fleet Utilization** | 95.6% | 50.9% | 32.7% |
"""
rows = DashboardDataProvider._parse_markdown_table(table_md)
assert len(rows) == 2
assert rows[0]["Metric"] == "Throughput (tasks/hr)"
assert rows[0]["2 AMRs"] == "77.00"
assert rows[0]["4 AMRs"] == "85.00"
assert rows[1]["Metric"] == "Fleet Utilization"
assert rows[1]["4 AMRs"] == "50.9%"
+117
View File
@@ -0,0 +1,117 @@
"""Unit tests for dashboard HTTP server and REST endpoints."""
from __future__ import annotations
import json
import socket
import threading
import time
import urllib.request
from pathlib import Path
import pytest
from warehouse_twin.dashboard.server import DashboardServer
def find_free_port() -> int:
"""Find a random available port on localhost."""
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 running_server(tmp_path: Path):
"""Fixture that initializes, starts, and tears down a DashboardServer."""
# Create mock experiment in tmp_path
exp_dir = tmp_path / "experiments" / "test_exp"
exp_dir.mkdir(parents=True)
(exp_dir / "config.json").write_text(json.dumps({"name": "Test Server Exp"}), encoding="utf-8")
(exp_dir / "kpi_summary.json").write_text(json.dumps({
"throughput": {"completed_per_hour": 85.0},
"turnaround_time": {"p50": 74.0}
}), encoding="utf-8")
(exp_dir / "congestion_heatmap.svg").write_text("<svg><circle r='10'/></svg>", encoding="utf-8")
(exp_dir / "report.md").write_text("# Test Report\nContent", encoding="utf-8")
port = find_free_port()
server = DashboardServer(results_dir=tmp_path, host="127.0.0.1", port=port)
# Start server in daemon thread
server_thread = threading.Thread(target=lambda: server.start(blocking=True), daemon=True)
server_thread.start()
time.sleep(0.2) # Allow server to bind
base_url = f"http://127.0.0.1:{port}"
yield base_url, server
# Teardown
server.stop()
server_thread.join(timeout=1.0)
def test_server_health_and_api_endpoints(running_server):
"""Verify health, experiments list, details, and heatmap endpoints."""
base_url, server = running_server
# 1. Health endpoint
with urllib.request.urlopen(f"{base_url}/api/health", timeout=3.0) as resp:
assert resp.status == 200
data = json.loads(resp.read().decode("utf-8"))
assert data["status"] == "ok"
assert data["version"] == "0.8.0"
# 2. Experiments list endpoint
with urllib.request.urlopen(f"{base_url}/api/experiments", timeout=3.0) as resp:
assert resp.status == 200
exps = json.loads(resp.read().decode("utf-8"))
assert len(exps) == 1
assert exps[0]["id"] == "test_exp"
# 3. Experiment detail endpoint
with urllib.request.urlopen(f"{base_url}/api/experiments/test_exp", timeout=3.0) as resp:
assert resp.status == 200
detail = json.loads(resp.read().decode("utf-8"))
assert detail["id"] == "test_exp"
assert detail["config"]["name"] == "Test Server Exp"
assert detail["has_heatmap"] is True
# 4. SVG Heatmap endpoint
with urllib.request.urlopen(f"{base_url}/api/experiments/test_exp/heatmap.svg", timeout=3.0) as resp:
assert resp.status == 200
assert "image/svg+xml" in resp.headers.get("Content-Type", "")
svg_body = resp.read().decode("utf-8")
assert "<svg>" in svg_body
# 5. Report Markdown endpoint
with urllib.request.urlopen(f"{base_url}/api/experiments/test_exp/report", timeout=3.0) as resp:
assert resp.status == 200
assert "text/markdown" in resp.headers.get("Content-Type", "")
report_text = resp.read().decode("utf-8")
assert "# Test Report" in report_text
# 6. Scenarios endpoint
with urllib.request.urlopen(f"{base_url}/api/scenarios", timeout=3.0) as resp:
assert resp.status == 200
comps = json.loads(resp.read().decode("utf-8"))
assert "fleet_sizing" in comps
assert "dispatch_policies" in comps
# 7. Static HTML page
with urllib.request.urlopen(f"{base_url}/", timeout=3.0) as resp:
assert resp.status == 200
html = resp.read().decode("utf-8")
assert "Warehouse Digital Twin" in html
assert "app.js" in html
def test_server_404_error_handling(running_server):
"""Verify 404 response for nonexistent experiment."""
base_url, _ = running_server
try:
urllib.request.urlopen(f"{base_url}/api/experiments/non_existent_exp", timeout=3.0)
pytest.fail("Expected HTTPError 404")
except urllib.error.HTTPError as err:
assert err.code == 404
err_body = json.loads(err.read().decode("utf-8"))
assert err_body["error"] is True
+27
View File
@@ -0,0 +1,27 @@
"""Unit tests verifying that dashboard dependencies remain strictly optional."""
from __future__ import annotations
import pytest
from warehouse_twin.dashboard.data_provider import DashboardDataProvider
from warehouse_twin.dashboard.streamlit_app import HAS_STREAMLIT, run_streamlit_app
def test_dashboard_operates_without_streamlit():
"""Verify that DashboardDataProvider and server function independently of Streamlit."""
dp = DashboardDataProvider()
assert dp is not None
# Data provider does not import streamlit
assert hasattr(dp, "list_experiments")
def test_streamlit_app_handles_missing_dependency():
"""Verify that streamlit_app module handles missing streamlit cleanly."""
if not HAS_STREAMLIT:
# Calling run_streamlit_app without streamlit should exit cleanly or print error
with pytest.raises(SystemExit) as exc:
run_streamlit_app()
assert exc.value.code == 1
else:
assert HAS_STREAMLIT is True