Files
Warehouse-Digital-Twin-and-…/tests/unit/test_dashboard_server.py
T

141 lines
5.4 KiB
Python

"""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")
# Create mock optimization in tmp_path
opt_dir = tmp_path / "optimization"
opt_dir.mkdir(parents=True)
(opt_dir / "optimization_summary.json").write_text(json.dumps({
"evaluation": {"overall_score": 85.0},
"layout_comparison": [{"variant": "baseline", "is_best": False}],
}), encoding="utf-8")
(opt_dir / "layout_comparison.svg").write_text("<svg><rect width='100' height='100'/></svg>", 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. Optimization endpoint
with urllib.request.urlopen(f"{base_url}/api/optimization", timeout=3.0) as resp:
assert resp.status == 200
opt_data = json.loads(resp.read().decode("utf-8"))
assert "evaluation" in opt_data
assert "layout_comparison" in opt_data
# 8. Optimization comparison SVG endpoint
with urllib.request.urlopen(f"{base_url}/api/optimization/comparison.svg", timeout=3.0) as resp:
assert resp.status == 200
assert "image/svg+xml" in resp.headers.get("Content-Type", "")
opt_svg = resp.read().decode("utf-8")
assert "<svg" in opt_svg
# 9. 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