Files
fpv-rid-workbench/scripts/test-realtime-layout.mjs
JiuContinent 281af4fe3d ```
refactor(registry): 生产环境数据库访问迁移至 SQLx 并统一测试端口策略

将 rusqlite 从生产依赖移至 dev-dependencies,正式数据库操作全部
由 SQLx 完成;rusqlite 仅保留用于测试夹具及旧数据库兼容验证。

UI 验收脚本移除 HTTP 代理和动态端口分配,统一通过
ui-test-port.mjs 的 assertUiPortAvailable 直连 8787 端口,
确保测试与正式实例串行执行。

新增 doc/registry/rust/axum-sqlx-architecture.md 记录模块职责、
数据兼容、退出资源回收及验证维护规范。

修复接收器页面按钮缺少显式 height 导致的布局偏差。
```
2026-10-27 20:04:34 +08:00

89 lines
15 KiB
JavaScript

import {UI_URL, assertUiPortAvailable} from './ui-test-port.mjs';
const base=UI_URL;
await assertUiPortAvailable();
// Real Rust/Wasm acceptance in an isolated database. Never opens receiver transports.
import {mkdtemp,writeFile,readFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
import {createRequire} from 'node:module';
import assert from 'node:assert/strict';
const {chromium}=createRequire(import.meta.url)('playwright');
const root=await mkdtemp(path.join(tmpdir(),'RID-realtime-layout-'));
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
let output='',child,browser;const errors=[],csp=[];
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,PATH:'C:\\Windows\\System32',},windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>output+=e.message);}
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/appearance')).ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('server timeout '+output);}
async function stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
const key='rid.realtime.layout.v1';
let report={};let heartbeat;let sequence=1;
const wait=ms=>new Promise(r=>setTimeout(r,ms));
try {
start();await ready();
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'});
const context=await browser.newContext({viewport:{width:1600,height:1000}});const page=await context.newPage();
page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text())});
const requests={config:0,status:0,writes:0};page.on('request',r=>{if(r.url().endsWith('/api/receiver/config')){if(r.method()==='GET')requests.config++;else requests.writes++;}if(r.url().endsWith('/api/receiver/status'))requests.status++;});
for(const asset of ['workspace-native.css','map-adapter.js','index.html']){const response=await fetch(base+'/'+(asset==='index.html'?'realtime':asset));assert.equal(response.status,200);assert.ok(await response.text()===await readFile(path.resolve('dist/web-ui',asset),'utf8'),'Executable contains stale '+asset);}
await page.goto(base+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();
console.log('Checking actual Rust/Wasm layout and telemetry');
assert.equal(await page.locator('#rt-dock').isVisible(),false);await page.locator('#rt-dock-restore').click();
await page.locator('.live-empty').waitFor();assert.equal(await page.locator('.mc-btn-row a').getAttribute('aria-disabled'),'true');
await page.getByRole('button',{name:'聚焦此目标',exact:true}).isDisabled().then(v=>assert.ok(v));
const registered=await fetch(base+'/api/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({serialNo:'LAYOUT-0000',modelName:'验收模拟机型',ownerName:'隔离验收数据'})});assert.equal(registered.status,200);
const batch=Array.from({length:120},(_,i)=>({target_id:`LAYOUT-${String(i).padStart(4,'0')}`,receiver_id:'TEST',source_epoch:1,sequence:1,longitude:120+i*.0001,latitude:30+i*.0001,altitude_m:100+i,heading_deg:i%360}));
const longId='LAYOUT-LONG-'+ 'X'.repeat(52);batch[119].target_id=longId;
async function ingest(items){const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(items)});assert.equal(r.status,200);return r.json()}
heartbeat=setInterval(()=>ingest(batch.map(x=>({...x,sequence:++sequence}))).catch(()=>{}),5000);
await ingest(batch);await page.getByText('目标 120 ·',{exact:false}).waitFor();assert.equal(await page.locator('.rt-target').count(),100);
await page.getByRole('button',{name:'下一组',exact:true}).click();await page.getByRole('button',{name:'LAYOUT-0100',exact:true}).waitFor();
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();
await page.locator('.rt-details').filter({hasText:'120.000000'}).waitFor();await page.locator('.rt-details').filter({hasText:'已匹配本地登记档案'}).waitFor();
await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);
await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await wait(650);
const metrics=await page.evaluate(()=>window.ridMap.metrics());const canvas=await page.locator('.maplibregl-canvas').boundingBox();
assert.ok(metrics.selectedPixel.x>metrics.occlusion.left && metrics.selectedPixel.x<canvas.width-metrics.occlusion.right,JSON.stringify(metrics));
assert.ok(metrics.selectedPixel.y>metrics.occlusion.top && metrics.selectedPixel.y<canvas.height-metrics.occlusion.bottom,JSON.stringify(metrics));
await page.getByRole('textbox',{name:'搜索实时目标'}).fill(longId);await page.getByRole('button',{name:longId,exact:true}).click();await page.locator('.rt-details').filter({hasText:'未匹配本地档案'}).waitFor();
const longOverflow=await page.locator('#rt-details').evaluate(e=>e.scrollWidth>e.clientWidth);assert.equal(longOverflow,false);
await page.route('**/api/records?q=*',route=>route.fulfill({status:503,contentType:'application/json',body:'{}'}));
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0001');await page.getByRole('button',{name:'LAYOUT-0001',exact:true}).click();await page.locator('.rt-details').filter({hasText:'本地档案查询失败'}).waitFor();await page.unroute('**/api/records?q=*');
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();
const grip=page.getByRole('separator',{name:'调整底栏高度'});let box=await grip.boundingBox();await page.mouse.move(box.x+box.width/2,box.y+4);await page.mouse.down();await page.mouse.move(box.x+box.width/2,box.y-80,{steps:5});await page.mouse.up();await wait(200);
const grown=Number(await grip.getAttribute('aria-valuenow'));assert.ok(grown>=240);await grip.focus();await page.keyboard.press('ArrowUp');assert.equal(Number(await grip.getAttribute('aria-valuenow')),grown+16);
const preferred=Number(await grip.getAttribute('aria-valuenow'));await page.reload();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await wait(250);assert.equal(Number(await grip.getAttribute('aria-valuenow')),preferred);
await page.getByRole('button',{name:'隐藏事件面板',exact:true}).click();await page.locator('#rt-dock-restore').waitFor();await wait(50);assert.equal(await page.evaluate(()=>document.activeElement.id),'rt-dock-restore');await page.reload();await page.locator('#rt-dock-restore').waitFor();await page.locator('#rt-dock-restore').click();
await page.getByRole('button',{name:'接收器与解码',exact:true}).click();await page.getByLabel('串口',{exact:true}).waitFor();await wait(250);await page.getByLabel('串口',{exact:true}).fill('UNSAVED-COM');
await wait(3200);const baseline=requests.status;await wait(3200);const beforeRate=requests.status-baseline;
for(let i=0;i<20;i++){await page.getByRole('button',{name:'目标快照与事件',exact:true}).click();await page.getByRole('button',{name:'接收器与解码',exact:true}).click();}
assert.equal(await page.getByLabel('串口',{exact:true}).inputValue(),'UNSAVED-COM');assert.equal(requests.config,1);assert.equal(requests.writes,0);
const afterStart=requests.status;await wait(3200);const afterRate=requests.status-afterStart;assert.ok(afterRate<=beforeRate+2,{beforeRate,afterRate});
await page.getByRole('button',{name:'目标快照与事件',exact:true}).click();
// Generate real transport events without writing receiver configuration.
for(let i=0;i<23;i++){await stop();await page.locator('.rt-status').filter({hasText:'连接断开'}).waitFor();assert.equal(await page.getByRole('button',{name:'聚焦此目标',exact:true}).isDisabled(),true);start();await ready();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();}
assert.equal(await page.locator('.live-events li').count(),64);
await grip.focus();await page.keyboard.press('Home');const scroller=page.locator('#rt-event-scroll');await scroller.evaluate(e=>e.scrollTop=Math.min(400,e.scrollHeight/2));
const anchor=await scroller.evaluate(e=>{const r=e.getBoundingClientRect();return [...e.querySelectorAll('li')].map(li=>({text:li.textContent,y:li.getBoundingClientRect().top-r.top})).find(x=>x.y>=0)});
await stop();start();await ready();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await wait(200);
if(anchor){const next=await scroller.evaluate((e,a)=>{const li=[...e.querySelectorAll('li')].find(li=>li.textContent===a.text);return li?li.getBoundingClientRect().top-e.getBoundingClientRect().top:null},anchor);assert.ok(next!==null&&Math.abs(next-anchor.y)<4,JSON.stringify({anchor,next}));}
// Restore a normal useful desktop frame with live Worker data.
await ingest(batch.map(x=>({...x,sequence:++sequence})));await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();
await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await grip.focus();await page.keyboard.press('ArrowUp');await page.keyboard.press('ArrowUp');await page.keyboard.press('ArrowUp');await page.keyboard.press('ArrowUp');await wait(500);
const sizes=[[1920,1080],[1440,900],[1280,720],[1440,500],[768,1024],[390,844]];const themes=['graphite','blue','white'];
let frames=0;
for(const [width,height]of sizes){await page.setViewportSize({width,height});await wait(250);for(const theme of themes){await page.evaluate(t=>{document.body.classList.remove('theme-blue','theme-white');if(t!=='graphite')document.body.classList.add('theme-'+t)},theme);
const state=await page.evaluate(()=>{const root=document.getElementById('rt-layout'),panels=[...root.querySelectorAll('.mc-floating-panel')].filter(e=>!e.hidden);return {headerClipped:[...root.querySelectorAll('.mc-dock-header button')].filter(e=>e.getBoundingClientRect().height>0).some(e=>{const r=e.getBoundingClientRect(),h=root.querySelector('.mc-dock-header').getBoundingClientRect();return r.left<h.left-1||r.right>h.right+1||r.top<h.top-1||r.bottom>h.bottom+1}),overflow:document.documentElement.scrollWidth>innerWidth,compact:root.classList.contains('compact'),count:panels.length,clipped:panels.some(p=>{const action=p.querySelector('.mc-btn-row,.pagination');const a=action.getBoundingClientRect(),b=p.getBoundingClientRect();return a.bottom>b.bottom+1||a.top<b.top;})}});assert.equal(state.overflow,false);assert.equal(state.clipped,false);assert.equal(state.headerClipped,false,JSON.stringify({width,height,theme,state}));if(width<900||height<568)assert.ok(state.count<=1);frames++;
if(theme==='graphite')await page.screenshot({path:path.join(root,`realtime-b-${width}x${height}.png`)});
}}
await page.setViewportSize({width:1440,height:500});await wait(250);await page.locator('#rt-list-toggle').click();await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();await wait(100);assert.equal(await page.locator('#rt-details').isVisible(),true);assert.equal(await page.evaluate(()=>document.activeElement.id),'rt-details');const lowClipped=await page.locator('#rt-details').evaluate(e=>e.querySelector('.mc-btn-row').getBoundingClientRect().bottom>e.getBoundingClientRect().bottom+1);assert.equal(lowClipped,false);await page.getByRole('button',{name:'收起详情',exact:true}).click();
await page.setViewportSize({width:390,height:844});await wait(250);await page.locator('#rt-list-toggle').click();await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();assert.equal(await page.locator('#rt-directory').isVisible(),false);assert.equal(await page.locator('#rt-details').isVisible(),true);assert.equal(await page.locator('#rt-dock').isVisible(),false);await page.screenshot({path:path.join(root,'realtime-b-mobile-detail.png')});await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await wait(500);assert.equal(await page.locator('#rt-details').isVisible(),false);
for(const zoom of [1.25,1.5]){await page.setViewportSize({width:1280,height:720});await page.evaluate(z=>document.documentElement.style.zoom=String(z),zoom);await wait(250);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:path.join(root,`realtime-b-zoom-${zoom}.png`)});}
await page.evaluate(()=>document.documentElement.style.zoom='');await page.setViewportSize({width:1600,height:1000});await wait(250);
const savedBeforeHome=await page.evaluate(k=>localStorage.getItem(k),key);await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('body[data-screen=home]').waitFor();await page.setViewportSize({width:390,height:844});await wait(250);await page.setViewportSize({width:1600,height:1000});await wait(250);assert.equal(await page.evaluate(k=>localStorage.getItem(k),key),savedBeforeHome);await page.locator('#home-app-realtime').click();await page.locator('body[data-screen=realtime]').waitFor();await wait(250);
await page.evaluate(k=>localStorage.setItem(k,'broken json'),key);await page.reload();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await wait(250);assert.equal(await page.locator('#rt-dock').isVisible(),false);await page.locator('#rt-dock-restore').click();assert.equal(Number(await grip.getAttribute('aria-valuenow')),170);
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await wait(500);await page.screenshot({path:path.join(root,'realtime-b-final.png')});
const realtimeStatus=await (await fetch(base+'/api/realtime/status')).json();assert.equal(realtimeStatus.clients,1);
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
report={status:'PASS',root,exe,serverPid:child.pid,clients:realtimeStatus.clients,frames,requests,beforeRate,afterRate,checks:['embedded-assets-match-build','empty','real-worker-120-targets','search-pagination','local-record-match-unmatched-error','long-id','safe-focus','drag-keyboard','reload-persistence','hide-restore-focus','receiver-20-switches','events-bounded-at-64','event-scroll-anchor','three-themes-six-sizes-including-low-height','hidden-workspace-keeps-preferences','compact-select-focus','zoom-125-150','corrupt-storage'],note:'Synthetic input; no physical receiver transport opened.'};console.log(JSON.stringify(report));
}finally{clearInterval(heartbeat);if(browser){if(report.status!=='PASS'){const p=browser.contexts()[0]?.pages()[0];if(p){await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});console.log(JSON.stringify({root,errors,csp,diagnostic:await p.evaluate(()=>({layout:document.getElementById('rt-layout')?.outerHTML.slice(0,2000),metrics:window.ridMap?.metrics()})).catch(()=>null)}));}}await browser.close();}await stop();await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'layout-report.json'),JSON.stringify({...report,errors,csp},null,2));}