Files
fpv-rid-workbench/scripts/verify.mjs
T
JiuContinent 7d2e37a0ef ```text
chore: 新增项目规则文档、构建别名及忽略规则

添加 AGENTS.md 项目规则文件,涵盖语言与工具链、模块设计、
Git 提交规范及验证流程等内容。

变更要点:
- .cargo/config.toml 新增 xtask 命令别名
- .gitignore 忽略运行时地图缓存、接收器配置文件、
  构建锁文件及本地 docs/ 目录
- 新增 AGENTS.md 定义项目编码、提交与审查规则
```
2026-10-21 16:23:47 +08:00

114 lines
9.6 KiB
JavaScript

// Uses built-in Node APIs as test tooling. Runs only Rust against disposable data.
import {mkdtemp,mkdir,writeFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
import assert from 'node:assert/strict';
import {DatabaseSync} from 'node:sqlite';
import {inflateRawSync} from 'node:zlib';
const repo=path.resolve(import.meta.dirname,'..');
const root=await mkdtemp(path.join(tmpdir(),'RID-中文验证-'));
const base='http://127.0.0.1:8787';
const png='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=';
let child;let output='';
let spawnError;
async function start(command,args){
// Never attach to, or mutate, an unrelated service already listening on this port.
let occupied=false;try{await fetch(base+'/api/records',{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}
if(occupied)throw Error('8787 已被占用,请关闭登记站再执行独立验收');
output='';spawnError=null;child=spawn(command,args,{cwd:root,windowsHide:true,stdio:['ignore','pipe','pipe']});
child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);
child.on('error',e=>{spawnError=e;output+=e.message;});
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output);try{const r=await fetch(base+'/api/records');if(r.ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('启动超时 '+output);
}
async function stop(){if(child&&!spawnError&&child.exitCode===null){const exited=new Promise(r=>child.once('exit',r));if(child.kill())await exited;}child=null;}
async function api(route,method='GET',body,status=200){const r=await fetch(base+route,{method,headers:body?{'content-type':'application/json'}:{},body:body?JSON.stringify(body):undefined});const v=await r.json();assert.equal(r.status,status,JSON.stringify(v));return v;}
function unzip(bytes){
const end=bytes.lastIndexOf(Buffer.from([0x50,0x4b,0x05,0x06]));assert.ok(end>=0);
const entries=new Map();let offset=bytes.readUInt32LE(end+16);
for(let i=0;i<bytes.readUInt16LE(end+10);i++){
assert.equal(bytes.readUInt32LE(offset),0x02014b50);
const method=bytes.readUInt16LE(offset+10),size=bytes.readUInt32LE(offset+20),rawSize=bytes.readUInt32LE(offset+24);
const nameLength=bytes.readUInt16LE(offset+28),extra=bytes.readUInt16LE(offset+30),comment=bytes.readUInt16LE(offset+32),local=bytes.readUInt32LE(offset+42);
const name=bytes.toString('utf8',offset+46,offset+46+nameLength);
assert.equal(bytes.readUInt32LE(local),0x04034b50);
const start=local+30+bytes.readUInt16LE(local+26)+bytes.readUInt16LE(local+28);
const compressed=bytes.subarray(start,start+size);assert.ok(method===0||method===8);
const data=method===8?inflateRawSync(compressed):compressed;assert.equal(data.length,rawSize);
entries.set(name,data);offset+=46+nameLength+extra+comment;
}return entries;
}
async function exports(id,label){
for(const kind of ['archive','excel']){
const r=await fetch(base+'/api/export/'+kind,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({ids:[id]})});assert.equal(r.status,200);
const bytes=Buffer.from(await r.arrayBuffer());const entries=unzip(bytes);
if(kind==='archive'){
const manifest=JSON.parse(entries.get('档案库/records.json').toString());assert.equal(manifest[0].id,id);assert.equal(manifest[0].fpvCode,'FPV00000001');
assert.deepEqual(entries.get('档案库/照片/TEST-SN-001-1.png'),Buffer.from(png.split(',')[1],'base64'));
assert.match(entries.get('档案库/档案卡/TEST-SN-001.html').toString(),/data:image\/png;base64,/);
}else{
assert.ok(entries.has('[Content_Types].xml'));assert.ok(entries.has('xl/workbook.xml'));assert.ok(entries.has('xl/worksheets/sheet1.xml'));
const xml=[...entries.values()].map(b=>b.toString()).join('');assert.ok(xml.includes(id));assert.ok(xml.includes('TEST-SN-001'));assert.ok(xml.includes('模块 SN'));
}
await writeFile(path.join(root,`${label}-${kind}.zip`),bytes);
}
const r=await fetch(base+`/api/records/${id}/archive`);const html=await r.text();assert.match(html,/data:image\/png;base64,/);assert.ok(!html.includes('${'));assert.ok(html.includes('&lt;测试&gt;'));
}
try{
const exe=path.resolve(process.argv[2]||path.join(repo,'dist/FPV-RID-Rust/fpv-rid-registry.exe'));
await start(exe,['--data-root',root]);
const a=await api('/api/records','POST',{serialNo:'TEST-SN-001',uasCode:'FPV00000001',modelName:'<测试>',ownerName:'原登记人',photo1:png});
const id=a.record.id;assert.match(id,/^[0-9a-f]{36}$/);assert.equal(a.existing,false);
const b=await api('/api/records','POST',{serialNo:'TEST-SN-001',modelName:'',ownerName:''});assert.equal(b.existing,true);assert.equal(b.record.modelName,'<测试>');
await api('/api/records','POST',{serialNo:'TEST-SN-002',uasCode:'FPV00000001'},400);
await api('/api/records','POST',{serialNo:'x'},400);
assert.equal((await api('/api/records?q='+encodeURIComponent('原登记人'))).records.length,1);
await exports(id,'rust-initial');await stop();
const dbPath=path.join(root,'registry/data/registry.sqlite');
let db=new DatabaseSync(dbPath);const before=db.prepare('SELECT hex(image) AS bytes FROM photos').get().bytes;db.close();
await start(exe,['--data-root',root]);
assert.equal((await api('/api/records')).records[0].id,id);
assert.equal((await api('/api/resolve?url='+encodeURIComponent(base+'/r/'+id))).id,id);
await api('/api/resolve?url='+encodeURIComponent('http://example.com/r/'+id),'GET',undefined,400);
await exports(id,'rust');db=new DatabaseSync(dbPath);assert.equal(db.prepare('SELECT hex(image) AS bytes FROM photos').get().bytes,before);db.close();
const blocked=await fetch(base+'/api/records',{headers:{origin:'https://example.com'}});assert.equal(blocked.status,403);
const p=await api('/api/records?page=1&pageSize=1');assert.equal(p.total,1);assert.equal(p.records.length,1);
await api('/api/records?page=0','GET',undefined,400);
const edited=await api('/api/records/'+id,'PATCH',{modelName:'',ownerName:'新登记人'});assert.equal(edited.record.modelName,'');
await api('/api/records/'+id,'PATCH',{serialNo:'OTHER-SN'},400);
await api('/api/records/'+id,'PATCH',{ownerName:'must rollback',photo1:'invalid'},400);
assert.equal((await api('/api/resolve?url='+encodeURIComponent(base+'/r/'+id))).ownerName,'新登记人');
await api('/api/records/'+id,'PATCH',{photo1:null,photo2:png});
assert.equal((await fetch(base+'/api/records/'+id+'/photos/2')).status,200);
await api('/api/records/'+id+'/photos/1','DELETE');await api('/api/records/'+id+'/photos/1','GET',undefined,404);
await api('/api/records','POST',{serialNo:'TEST-SN-001',photo1:png});
// Simulate an archive directory failure without modifying the active database.
await stop();await rm(path.join(root,'档案库'),{recursive:true});await writeFile(path.join(root,'档案库'),'blocked');
await start(exe,['--data-root',root]);
const pending=await api('/api/records','POST',{serialNo:'TEST-SN-003',ownerName:'已保存'});assert.equal(pending.archiveStatus,'pending');assert.ok(pending.warning);
assert.equal((await api('/api/archive/status')).archiveStatus,'pending');
await api('/api/archive/retry','POST',{},500);
db=new DatabaseSync(dbPath);assert.ok(db.prepare("SELECT value FROM registry_meta WHERE key='archive_pending'").get());db.close();
await rm(path.join(root,'档案库'));await api('/api/archive/retry','POST',{});
assert.equal((await api('/api/records')).records.length,2);
await api('/api/records/'+id,'DELETE');assert.equal((await api('/api/records')).records.length,1);
await api('/api/records/'+id,'PATCH',{ownerName:'resurrect',photo1:png},404);
await stop();await start(exe,['--data-root',root]);assert.equal((await api('/api/records')).records.length,1);await stop();
db=new DatabaseSync(path.join(root,'档案库/登记数据库.sqlite'));assert.equal(db.prepare('SELECT COUNT(*) AS n FROM records').get().n,1);assert.equal(db.prepare('PRAGMA integrity_check').get().integrity_check,'ok');db.close();
const legacyRoot=path.join(root,'legacy-regression');
await mkdir(path.join(legacyRoot,'registry/data'),{recursive:true});
const legacyRows=[{id:'1'.repeat(36),serialNo:'IMPORT-001',uasCode:'FPV00000001',createdAt:'2020-01-01T00:00:00.000Z'},{id:'2'.repeat(36),serialNo:'IMPORT-002',uasCode:'FPV00000002'}];
const legacyFile=path.join(legacyRoot,'registry/data/records.json');
await writeFile(legacyFile,JSON.stringify(legacyRows));
const rejected=spawn(exe,['--data-root',legacyRoot],{windowsHide:true,stdio:['ignore','pipe','pipe']});
let importError='';rejected.stderr.on('data',b=>importError+=b);
const exitCode=await new Promise((resolve,reject)=>{rejected.once('exit',resolve);rejected.once('error',reject);});
assert.notEqual(exitCode,0);assert.match(importError,/第 2 条/);
db=new DatabaseSync(path.join(legacyRoot,'registry/data/registry.sqlite'));
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM records').get().n,0);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM registry_meta').get().n,0);db.close();
legacyRows[1].createdAt='2020-01-01T00:00:00.000Z';await writeFile(legacyFile,JSON.stringify(legacyRows));
await start(exe,['--data-root',legacyRoot]);assert.equal((await api('/api/records')).records.length,2);await stop();
console.log(JSON.stringify({status:'PASS',root,scenarios:['Rust registration','Rust database restart','photo bytes','QR','ZIP/XLSX contents','HTML escaping','origin','PATCH','photo deletion','pagination','archive fault and retry','restart','backup integrity','invalid legacy import fails visibly and rolls back','corrected legacy file retries successfully']}));
}finally{await stop();}