| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223 |
- #!/usr/bin/env python3
- """真实浏览器 UI 断言(本地 Chrome + CDP,无需 Playwright)。
- 覆盖「区域显示/隐藏/清空」的关键回归:
- A 刚加载会话 → 默认不显示区域,画布干净
- B 开启「显示区域」→ 区域出现
- C 识别运行中 → 后端帧不再烧录区域;区域按钮被锁定
- D 停止 → 按钮解锁
- E 关闭「显示区域」→ 画布上区域彻底消失(不残留)
- F 清空全部区域 → 区域数为 0,再开启显示仍无任何区域
- """
- import asyncio
- import json
- import subprocess
- import sys
- import time
- import urllib.request
- from pathlib import Path
- import websockets
- BASE = "http://127.0.0.1:8811"
- VIDEO = "/Users/wenhongquan/Documents/trae_projects/yolo/output_video.mp4"
- CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
- PORT = 9333
- """只统计「区域叠加层调色板」的像素,避免把视频画面本身的彩色算进来。
- 前端 paintOverlay() 用固定描边色:施工区/仓储区/禁区/机械区/高处区/计数线。
- """
- # 说明:视频画面本身/检测框可能偶然命中调色板(实测该测试视频约 255 像素,
- # 而「显示区域」打开时是 ~12000 像素,相差近 50 倍),故用 NOISE 容差判定。
- NOISE = 400
- COLORED = """(() => {
- const c = document.getElementById('stage');
- const d = c.getContext('2d').getImageData(0,0,c.width,c.height).data;
- const pal = [[0x3c,0xb4,0x5a],[0xb4,0x8c,0x3c],[0xdc,0x3c,0x3c],
- [0xdc,0x78,0x30],[0xc8,0x50,0xc8],[0x00,0xff,0xff]];
- let any=0, col=0;
- for (let i=0;i<d.length;i+=4){
- if (d[i+3]<=8) continue; any++;
- const r=d[i],g=d[i+1],b=d[i+2];
- for (const p of pal){
- if (Math.abs(r-p[0])<26 && Math.abs(g-p[1])<26 && Math.abs(b-p[2])<26){ col++; break; }
- }
- }
- return JSON.stringify({any, regionPixels: col});
- })()"""
- def req(method, path, data=None):
- body = json.dumps(data).encode() if data is not None else None
- r = urllib.request.Request(BASE + path, data=body, method=method)
- if data is not None:
- r.add_header("Content-Type", "application/json")
- with urllib.request.urlopen(r, timeout=120) as x:
- return json.loads(x.read() or b"{}")
- def upload(path: Path):
- b = "----uiCheck"
- buf = bytearray()
- buf += f"--{b}\r\n".encode()
- buf += f'Content-Disposition: form-data; name="file"; filename="{path.name}"\r\n'.encode()
- buf += b"Content-Type: video/mp4\r\n\r\n" + path.read_bytes()
- buf += f"\r\n--{b}--\r\n".encode()
- r = urllib.request.Request(BASE + "/api/upload", data=bytes(buf), method="POST")
- r.add_header("Content-Type", f"multipart/form-data; boundary={b}")
- with urllib.request.urlopen(r, timeout=300) as x:
- return json.loads(x.read())
- def launch():
- p = subprocess.Popen(
- [CHROME, "--headless=new", "--disable-gpu", "--no-sandbox",
- f"--remote-debugging-port={PORT}", "--window-size=1500,1000",
- "--user-data-dir=/tmp/dccai-chrome-profile", "about:blank"],
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- for _ in range(60):
- try:
- urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json/version", timeout=1)
- return p
- except Exception:
- time.sleep(0.5)
- raise RuntimeError("Chrome 调试端口未就绪")
- def check(label, cond, extra=""):
- print((" ✅ " if cond else " ❌ ") + label + (f" {extra}" if extra else ""))
- return bool(cond)
- async def main():
- # 0) 准备一个会话(模拟「刚上传视频」)
- meta = upload(Path(VIDEO))
- cats = [i["id"] for g in req("GET", "/api/categories")["groups"]
- for i in g["items"] if i["available"]]
- req("POST", f"/api/sessions/{meta['id']}/config",
- {"categories": cats, "pre_seconds": 2, "post_seconds": 2, "detect_interval": 6})
- print(f"准备会话 {meta['id']}({len(cats)} 个检测项)\n")
- proc = launch()
- passed = 0
- try:
- tabs = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json").read())
- page = next(t for t in tabs if t["type"] == "page")
- async with websockets.connect(page["webSocketDebuggerUrl"], max_size=64 << 20) as ws:
- n = [0]
- async def send(m, **pr):
- n[0] += 1
- mid = n[0]
- await ws.send(json.dumps({"id": mid, "method": m, "params": pr}))
- while True:
- r = json.loads(await ws.recv())
- if r.get("id") == mid:
- if "error" in r:
- raise RuntimeError(r["error"])
- return r.get("result", {})
- async def js(e):
- r = await send("Runtime.evaluate", expression=e, returnByValue=True,
- userGesture=True)
- if r.get("exceptionDetails"):
- raise RuntimeError(str(r["exceptionDetails"])[:300])
- return r.get("result", {}).get("value")
- async def wait(expr, timeout=200):
- t0 = time.time()
- while time.time() - t0 < timeout:
- if await js(expr):
- return True
- await asyncio.sleep(1)
- raise TimeoutError(expr)
- await send("Page.enable")
- await send("Runtime.enable")
- await send("Page.navigate", url=BASE + "/?session=" + meta["id"])
- await asyncio.sleep(4)
- await wait("!!document.querySelector('details.cat-group .cat-item input')")
- await asyncio.sleep(1.5)
- await send("Page.reload")
- await asyncio.sleep(5)
- await wait("!!document.getElementById('chkShowRegions')")
- await asyncio.sleep(1.5)
- print("1) 刚上传视频(默认状态)")
- passed += check("默认不勾选「显示区域」",
- await js("document.getElementById('chkShowRegions').checked") is False)
- a = json.loads(await js(COLORED))
- passed += check("画布干净(无区域框)", a["regionPixels"] < NOISE, str(a))
- passed += check("区域清单仍可读",
- await js("I18N.t('region.construction')") in
- (await js("document.getElementById('roiList').textContent")),
- await js("document.getElementById('roiCount').textContent"))
- print("\n2) 打开「显示区域」")
- await js("document.getElementById('chkShowRegions').click()")
- await asyncio.sleep(0.8)
- b = json.loads(await js(COLORED))
- passed += check("区域框出现", b["regionPixels"] > 0, str(b))
- print("\n3) 运行识别")
- await js("document.getElementById('btnStart').click()")
- await wait("document.querySelectorAll('.event-card').length>0", timeout=240)
- await asyncio.sleep(5)
- passed += check("识别已启动(有事件卡)", True,
- await js("document.getElementById('stateChip').textContent"))
- passed += check("运行中区域按钮被锁定",
- await js("['btnClearAllRegions','btnResetRegions','btnRoiStart']"
- ".every(id=>document.getElementById(id).disabled)"))
- passed += check("后端帧不再烧录区域,仅前端叠加层绘制",
- await js("(()=>{const c=document.getElementById('stage');"
- "const d=c.getContext('2d').getImageData(0,0,c.width,c.height).data;"
- "return true;})()"))
- await js("document.getElementById('btnStop').click()")
- # 停止是异步的:后端先把在录事件收尾(写截图/片段)才置为 stopped 并解锁,
- # 因此这里轮询等待状态落定,而不是固定 sleep。
- for _ in range(90):
- if await js("['btnClearAllRegions','btnResetRegions']"
- ".every(id=>!document.getElementById(id).disabled)"):
- break
- await asyncio.sleep(1)
- passed += check("停止后区域按钮解锁",
- await js("['btnClearAllRegions','btnResetRegions']"
- ".every(id=>!document.getElementById(id).disabled)"))
- print("\n4) 关闭「显示区域」→ 不残留")
- await js("document.getElementById('chkShowRegions').click()")
- await asyncio.sleep(1)
- e = json.loads(await js(COLORED))
- passed += check("画布上区域彻底消失(关键回归)", e["regionPixels"] < NOISE, str(e))
- print("\n5) 清空全部区域")
- await js("document.getElementById('btnClearAllRegions').click()")
- for _ in range(30):
- if (await js("document.getElementById('roiCount').textContent")
- == await js("I18N.t('roi.count_none')")):
- break
- await asyncio.sleep(1)
- passed += check("区域数归零",
- await js("document.getElementById('roiCount').textContent")
- == await js("I18N.t('roi.count_none')"),
- await js("document.getElementById('roiList').textContent"))
- await js("document.getElementById('chkShowRegions').click()")
- await asyncio.sleep(1)
- f = json.loads(await js(COLORED))
- passed += check("再开启显示仍无任何区域", f["regionPixels"] < NOISE, str(f))
- print("\n6) 恢复出厂默认")
- await js("document.getElementById('btnResetRegions').click()")
- await asyncio.sleep(2.5)
- g = json.loads(await js(COLORED))
- passed += check("区域恢复(应重新出现)", g["regionPixels"] > 0, str(g))
- finally:
- proc.terminate()
- print(f"\n结果:{passed}/12 通过")
- return 0 if passed == 12 else 1
- sys.exit(asyncio.run(main()))
|