Files
fpv-rid-workbench/scripts/test-target-lists.mjs
T
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

98 lines
15 KiB
JavaScript

import {UI_URL, assertUiPortAvailable} from './ui-test-port.mjs';
const base=UI_URL;
await assertUiPortAvailable();
// Real SQLite, Rust/Wasm, Worker and WebGL acceptance. No physical transports opened.
import {mkdtemp,readFile,writeFile} 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-target-lists-'));
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
let child,browser,heartbeat,output='';const errors=[],csp=[];
const wait=ms=>new Promise(r=>setTimeout(r,ms));
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 stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done}}
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/target-lists')).ok)return}catch{}await wait(100)}throw Error('server timeout '+output)}
async function snapshot(){return(await fetch(base+'/api/target-lists')).json()}
async function save(id,kind,note='验收备注'){const current=await snapshot();const r=await fetch(base+'/api/target-lists/'+id,{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({list_kind:kind,note,expected_revision:current.revision})});assert.equal(r.status,200);return r.json()}
let sequence=0;const targetIds=['LIST-WHITE','LIST-BLACK','LIST-OTHER'];
async function ingest(){sequence++;const frames=targetIds.map((target_id,i)=>({target_id,receiver_id:'TEST',source_epoch:1,sequence,longitude:120.15+i*.001,latitude:30.28+i*.001,altitude_m:100,heading_deg:40}));const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(frames)});assert.equal(r.status,200)}
let report={};
try{
start();await ready();
assert.deepEqual((await snapshot()).entries,[]);
await save('LIST-WHITE','white');await save('LIST-BLACK','black');await save('OFFLINE_001','white');
for(const file of ['target-lists.css','map-adapter.js'])assert.equal(await(await fetch(base+'/'+file)).text(),await readFile(path.join('dist/web-ui',file),'utf8'));
browser=await chromium.launch({headless:true,channel:'msedge'});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())});
await page.goto(base+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await page.locator('#rt-dock-restore').click();
const filters=page.getByRole('group',{name:'目标名单筛选'});
await page.waitForFunction(()=>![...document.querySelectorAll('.rt-target-list-filters button')].some(b=>b.disabled));
await ingest();heartbeat=setInterval(()=>ingest().catch(()=>{}),3000);
await page.getByRole('button',{name:'LIST-BLACK',exact:true}).waitFor();await page.waitForFunction(()=>window.ridMap?.metrics().mapReady&&window.ridMap.metrics().classifiedTargets.black===1);
assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'white');
assert.equal(await page.getByRole('button',{name:'LIST-OTHER',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'unknown');
const blackEvents=()=>page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-BLACK'});
await blackEvents().waitFor();for(let i=0;i<5;i++)await ingest();await wait(500);assert.equal(await blackEvents().count(),1);
await page.getByRole('button',{name:'LIST-BLACK',exact:true}).click();await page.locator('.rt-detail-classification').waitFor();
await page.screenshot({path:path.join(root,'classified-workspace.png')});
await filters.getByRole('button',{name:/^白名单/}).click();await page.waitForFunction(()=>window.ridMap.metrics().visibleTargets===1);assert.equal(await page.locator('.rt-target').count(),1);assert.equal(await page.evaluate(()=>window.ridMap.metrics().targets),3);
await filters.getByRole('button',{name:/^全部/}).click();await page.getByRole('button',{name:'LIST-WHITE',exact:true}).click();
await page.getByRole('button',{name:'加入黑名单',exact:true}).click();
await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'black');
await page.locator('.rt-detail-classification').getByRole('button',{name:'加入黑名单',exact:true}).click();await wait(350);
await page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-WHITE'}).waitFor();
assert.equal(await page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-WHITE'}).count(),1);
await page.getByRole('button',{name:'管理黑白名单',exact:true}).click();await page.locator('#rt-list-manager').waitFor();assert.equal((await page.locator('#rt-list-manager').innerText()).includes('rows.get'),false);assert.equal(await page.locator('.rt-list-pagination').getByRole('button',{name:'下一页',exact:true}).isDisabled(),true);
await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('OFFLINE_002');await page.locator('#rt-list-entry-kind').selectOption('white');await page.locator('#rt-list-entry-note').fill('离线条目');await page.locator('#rt-list-entry-form .primary').click();
await page.locator('.rt-list-manager-footer').filter({hasText:'已将 OFFLINE_002 保存为白名单'}).waitFor();assert.equal(await page.evaluate(()=>window.ridMap.metrics().targets),3);
assert.equal((await(await fetch(base+'/api/records?page=1')).json()).total,0);
const offline=page.locator('.rt-list-row[data-target-id=OFFLINE_002]');await offline.getByRole('button',{name:'编辑',exact:true}).click();assert.equal(await page.locator('#rt-list-entry-id').isEditable(),false);
await page.locator('#rt-list-entry-note').fill('<img src=x onerror=alert(1)>人工备注');await page.locator('#rt-list-entry-form .primary').click();await offline.filter({hasText:'人工备注'}).waitFor();assert.equal(await offline.locator('img').count(),0);
const otherContext=await browser.newContext({viewport:{width:1280,height:900}}),other=await otherContext.newPage();await other.goto(base+'/realtime');await other.waitForFunction(()=>![...document.querySelectorAll('.rt-target-list-filters button')].some(b=>b.disabled));
await other.getByRole('button',{name:'管理黑白名单',exact:true}).click();await other.locator('.rt-list-row[data-target-id=OFFLINE_002]').filter({hasText:'人工备注'}).waitFor();
await page.locator('#rt-list-entry-note').fill('尚未保存的备注');await save('OFFLINE_002','white','来自其他浏览器');
await offline.filter({hasText:'来自其他浏览器'}).waitFor({timeout:12000});assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'尚未保存的备注');
await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('LIST-OTHER');await page.locator('#rt-list-entry-note').fill('冲突后保留草稿');
let releaseRequest,heldRequest;const gate=new Promise(r=>releaseRequest=r),held=new Promise(r=>heldRequest=r);let intercept=true;
await page.route('**/api/target-lists/LIST-OTHER',async route=>{if(route.request().method()==='PUT'&&intercept){intercept=false;heldRequest();await gate;}await route.continue()});
await page.locator('#rt-list-entry-form .primary').click();await held;assert.equal(await page.locator('#rt-list-entry-id').isDisabled(),true);await save('REMOTE_001','white');releaseRequest();
await page.locator('.rt-list-manager-footer p.error').filter({hasText:'其他页面修改'}).waitFor();await page.locator('.rt-list-row[data-target-id=REMOTE_001]').waitFor();assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'冲突后保留草稿');
await page.unroute('**/api/target-lists/LIST-OTHER');await page.locator('#rt-list-entry-form .primary').click();await page.locator('.rt-list-row[data-target-id=LIST-OTHER]').waitFor();
await page.locator('#rt-list-entry-note').fill('保存失败仍保留');await page.route('**/api/target-lists/LIST-OTHER',r=>r.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离保存失败'})}));
await page.locator('#rt-list-entry-form .primary').click();await page.locator('.rt-list-manager-footer p.error').filter({hasText:'隔离保存失败'}).waitFor();assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'保存失败仍保留');assert.equal((await snapshot()).entries.find(e=>e.target_id==='LIST-OTHER').note,'冲突后保留草稿');await page.unroute('**/api/target-lists/LIST-OTHER');
await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('bad id');await page.locator('#rt-list-entry-form').evaluate(f=>f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true})));await page.locator('.rt-list-manager-footer p.error').filter({hasText:'目标标识须'}).waitFor();
await page.screenshot({path:path.join(root,'manager-validation.png')});
await page.locator('.rt-list-row[data-target-id=LIST-OTHER]').getByRole('button',{name:'移除',exact:true}).click();await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2);
await page.route('**/api/target-lists?revision=*',r=>r.fulfill({status:503,contentType:'application/json',body:'{}'}));
await page.locator('#rt-list-manager .rt-list-sync-error').filter({hasText:'暂用上次名单'}).waitFor({timeout:12000});
assert.equal(await page.evaluate(()=>window.ridMap.metrics().classifiedTargets.black),2);
await page.unroute('**/api/target-lists?revision=*');await page.locator('#rt-list-manager .rt-list-sync-error').getByRole('button',{name:'重试',exact:true}).click();await page.locator('#rt-list-manager .rt-list-sync-error').waitFor({state:'hidden'});
const unavailableContext=await browser.newContext(),unavailable=await unavailableContext.newPage();
await unavailable.route('**/api/target-lists**',r=>r.fulfill({status:503,contentType:'application/json',body:'{}'}));await unavailable.goto(base+'/realtime');
await unavailable.locator('#rt-directory .rt-list-sync-error').filter({hasText:'名单读取失败'}).waitFor();await unavailable.locator('.rt-target').first().waitFor();
assert.equal(await unavailable.locator('.rt-target .rt-list-badge[data-kind=unavailable]').count(),3);
assert.equal(await unavailable.getByRole('group',{name:'目标名单筛选'}).getByRole('button',{name:/^黑名单/}).isDisabled(),true);assert.ok((await unavailable.getByRole('group',{name:'目标名单筛选'}).getByRole('button',{name:/^黑名单/}).innerText()).includes('—'));
await unavailableContext.close();
const sizes=[[1600,1000],[1366,600],[1080,900],[390,844]];const geometry=[];
for(const [width,height]of sizes){await page.setViewportSize({width,height});await wait(250);await page.locator('#rt-list-entry-form .primary').scrollIntoViewIfNeeded();const box=await page.locator('#rt-list-entry-form .primary').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=width&&box.y>=48&&box.y+box.height<=height+1);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('.rt-list-manager-body').evaluate(e=>e.scrollTop=0);await page.screenshot({path:path.join(root,'manager-'+width+'.png')});geometry.push({width,height})}
await page.setViewportSize({width:1280,height:720});await page.evaluate(()=>document.documentElement.style.zoom='2');await page.locator('#rt-list-entry-form .primary').scrollIntoViewIfNeeded();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:path.join(root,'manager-zoom200.png')});await page.evaluate(()=>document.documentElement.style.zoom='');
await page.keyboard.press('Escape');await page.locator('#rt-list-manager').waitFor({state:'hidden'});await page.waitForFunction(()=>['rt-list-manager-open','rt-list-manager-from-directory'].includes(document.activeElement.id));
await page.setViewportSize({width:1600,height:1000});await otherContext.close();
const persisted=await snapshot();clearInterval(heartbeat);await stop();start();await ready();assert.deepEqual(await snapshot(),persisted);
await page.reload();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await ingest();await page.waitForFunction(()=>window.ridMap.metrics().targets===3&&window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-OTHER',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'unknown');
// Registration remains independent: registered targets are not automatically trusted.
for(const [id,expectedKind]of [['LIST-BLACK','black'],['LIST-OTHER','unknown']]){
const response=await fetch(base+'/api/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({serialNo:id})});assert.equal(response.status,200);const record=(await response.json()).record;
await page.getByRole('button',{name:id,exact:true}).click();await page.locator('.rt-details').filter({hasText:'已匹配本地登记档案'}).waitFor();
assert.equal(await page.locator('.rt-detail-classification .rt-list-badge').getAttribute('data-kind'),expectedKind);
assert.equal((await fetch(base+'/api/records/'+record.id,{method:'DELETE'})).status,200);
}
assert.equal((await snapshot()).entries.find(e=>e.target_id==='LIST-BLACK').list_kind,'black');
assert.equal(await page.locator('.mc-map-toolstrip').count(),0);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
report={status:'PASS',root,exe,geometry,errors,csp,revision:persisted.revision,entries:persisted.entries.length,checks:['exact persisted membership independent of registration','online quick marking and offline entry','map and directory filtering without telemetry loss','black alert deduplication','safe notes and reactive remote updates','cross-browser sync preserves unsaved draft','optimistic concurrency and failed save rollback','busy controls and ID validation','removal restores unclassified','four viewports and 200% zoom','escape return focus','restart persistence','failed initial load and stale snapshot recovery','topdown map and removed toolbar preserved']};console.log(JSON.stringify(report));
}catch(error){console.log('FAILED ROOT',root,error.stack,JSON.stringify({errors,csp}));if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)console.log('MAP',await p.evaluate(()=>window.ridMap?.metrics()).catch(()=>null));}if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});}throw error;}finally{clearInterval(heartbeat);if(browser)await browser.close();await stop();await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output)}