test_tier4_chrome_web_e2e.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. #!/usr/bin/env python3
  2. """
  3. test_tier4_chrome_web_e2e.py — Tier 4 Real Headless Chrome 156 CDP Web Frontend E2E
  4. Drives real Chromium 156 (`/root/.cache/puppeteer/chrome/linux-156.0.8078.47/chrome-linux64/chrome`)
  5. over Chrome DevTools Protocol (CDP WebSocket) against live `stl_native_server` + HIL cluster:
  6. 1. Real password login (`#login-form`, `xjkj123456!`) & workbench initialization (0 JS exceptions)
  7. 2. Tab 5 Watchdog settings UI (`#wd-link-lost-s`, `#wd-dense-silence-s`, `#btn-save-watchdog`)
  8. persisting via `ConfigureWatchdog` RPC to `stl_native_server`
  9. 3. Live Overview DOM alerting during >5s dual-disconnect (`#watchdog-alert-banner`
  10. `dataset.alertKind == "link_offline_waiting"`) -> recovery (`dataset.alertKind == "serial_gap_detected"`)
  11. 4. Live RMT hard-hang DOM alerting (`dataset.alertKind == "stage_hang_timeout"`,
  12. scene-preserved & `0x08 00` cooling badges, AND G27 fix keeping `#dimm-replacement-banner` visible)
  13. """
  14. import asyncio
  15. import contextlib
  16. import json
  17. import os
  18. from pathlib import Path
  19. import shutil
  20. import subprocess
  21. import sys
  22. import tempfile
  23. import time
  24. from typing import Any, Callable, Dict, List, Optional
  25. import aiohttp
  26. ROOT_DIR = Path(__file__).resolve().parents[2]
  27. sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster"))
  28. from cluster_harness import HilClusterStack # noqa: E402
  29. CHROME_CANDIDATES = [
  30. "/root/.cache/puppeteer/chrome/linux-156.0.8078.47/chrome-linux64/chrome",
  31. shutil.which("google-chrome") or "",
  32. shutil.which("chromium") or "",
  33. shutil.which("chromium-browser") or "",
  34. ]
  35. def find_chrome_binary() -> str:
  36. for c in CHROME_CANDIDATES:
  37. if c and os.path.isfile(c) and os.access(c, os.X_OK):
  38. return c
  39. raise FileNotFoundError("Headless Chrome binary not found")
  40. async def wait_until(
  41. pred: Callable[[], Any],
  42. timeout_s: float = 25.0,
  43. interval_s: float = 0.25,
  44. desc: str = "condition",
  45. ) -> Any:
  46. deadline = time.monotonic() + timeout_s
  47. last_val = None
  48. while time.monotonic() < deadline:
  49. res = pred()
  50. if asyncio.iscoroutine(res):
  51. res = await res
  52. last_val = res
  53. if res:
  54. return res
  55. await asyncio.sleep(interval_s)
  56. raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}")
  57. class CdpPageClient:
  58. """Lightweight async Chrome DevTools Protocol (CDP) page controller over `aiohttp`."""
  59. def __init__(self, http: aiohttp.ClientSession, debug_port: int):
  60. self.http = http
  61. self.debug_port = debug_port
  62. self.ws: Optional[aiohttp.ClientWebSocketResponse] = None
  63. self.reader_task: Optional[asyncio.Task] = None
  64. self.seq = 0
  65. self.pending: Dict[int, asyncio.Future] = {}
  66. self.js_exceptions: List[str] = []
  67. async def connect_first_page(self, target_url: str, timeout_s: float = 12.0) -> None:
  68. deadline = time.monotonic() + timeout_s
  69. ws_url = ""
  70. while time.monotonic() < deadline:
  71. try:
  72. async with self.http.put(
  73. f"http://127.0.0.1:{self.debug_port}/json/new?{target_url}",
  74. timeout=aiohttp.ClientTimeout(total=2.0),
  75. ) as r:
  76. if r.status == 200:
  77. info = await r.json()
  78. ws_url = info.get("webSocketDebuggerUrl", "")
  79. if ws_url:
  80. break
  81. except Exception:
  82. pass
  83. await asyncio.sleep(0.2)
  84. if not ws_url:
  85. raise TimeoutError("Failed to open CDP page target")
  86. self.ws = await self.http.ws_connect(ws_url, max_msg_size=16 * 1024 * 1024)
  87. self.reader_task = asyncio.create_task(self._read_loop())
  88. await self.send("Page.enable")
  89. await self.send("Runtime.enable")
  90. async def _read_loop(self) -> None:
  91. assert self.ws is not None
  92. try:
  93. async for msg in self.ws:
  94. if msg.type != aiohttp.WSMsgType.TEXT:
  95. continue
  96. data = json.loads(msg.data)
  97. if "id" in data and data["id"] in self.pending:
  98. fut = self.pending.pop(data["id"])
  99. if not fut.done():
  100. fut.set_result(data)
  101. elif data.get("method") == "Runtime.exceptionThrown":
  102. details = (data.get("params") or {}).get("exceptionDetails") or {}
  103. self.js_exceptions.append(json.dumps(details, ensure_ascii=False))
  104. except Exception as exc:
  105. for fut in self.pending.values():
  106. if not fut.done():
  107. fut.set_exception(exc)
  108. async def send(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 10.0) -> Dict[str, Any]:
  109. assert self.ws is not None
  110. self.seq += 1
  111. cid = self.seq
  112. fut = asyncio.get_running_loop().create_future()
  113. self.pending[cid] = fut
  114. await self.ws.send_json({"id": cid, "method": method, "params": params or {}})
  115. try:
  116. resp = await asyncio.wait_for(fut, timeout=timeout)
  117. finally:
  118. self.pending.pop(cid, None)
  119. if "error" in resp:
  120. raise RuntimeError(f"CDP {method} error: {resp['error']}")
  121. return resp.get("result") or {}
  122. async def eval_js(self, expression: str) -> Any:
  123. res = await self.send(
  124. "Runtime.evaluate",
  125. {"expression": expression, "returnByValue": True, "awaitPromise": True},
  126. )
  127. if "exceptionDetails" in res:
  128. raise RuntimeError(f"JS eval exception: {res['exceptionDetails']}")
  129. return (res.get("result") or {}).get("value")
  130. async def close(self) -> None:
  131. if self.ws is not None:
  132. with contextlib.suppress(Exception):
  133. await self.ws.close()
  134. if self.reader_task is not None:
  135. self.reader_task.cancel()
  136. with contextlib.suppress(asyncio.CancelledError, Exception):
  137. await self.reader_task
  138. async def run_tier4_web_suite() -> Dict[str, Any]:
  139. t0 = time.monotonic()
  140. chrome_bin = find_chrome_binary()
  141. cdp_port = 19322
  142. user_data_dir = Path(tempfile.mkdtemp(prefix="xjkj_stl_chrome_"))
  143. chrome_proc: Optional[subprocess.Popen] = None
  144. results = []
  145. try:
  146. async with HilClusterStack(
  147. web_port=18984,
  148. tftp_port=19074,
  149. bmc_ctrl_port=19299,
  150. hil_http_port=19298,
  151. uart_base=19240,
  152. web_password="xjkj123456!",
  153. speed_scale=0.18,
  154. station_ips=["127.0.3.166", "127.0.3.165", "127.0.3.167", "127.0.3.168"],
  155. ) as stack:
  156. assert stack.admin_ws is not None
  157. assert stack.http_session is not None
  158. await stack.wait_station_online("S1", timeout_s=15.0)
  159. env = dict(os.environ)
  160. for k in (
  161. "LD_LIBRARY_PATH",
  162. "http_proxy",
  163. "https_proxy",
  164. "HTTP_PROXY",
  165. "HTTPS_PROXY",
  166. "all_proxy",
  167. "ALL_PROXY",
  168. ):
  169. env.pop(k, None)
  170. chrome_proc = subprocess.Popen(
  171. [
  172. chrome_bin,
  173. "--headless=new",
  174. "--no-sandbox",
  175. "--no-proxy-server",
  176. "--disable-gpu",
  177. "--disable-dev-shm-usage",
  178. "--no-first-run",
  179. "--window-size=1600,1080",
  180. f"--user-data-dir={user_data_dir}",
  181. f"--remote-debugging-port={cdp_port}",
  182. "about:blank",
  183. ],
  184. stdout=subprocess.DEVNULL,
  185. stderr=subprocess.PIPE,
  186. env=env,
  187. )
  188. cdp = CdpPageClient(stack.http_session, cdp_port)
  189. await cdp.connect_first_page(f"http://127.0.0.1:{stack.web_port}/")
  190. try:
  191. # ============================================================
  192. # Scenario 1: Real Web Login Flow (`#login-form` -> Workbench)
  193. # ============================================================
  194. print("[Tier4][1/4] Verifying Chrome 156 password login gate & live workbench initialization...", flush=True)
  195. await wait_until(
  196. lambda: cdp.eval_js("!!document.getElementById('admin-password')"),
  197. timeout_s=10.0,
  198. desc="Login page #admin-password",
  199. )
  200. await cdp.eval_js(
  201. """(() => {
  202. const inp = document.getElementById('admin-password');
  203. inp.value = 'xjkj123456!';
  204. document.getElementById('login-form').requestSubmit();
  205. return true;
  206. })()"""
  207. )
  208. await wait_until(
  209. lambda: cdp.eval_js("!!document.getElementById('watchdog-alert-banner') && document.querySelectorAll('#cpu0-grid .dimm-slot').length === 12"),
  210. timeout_s=15.0,
  211. desc="Main workbench loaded with 24 DIMM slots",
  212. )
  213. assert not cdp.js_exceptions, f"Unexpected JS exceptions after login: {cdp.js_exceptions}"
  214. results.append({"scenario": "1_chrome_login_and_workbench_boot", "status": "PASS"})
  215. print(" -> PASS", flush=True)
  216. # ============================================================
  217. # Scenario 2: Tab 5 Watchdog Settings Panel -> `ConfigureWatchdog`
  218. # ============================================================
  219. print("[Tier4][2/4] Verifying Tab 5 Watchdog settings UI & persistence in Chrome...", flush=True)
  220. await cdp.eval_js(
  221. """(() => {
  222. const tabBtn = document.querySelector('[data-page="plans"], [data-nav-page="plans"]');
  223. if (tabBtn) tabBtn.click();
  224. return !!tabBtn;
  225. })()"""
  226. )
  227. await wait_until(
  228. lambda: cdp.eval_js("!!document.getElementById('btn-save-watchdog')"),
  229. timeout_s=8.0,
  230. desc="#btn-save-watchdog present",
  231. )
  232. await cdp.eval_js(
  233. """(() => {
  234. document.getElementById('wd-link-lost-s').value = '180';
  235. document.getElementById('wd-dense-silence-s').value = '95';
  236. document.getElementById('wd-hang-action').value = 'retry_current_task';
  237. document.getElementById('wd-max-hangs').value = '3';
  238. document.getElementById('btn-save-watchdog').click();
  239. return true;
  240. })()"""
  241. )
  242. async def _wd_persisted():
  243. ctrl = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
  244. wd = ctrl.get("watchdog") or {}
  245. return wd if wd.get("link_lost_timeout_ms") == 180000 and wd.get("dense_stage_silence_timeout_ms") == 95000 and wd.get("hang_action") == "retry_current_task" and wd.get("max_consecutive_hangs") == 3 else None
  246. await wait_until(_wd_persisted, timeout_s=8.0, desc="Watchdog config persisted via Web UI")
  247. # Switch back to Overview tab (`overview`)
  248. await cdp.eval_js(
  249. """(() => {
  250. const ovBtn = document.querySelector('[data-page="overview"], [data-nav-page="overview"]');
  251. if (ovBtn) ovBtn.click();
  252. return true;
  253. })()"""
  254. )
  255. results.append({"scenario": "2_tab5_watchdog_config_save", "status": "PASS"})
  256. print(" -> PASS", flush=True)
  257. # ============================================================
  258. # Scenario 3: Live `link_offline_waiting` -> `serial_gap_detected` Banner in Chrome
  259. # ============================================================
  260. print("[Tier4][3/4] Verifying live `link_offline_waiting` & `serial_gap_detected` banners in Chrome DOM...", flush=True)
  261. await stack.enqueue_cmd(
  262. "S1",
  263. "ConfigureWatchdog",
  264. {"watchdog": {"link_lost_timeout_ms": 45000, "dense_stage_silence_timeout_ms": 40000, "reboot_on_hang": False}},
  265. )
  266. await stack.trigger_dut_boot(0, reason="tier4_dual_drop")
  267. await asyncio.sleep(0.3)
  268. await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "start"})
  269. await stack.set_link(0, bmc_up=False, serial_up=False)
  270. async def _dom_link_waiting():
  271. return await cdp.eval_js(
  272. """(() => {
  273. const b = document.getElementById('watchdog-alert-banner');
  274. if (!b || b.classList.contains('hidden')) return null;
  275. return b.dataset.alertKind === 'link_offline_waiting' ? b.textContent : null;
  276. })()"""
  277. )
  278. banner_wait_txt = await wait_until(_dom_link_waiting, timeout_s=35.0, desc="Chrome #watchdog-alert-banner link_offline_waiting")
  279. assert "同时断联保护中" in banner_wait_txt, f"Unexpected banner text: {banner_wait_txt}"
  280. # Restore S1 links -> verify banner switches live to `serial_gap_detected`!
  281. await stack.set_link(0, bmc_up=True, serial_up=True)
  282. async def _dom_serial_gap():
  283. return await cdp.eval_js(
  284. """(() => {
  285. const b = document.getElementById('watchdog-alert-banner');
  286. if (!b || b.classList.contains('hidden')) return null;
  287. return b.dataset.alertKind === 'serial_gap_detected' ? b.textContent : null;
  288. })()"""
  289. )
  290. banner_gap_txt = await wait_until(_dom_serial_gap, timeout_s=15.0, desc="Chrome #watchdog-alert-banner serial_gap_detected")
  291. assert "serial_gap_detected" in banner_gap_txt, f"Unexpected gap banner text: {banner_gap_txt}"
  292. results.append({"scenario": "3_chrome_live_dual_drop_and_serial_gap_banners", "status": "PASS"})
  293. print(" -> PASS", flush=True)
  294. # ============================================================
  295. # Scenario 4: Live RMT Hard-Hang `stage_hang_timeout` Banner + G27 Fix
  296. # ============================================================
  297. print("[Tier4][4/4] Verifying live `stage_hang_timeout` red alert banner + G27 `#dimm-replacement-banner` visibility in Chrome...", flush=True)
  298. await stack.connect_and_heat_backend_hood("S1", 0, target_c=70)
  299. await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.15)
  300. await stack.enqueue_cmd(
  301. "S1",
  302. "SaveBootPlan",
  303. {
  304. "plan": {
  305. "preset": "auto",
  306. "mt_enabled": False,
  307. "run_rmt": True,
  308. "stages": {"uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto"},
  309. },
  310. "watchdog": {"dense_stage_silence_timeout_ms": 2200, "reboot_on_hang": False},
  311. },
  312. )
  313. await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "restart"})
  314. async def _dom_hang_alert():
  315. return await cdp.eval_js(
  316. """(() => {
  317. const wb = document.getElementById('watchdog-alert-banner');
  318. const db = document.getElementById('dimm-replacement-banner');
  319. if (!wb || wb.classList.contains('hidden')) return null;
  320. if (wb.dataset.alertKind !== 'stage_hang_timeout') return null;
  321. return {
  322. wdText: wb.textContent,
  323. dimmBannerVisible: !!(db && !db.classList.contains('hidden')),
  324. dimmBannerText: db ? db.textContent : ''
  325. };
  326. })()"""
  327. )
  328. hang_dom = await wait_until(_dom_hang_alert, timeout_s=25.0, desc="Chrome #watchdog-alert-banner stage_hang_timeout")
  329. assert "stage_hang_timeout" in hang_dom["wdText"]
  330. assert "保留死机现场" in hang_dom["wdText"]
  331. assert "0x08 00" in hang_dom["wdText"]
  332. assert hang_dom["dimmBannerVisible"] is True, f"G27 regression: #dimm-replacement-banner hidden on hang fault! {hang_dom}"
  333. assert not cdp.js_exceptions, f"Uncaught JS exceptions during Web E2E: {cdp.js_exceptions}"
  334. results.append({"scenario": "4_chrome_stage_hang_alert_and_g27_banner_fix", "status": "PASS"})
  335. print(" -> PASS", flush=True)
  336. # ============================================================
  337. # Scenario 5: Phase 1 Production/Engineering Switch, Single-DIMM Curve & Excel Export
  338. # ============================================================
  339. print("[Tier4][5/5] Verifying Production/Engineering view switch, single-DIMM curve modal & alarms.xlsx...", flush=True)
  340. await cdp.eval_js(
  341. """(() => {
  342. document.getElementById('btn-mode-production').click();
  343. return document.body.dataset.uiMode;
  344. })()"""
  345. )
  346. prod_cards = await wait_until(
  347. lambda: cdp.eval_js("document.querySelectorAll('#prod-stations-grid .prod-station-card').length >= 4 && document.querySelectorAll('#prod-stations-grid .prod-dimm-cell').length >= 96"),
  348. timeout_s=8.0,
  349. desc="Production dashboard 4+ cards and 96+ DIMM cells",
  350. )
  351. assert prod_cards is True
  352. # Click first DIMM cell to open single-DIMM temperature curve modal
  353. await cdp.eval_js(
  354. """(() => {
  355. document.querySelector('#prod-stations-grid .prod-dimm-cell').click();
  356. return true;
  357. })()"""
  358. )
  359. curve_open = await wait_until(
  360. lambda: cdp.eval_js("!document.getElementById('stl-dimm-curve-modal').classList.contains('hidden') && !!document.getElementById('dimm-curve-canvas')"),
  361. timeout_s=6.0,
  362. desc="Single-DIMM temperature curve modal open",
  363. )
  364. assert curve_open is True
  365. await cdp.eval_js("document.getElementById('dimm-curve-close').click(); document.getElementById('btn-mode-engineering').click(); true")
  366. # Verify alarms.xlsx download via browser authenticated fetch (valid PK ZIP signature)
  367. xlsx_ok = await cdp.eval_js(
  368. """(async () => {
  369. const r = await fetch('/api/stations/S1/alarms.xlsx', { credentials: 'same-origin' });
  370. if (!r.ok) return { ok: false, status: r.status };
  371. const buf = new Uint8Array(await r.arrayBuffer());
  372. return { ok: buf.length > 500 && buf[0] === 0x50 && buf[1] === 0x4b, size: buf.length };
  373. })()"""
  374. )
  375. assert xlsx_ok and xlsx_ok.get("ok") is True, f"alarms.xlsx export failed: {xlsx_ok}"
  376. assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 5: {cdp.js_exceptions}"
  377. results.append({"scenario": "5_production_view_dimm_curve_and_xlsx", "status": "PASS", "xlsx_size": xlsx_ok.get("size")})
  378. print(f" -> PASS (alarms.xlsx={xlsx_ok.get('size')} bytes)", flush=True)
  379. # ============================================================
  380. # Scenario 6: Phase 2 Full-Detail Frontend + Backend Trace, Dynamic Toggle & .tar Bundle
  381. # ============================================================
  382. print("[Tier4][6/6] Verifying Phase 2 full-detail frontend+backend trace ingestion, toggle OFF & .tar bundle...", flush=True)
  383. await cdp.eval_js("window.stlTrace && window.stlTrace.flush(false)")
  384. trace_st = await wait_until(
  385. lambda: cdp.eval_js(
  386. """(async () => {
  387. const r = await fetch('/api/trace/status', { credentials: 'same-origin' });
  388. if (!r.ok) return null;
  389. const d = await r.json();
  390. return (d.frontend_events_ingested > 0 && d.written_events > 0) ? d : null;
  391. })()"""
  392. ),
  393. timeout_s=10.0,
  394. desc="Frontend trace events ingested on disk",
  395. )
  396. # Verify .tar diagnostic bundle download
  397. tar_ok = await cdp.eval_js(
  398. """(async () => {
  399. const r = await fetch('/api/trace/bundle?station_id=S1', { credentials: 'same-origin' });
  400. if (!r.ok) return { ok: false, status: r.status };
  401. const txt = await r.text();
  402. return { ok: txt.includes('trace/config.json') && txt.includes('frontend.0001.jsonl') && txt.includes('backend.0001.jsonl'), size: txt.length };
  403. })()"""
  404. )
  405. assert tar_ok and tar_ok.get("ok") is True, f"Diagnostic .tar bundle invalid: {tar_ok}"
  406. # Toggle trace OFF dynamically via UI/HTTP and verify WS broadcast syncs browser trace.js immediately
  407. await cdp.eval_js(
  408. """(async () => {
  409. await fetch('/api/trace/config', {
  410. method: 'POST',
  411. credentials: 'same-origin',
  412. headers: { 'Content-Type': 'application/json' },
  413. body: JSON.stringify({ enabled: false }),
  414. });
  415. return true;
  416. })()"""
  417. )
  418. toggled_off = await wait_until(
  419. lambda: cdp.eval_js("window.stlTrace && window.stlTrace.isActive() === false"),
  420. timeout_s=6.0,
  421. desc="Browser stlTrace dynamically disabled via WS broadcast",
  422. )
  423. assert toggled_off is True
  424. # Verify Phase 3 6-tier hardware info endpoint
  425. hw_ok = await cdp.eval_js(
  426. """(async () => {
  427. const r = await fetch('/api/hw/info', { credentials: 'same-origin' });
  428. if (!r.ok) return null;
  429. const d = await r.json();
  430. return (d.available === true && typeof d.tier_name === 'string' && d.opencl_igpu) ? d : null;
  431. })()"""
  432. )
  433. assert hw_ok and hw_ok.get("available") is True, f"/api/hw/info invalid: {hw_ok}"
  434. # Re-enable so default state remains intact
  435. await cdp.eval_js(
  436. """(async () => {
  437. await fetch('/api/trace/config', {
  438. method: 'POST',
  439. credentials: 'same-origin',
  440. headers: { 'Content-Type': 'application/json' },
  441. body: JSON.stringify({ enabled: true }),
  442. });
  443. return true;
  444. })()"""
  445. )
  446. assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 6: {cdp.js_exceptions}"
  447. results.append({"scenario": "6_full_detail_trace_frontend_backend_and_toggle", "status": "PASS", "fe_events": trace_st.get("frontend_events_ingested"), "tar_size": tar_ok.get("size")})
  448. print(f" -> PASS (fe_events={trace_st.get('frontend_events_ingested')}, tar={tar_ok.get('size')}B)", flush=True)
  449. # ============================================================
  450. # Scenario 7: Phase 4 Built-in PXE/ProxyDHCP UI, Full BMC Sensor Table & Console-Expand Tab Fix
  451. # ============================================================
  452. print("[Tier4][7/7] Verifying Phase 4 BMC Full Sensor Table, Console-Expand Tab Fix & Built-in PXE/ProxyDHCP UI...", flush=True)
  453. # 7a. Full BMC sensor table on Overview shows Voltage/Fan/Power from live RMCP+ SDR
  454. bmc_dom = await wait_until(
  455. lambda: cdp.eval_js(
  456. """(() => {
  457. const tb = document.getElementById('bmc-sensors-tbody');
  458. if (!tb) return null;
  459. const txt = tb.textContent || '';
  460. return (txt.includes('P12V') && txt.includes('FAN1_RPM') && txt.includes('PSU1_PIN_W')) ? txt.length : null;
  461. })()"""
  462. ),
  463. timeout_s=10.0,
  464. desc="BMC full sensor table (P12V, FAN1_RPM, PSU1_PIN_W) in Chrome",
  465. )
  466. assert bmc_dom and bmc_dom > 50
  467. # 7b. Console expand on Overview must NOT hide Testing page when switching tabs!
  468. await cdp.eval_js(
  469. """(() => {
  470. document.getElementById('btn-console-expand')?.click();
  471. document.querySelector('[data-page="testing"]')?.click();
  472. return true;
  473. })()"""
  474. )
  475. pxe_ui_ok = await wait_until(
  476. lambda: cdp.eval_js(
  477. """(() => {
  478. const left = document.querySelector('.workspace-left');
  479. const card = document.getElementById('pxe-dhcp-card');
  480. const modeSel = document.getElementById('pxe-dhcp-mode');
  481. const portTxt = document.getElementById('pxe-port-status')?.textContent || '';
  482. if (!left || !card || !modeSel) return null;
  483. const visible = getComputedStyle(left).display !== 'none';
  484. return (visible && portTxt.includes('HTTP Boot:')) ? { visible, mode: modeSel.value, portTxt } : null;
  485. })()"""
  486. ),
  487. timeout_s=8.0,
  488. desc="Built-in PXE/ProxyDHCP panel visible after console-expand tab switch",
  489. )
  490. assert pxe_ui_ok and pxe_ui_ok.get("visible") is True
  491. # 7c. Trigger 1-click LAN DHCP/PXE self-check in Chrome and verify result renders
  492. await cdp.eval_js("document.getElementById('btn-probe-pxe-network')?.click(); true")
  493. probe_txt = await wait_until(
  494. lambda: cdp.eval_js(
  495. """(() => {
  496. const b = document.getElementById('pxe-probe-result');
  497. if (!b || b.classList.contains('hidden')) return null;
  498. return b.textContent.includes('诊断结论:') ? b.textContent : null;
  499. })()"""
  500. ),
  501. timeout_s=10.0,
  502. desc="LAN DHCP/PXE self-check output in Chrome",
  503. )
  504. assert "诊断结论:" in probe_txt
  505. assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 7: {cdp.js_exceptions}"
  506. results.append({"scenario": "7_phase4_bmc_sensors_console_tab_fix_and_builtin_pxe_ui", "status": "PASS"})
  507. print(" -> PASS", flush=True)
  508. finally:
  509. await cdp.close()
  510. elapsed_s = round(time.monotonic() - t0, 2)
  511. summary = {"tier": "Tier4_Headless_Chrome156_Web_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
  512. print(f"\n[Tier4] ALL 7 HEADLESS CHROME 156 WEB E2E SCENARIOS PASSED in {elapsed_s}s!", flush=True)
  513. return summary
  514. finally:
  515. if chrome_proc and chrome_proc.poll() is None:
  516. with contextlib.suppress(Exception):
  517. chrome_proc.terminate()
  518. chrome_proc.wait(timeout=3.0)
  519. if chrome_proc.poll() is None:
  520. with contextlib.suppress(Exception):
  521. chrome_proc.kill()
  522. shutil.rmtree(user_data_dir, ignore_errors=True)
  523. if __name__ == "__main__":
  524. res = asyncio.run(run_tier4_web_suite())
  525. out_file = ROOT_DIR / "build" / "sim" / "tier4_chrome_web_report.json"
  526. out_file.parent.mkdir(parents=True, exist_ok=True)
  527. out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")