Files
fpv-rid-workbench/scripts/test-registration-b.mjs
T
JiuContinent df9e8bdeb5 ```
feat(target-lists): 新增黑白名单管理与实时告警功能

- rid-shared 新增 target_lists 模块,定义名单数据契约
- 地图适配器支持按名单类型着色渲染目标(白/黑/未知)
- 新增名单筛选器与目标目录过滤联动
- 实时详情面板支持加入/编辑白名单与黑名单操作
- 新增黑名单命中告警横幅与事件日志高亮
- 新增名单管理浮层(Manager 组件)与徽章展示
- 底图默认切换为影像图,相机初始俯仰角归零
- color-scheme 切换为 dark,新增 glass/workbench 样式
```
2026-10-23 09:12:50 +08:00

126 lines
22 KiB
JavaScript

// Real Rust/Wasm acceptance in an isolated database. Never opens receiver transports.
import {mkdtemp,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';
import http from 'node:http';
import net from 'node:net';
const {chromium}=createRequire(import.meta.url)('playwright');
const root=await mkdtemp(path.join(tmpdir(),'RID-workspace-'));
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
const frontendPort=Number(process.env.RID_BROWSER_TEST_PORT||18787),backendPort=Number(process.env.RID_BACKEND_TEST_PORT||18788);
const base='http://127.0.0.1:'+frontendPort;
// Keep production origin checks unchanged. Only this isolated proxy maps the test origin.
const sockets=new Set();
const proxy=http.createServer((req,res)=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';const upstream=http.request({hostname:'127.0.0.1',port:backendPort,path:req.url,method:req.method,headers},r=>{res.writeHead(r.statusCode,r.headers);r.pipe(res)});upstream.on('error',()=>{res.writeHead(502);res.end()});req.pipe(upstream)});
proxy.on('upgrade',(req,socket,head)=>{const upstream=net.connect(backendPort,'127.0.0.1');sockets.add(socket);sockets.add(upstream);upstream.on('connect',()=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';upstream.write(`GET ${req.url} HTTP/1.1\r\n${Object.entries(headers).map(([k,v])=>`${k}: ${v}`).join('\r\n')}\r\n\r\n`);if(head.length)upstream.write(head);socket.pipe(upstream);upstream.pipe(socket)});upstream.on('error',()=>socket.destroy());socket.on('error',()=>upstream.destroy());socket.on('close',()=>{upstream.destroy();sockets.delete(socket);sockets.delete(upstream)})});
let occupied=false;try{await fetch(base,{signal:AbortSignal.timeout(800)});occupied=true;}catch{}if(occupied)throw Error('8787 occupied; preserving existing service');
const backendOccupied=await new Promise(resolve=>{const socket=net.connect(backendPort,'127.0.0.1');socket.once('connect',()=>{socket.destroy();resolve(true)});socket.once('error',()=>resolve(false));socket.setTimeout(800,()=>{socket.destroy();resolve(false)})});if(backendOccupied)throw Error('18788 occupied; preserving existing service');
let output='',child,browser;const errors=[],csp=[];
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,PATH:'C:\\Windows\\System32',RID_TEST_PORT:String(backendPort)},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;}}
async function preferences(){return (await fetch(base+'/api/appearance')).json();}
async function waitPref(predicate){for(let i=0;i<80;i++){const p=await preferences();if(predicate(p))return p;await new Promise(r=>setTimeout(r,100));}throw Error('preferences timeout');}
async function setLegacyTheme(page, theme) {
const screen = await page.locator("body").getAttribute("data-screen");
const query = await page.locator("#history-query").count() ? await page.locator("#history-query").inputValue() : "";
const current = await preferences();
const response = await fetch(base+'/api/appearance', {method:'PATCH', headers:{'content-type':'application/json'}, body:JSON.stringify({...current, theme})});
assert.equal(response.status, 200);
await page.reload();
await page.waitForFunction(t => document.body.dataset.theme === t, theme);
if (screen !== await page.locator("body").getAttribute("data-screen")) {
if (await page.locator("body").getAttribute("data-screen") !== "home") await page.getByRole("button",{name:"返回应用总览",exact:true}).click();
await page.locator("#home-app-"+screen).click();
}
if (query) { await page.locator("#history-query").fill(query); const total=(await (await fetch(base+"/api/records?page=1&q="+encodeURIComponent(query))).json()).total; await page.locator("#page-status").filter({hasText:"共 "+total+" 条"}).waitFor(); }
assert.equal(await page.locator('.theme-quick, .theme-cards').count(), 0);
assert.equal(await page.locator('body').evaluate(e => getComputedStyle(e).getPropertyValue('--work-panel').trim()), 'rgba(6, 18, 33, .40)');
}
try {
await new Promise((resolve,reject)=>{proxy.once('error',reject);proxy.listen(frontendPort,'127.0.0.1',resolve)});
start();await ready();browser=await chromium.launch({headless:true,channel:'msedge'});
const context=await browser.newContext({viewport:{width:1600,height:1000},acceptDownloads:true,permissions:['clipboard-read','clipboard-write']});
await context.addInitScript(()=>{
window.ridPhotoUrls=new Set();const create=URL.createObjectURL.bind(URL),revoke=URL.revokeObjectURL.bind(URL);
URL.createObjectURL=b=>{const u=create(b);if(b.type.startsWith('image/'))window.ridPhotoUrls.add(u);return u};URL.revokeObjectURL=u=>{window.ridPhotoUrls.delete(u);revoke(u)};
const decode=HTMLImageElement.prototype.decode;HTMLImageElement.prototype.decode=function(){const delay=this.src.startsWith('blob:')?(window.ridDecodeDelay||0):0;if(delay)window.ridDecodeStarted=true;return decode.call(this).then(()=>new Promise(r=>setTimeout(r,delay)))};
});
const page=await context.newPage();page.on('pageerror',e=>{errors.push(e.message);console.log('PAGE ERROR',e.stack)});page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text())});
for(let i=0;i<21;i++){const r=await fetch(base+'/api/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({serialNo:'B-SEED-'+String(i).padStart(3,'0'),modelName:'验收机型',ownerName:'隔离数据'})});assert.equal(r.status,200)}
await page.goto(base+'/?app=register');await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();
await page.screenshot({path:path.join(root,'register-empty.png')});
console.log('STAGE selection');const png=Buffer.from(await page.evaluate(()=>{let c=document.createElement('canvas');c.width=20;c.height=20;let x=c.getContext('2d');x.fillStyle='#5098d1';x.fillRect(0,0,20,20);return c.toDataURL().split(',')[1]}),'base64');
const file=name=>({name,mimeType:'image/png',buffer:png});
const choose=async(id,name)=>{await page.locator(id).setInputFiles(file(name));};
const readyPhoto=async(i,name)=>{await page.locator('#slot-name-'+i).filter({hasText:name}).waitFor();await page.waitForFunction(i=>document.querySelector('#slot-status-'+i).getAttribute('aria-busy')==='false',i)};
// Selection, menu keyboard and redraw focus.
assert.equal(await page.locator('#select-all').isVisible(),false);assert.equal(await page.locator('#export-toggle').isDisabled(),true);
await page.locator('#selection-toggle').click();const first=page.locator('.archive-select input').first();await first.focus();const firstId=await first.getAttribute('id');await page.keyboard.press('Space');assert.equal(await page.evaluate(()=>document.activeElement.id),firstId);
await page.locator('#export-toggle').click();assert.equal(await page.locator('#export-options').isVisible(),true);await page.keyboard.press('Escape');assert.equal(await page.evaluate(()=>document.activeElement.id),'export-toggle');
await page.locator('#select-all').check();assert.equal(await page.locator('.archive-select input:checked').count(),20);
for(const kind of ['excel','archive']){await page.locator('#export-toggle').click();const req=page.waitForRequest(r=>r.url().endsWith('/api/export/'+kind));const dl=page.waitForEvent('download');await page.locator('#export-'+kind).click();assert.equal((await req).postDataJSON().ids.length,20);await(await dl).saveAs(path.join(root,kind==='excel'?'records.xlsx':'archives.zip'))}
await page.locator('#selection-toggle').click();assert.equal(await page.locator('#export-toggle').isDisabled(),true);
const card=page.locator('.archive-card').first();await card.locator('.archive-more').click();await page.keyboard.press('Escape');assert.equal(await page.evaluate(()=>document.activeElement.classList.contains('archive-more')),true);
await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片',exact:true}).click();await page.locator('#edit-model').waitFor();await page.locator('#edit-cancel').click();await page.waitForFunction(()=>document.activeElement.classList.contains('archive-more'));
console.log('STAGE draft');
// Viewing another record never overwrites draft fields.
await page.locator('#serial-no').fill('B-NEW-001');await page.locator('#owner-name').fill('待保存草稿');await card.getByRole('button',{name:'查看档案 →',exact:true}).click();assert.equal(await page.locator('#serial-no').inputValue(),'B-NEW-001');assert.match(await page.locator('#result-context').innerText(),/正在查看/);
page.once('dialog',d=>d.dismiss());await page.locator('#new-registration').click();assert.equal(await page.locator('#owner-name').inputValue(),'待保存草稿');page.once('dialog',d=>d.accept());await page.locator('#new-registration').click();assert.equal(await page.locator('#serial-no').inputValue(),'');assert.equal(await page.evaluate(()=>document.activeElement.id),'serial-no');assert.equal(await page.locator('#empty-result').isVisible(),true);
console.log('STAGE photos');
// Invalid replacement and cancelled picker preserve the accepted image.
const [picker]=await Promise.all([page.waitForEvent('filechooser'),page.locator('[data-photo-choose="0"]').click()]);await picker.setFiles(file('valid.png'));await readyPhoto(0,'valid.png');const src=await page.locator('#slot-preview-0').getAttribute('src');await page.locator('#photo-1').setInputFiles([]);assert.equal(await page.locator('#slot-preview-0').getAttribute('src'),src);
await page.locator('#photo-1').setInputFiles({name:'broken.png',mimeType:'image/png',buffer:Buffer.from('broken')});await page.locator('#slot-status-0').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal(await page.locator('#slot-preview-0').getAttribute('src'),src);await page.locator('#slot-keep-0').click();
// Out-of-order decode, removal and reset invalidate old work.
await page.evaluate(()=>{window.ridDecodeDelay=250;window.ridDecodeStarted=false});await choose('#photo-1','slow.png');await page.waitForFunction(()=>window.ridDecodeStarted);await page.evaluate(()=>window.ridDecodeDelay=0);await choose('#photo-1','latest.png');await readyPhoto(0,'latest.png');await page.waitForTimeout(320);assert.equal(await page.locator('#slot-name-0').innerText(),'latest.png');
await page.evaluate(()=>{window.ridDecodeDelay=200;window.ridDecodeStarted=false});await choose('#photo-2','removed.png');await page.waitForFunction(()=>window.ridDecodeStarted);await page.locator('#slot-remove-1').click();await page.waitForTimeout(240);assert.equal(await page.locator('#slot-preview-1').isVisible(),false);
await choose('#photo-2','reset.png');page.once('dialog',d=>d.accept());await page.locator('#new-registration').click();await page.waitForTimeout(250);assert.equal(await page.locator('#slot-preview-1').isVisible(),false);await page.evaluate(()=>window.ridDecodeDelay=0);
assert.equal(await page.evaluate(()=>window.ridPhotoUrls.size),0);
console.log('STAGE submit');
// Failure restores all controls and keeps draft + photos; busy navigation is blocked.
await page.locator('#serial-no').fill('B-NEW-001');await page.locator('#model-name').fill('验收新机');await page.locator('#owner-name').fill('原始快照');await choose('#photo-1','snapshot.png');await readyPhoto(0,'snapshot.png');
const draftPhoto=await page.locator('#slot-preview-0').getAttribute('src');
await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-settings').click();await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-register').click();
assert.equal(await page.locator('#serial-no').inputValue(),'B-NEW-001');assert.equal(await page.locator('#owner-name').inputValue(),'原始快照');assert.equal(await page.locator('#slot-preview-0').getAttribute('src'),draftPhoto);assert.equal(await page.evaluate(()=>window.ridPhotoUrls.size),1);
let requests=0;
await page.route('**/api/records',async route=>{if(route.request().method()==='POST'){requests++;assert.equal(route.request().postDataJSON().ownerName,'原始快照');await new Promise(r=>setTimeout(r,450));await route.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离验收失败'})})}else await route.continue()});
const sent=page.waitForRequest(r=>r.url().endsWith('/api/records')&&r.method()==='POST');await page.locator('#register-button').click();await sent;assert.equal(await page.locator('#serial-no').isDisabled(),true);assert.equal(await page.locator('#new-registration').isDisabled(),true);await page.getByRole('button',{name:'返回应用总览',exact:true}).click();assert.equal(await page.locator('body').getAttribute('data-screen'),'register');await page.locator('#register-form').evaluate(f=>{f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}));f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}))});
await page.locator('#form-message').filter({hasText:'隔离验收失败'}).waitFor();assert.equal(requests,1);assert.equal(await page.locator('#owner-name').inputValue(),'原始快照');assert.equal(await page.locator('#slot-name-0').innerText(),'snapshot.png');assert.equal(await page.locator('#serial-no').isEnabled(),true);await page.unroute('**/api/records');
console.log('STAGE save success');
// Saving waits for the latest photo validation and uses one immutable snapshot.
await page.evaluate(()=>{window.ridDecodeDelay=250;window.ridDecodeStarted=false});await choose('#photo-2','pending.png');await page.waitForFunction(()=>window.ridDecodeStarted);await page.locator('#register-button').click();await page.locator('#form-message').filter({hasText:'登记成功'}).waitFor();await page.evaluate(()=>window.ridDecodeDelay=0);
let records=(await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records;assert.equal(records.length,1);assert.ok(records[0].photo1Url&&records[0].photo2Url);const record=records[0];await page.locator('#qr-stage svg').waitFor();assert.match(await page.locator('#result-context').innerText(),/B-NEW-001/);
const qrDownload=page.waitForEvent('download');await page.locator('#download-qr').click();await(await qrDownload).saveAs(path.join(root,'qr.png'));await page.locator('#copy-url').click();assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),record.qrUrl);
assert.equal((await fetch(base+record.archiveUrl)).status,200);assert.equal((await fetch(base+record.downloadArchiveUrl)).status,200);
console.log('STAGE edit');
await page.screenshot({path:path.join(root,'register-saved.png')});
// Duplicate SN updates instead of adding another record.
await page.locator('#owner-name').fill('更新登记人');await page.locator('#register-button').click();await page.locator('#form-message').filter({hasText:'该 SN 已登记'}).waitFor();assert.equal((await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records.length,1);
// A committed record remains saved even when the follow-up list request fails.
let failList=true;await page.route('**/api/records?**',async r=>{if(failList){failList=false;await r.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离列表失败'})})}else await r.continue()});await page.locator('#register-button').click();await page.locator('#history-message').filter({hasText:'已保存,但列表刷新失败'}).waitFor();assert.equal((await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records[0].ownerName,'更新登记人');await page.unroute('**/api/records?**');
await page.locator('#history-query').fill('B-NEW-001');await page.locator('#page-status').filter({hasText:'共 1 条'}).waitFor();const own=page.locator('.archive-card').filter({has:page.getByRole('heading',{name:'B-NEW-001',exact:true})});
const edit=async()=>{await own.locator('.archive-more').click();await own.getByRole('button',{name:'编辑资料 / 照片',exact:true}).click();await page.locator('#edit-dialog').waitFor()};
await edit();await choose('#edit-photo-1','replace.png');await readyPhoto(2,'replace.png');await page.locator('#slot-remove-2').click();assert.match(await page.locator('#slot-name-2').innerText(),/现有照片/);
await page.locator('#edit-owner').fill('不得保存');await page.locator('#edit-photo-1').setInputFiles({name:'bad.png',mimeType:'image/png',buffer:Buffer.from('bad')});await page.locator('#slot-status-2.error').waitFor();await page.locator('#edit-save').click();await page.locator('#edit-message').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal((await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records[0].ownerName,'更新登记人');await page.locator('#edit-cancel').click();
await edit();await page.locator('#edit-owner').fill('修改后');await page.locator('#edit-delete-1').check();await choose('#edit-photo-2','replacement.png');await readyPhoto(3,'replacement.png');await page.locator('#edit-save').click();await page.locator('#edit-dialog').waitFor({state:'hidden'});await page.locator('#history-message').filter({hasText:'档案修改已保存'}).waitFor();records=(await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records;assert.equal(records[0].photo1Url,null);assert.ok(records[0].photo2Url);assert.equal(records[0].ownerName,'修改后');
console.log('STAGE geometry');
// Legacy theme preferences share one material; verify viewport/zoom geometry.
const cases=[];await page.locator('#new-registration').click();
for(const theme of ['graphite','blue','white']){await setLegacyTheme(page,theme);
for(const [width,height]of [[1600,1000],[1366,768],[1080,900],[390,844],[1366,600]]){await page.setViewportSize({width,height});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('.registration-photos').scrollIntoViewIfNeeded();await page.locator('#register-button').scrollIntoViewIfNeeded();const box=await page.locator('#register-button').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=width&&box.y>=48&&box.y+box.height<=height+1);await page.locator('#register-form .registration-fields-scroll>.registry-group:last-of-type>.registry-help').scrollIntoViewIfNeeded();const overlap=await page.evaluate(()=>{const a=document.querySelector('#register-form .registration-fields-scroll>.registry-group:last-of-type>.registry-help').getBoundingClientRect(),b=document.querySelector('.registration-savebar').getBoundingClientRect();return a.bottom>b.top&&a.top<b.bottom});assert.equal(overlap,false);cases.push({theme,width,height});if(width===1600){await page.locator('.registration-heading').scrollIntoViewIfNeeded();await page.screenshot({path:path.join(root,'register-'+theme+'.png')})}}
}
await page.setViewportSize({width:1600,height:1000});await page.evaluate(()=>document.documentElement.style.zoom='2');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('#register-button').scrollIntoViewIfNeeded();await page.screenshot({path:path.join(root,'register-zoom200.png')});await page.evaluate(()=>document.documentElement.style.zoom='');
await page.setViewportSize({width:390,height:844});await page.locator('#history-title').scrollIntoViewIfNeeded();const mobileHistory=await page.locator('.history-panel').boundingBox();const mobileEditor=await page.locator('.registration-editor').boundingBox();assert.ok(mobileHistory.height<=280.5);assert.ok(mobileHistory.y+mobileHistory.height<=mobileEditor.y);await page.setViewportSize({width:1600,height:1000});
console.log('STAGE delete');
// Delete current result and preserve unrelated records.
await own.getByRole('button',{name:'查看档案 →',exact:true}).click();await own.locator('.archive-more').click();page.once('dialog',d=>d.accept());await own.getByRole('button',{name:'删除档案',exact:true}).click();await page.locator('#empty-result').waitFor();await page.locator('#page-status').filter({hasText:'共 0 条'}).waitFor();assert.equal((await(await fetch(base+'/api/records?page=1')).json()).total,21);
await page.locator('#history-query').fill('');await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();await page.locator('#next-page').click();await page.locator('#page-status').filter({hasText:'第 2 / 2 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),1);
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
await writeFile(path.join(root,'report.json'),JSON.stringify({status:'PASS',root,errors,csp,cases,scenarios:['real Rust/Wasm registration B','validated photo preservation, cancel, replacement, reset, stale decode','immutable submit, failed save, duplicate suppression, busy navigation','draft/result separation, new confirmation','menu focus, selection redraw, current-page Excel and ZIP','duplicate SN, edit atomicity and delete current result','QR PNG and clipboard/archive links','three legacy theme values, 15 viewport cases, 200% zoom, mobile save boundary']},null,2));console.log(JSON.stringify({status:'PASS',root}));
}catch(e){console.log('FAILED ROOT',root,e.stack);if(browser){const pages=browser.contexts().flatMap(c=>c.pages());if(pages[0])await pages[0].screenshot({path:path.join(root,'failed.png')}).catch(()=>{});}throw e;}finally{if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();await new Promise(r=>proxy.close(r));await writeFile(path.join(root,'server.log'),output)}