// 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'; import {randomBytes} from 'node:crypto'; 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; let sessionCookie=''; const account={username:'registry-verification',password:randomBytes(24).toString('base64url')}; 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;}); sessionCookie=''; for(let i=0;i<150;i++){ if(spawnError||child.exitCode!==null)throw Error(output); const status=output.includes('FPV-RID Rust 登记站') ?await fetch(base+'/api/auth/status',{signal:AbortSignal.timeout(1000)}).catch(()=>null) :null; if(status?.ok){ const {configured}=await status.json(); const session=await fetch(base+(configured?'/api/auth/login':'/api/auth/setup'),{ method:'POST',headers:{origin:base,'content-type':'application/json'},body:JSON.stringify(account) }); assert.ok(session.ok,`验收账号登录失败:HTTP ${session.status}`); sessionCookie=session.headers.get('set-cookie')?.split(';')[0]??''; assert.match(sessionCookie,/^rid_session=/); return; } 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;} function authenticated(route,options={}){return fetch(base+route,{...options,headers:{cookie:sessionCookie,...options.headers}});} async function api(route,method='GET',body,status=200){const r=await authenticated(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;ib.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 authenticated(`/api/records/${id}/archive`);const html=await r.text();assert.match(html,/data:image\/png;base64,/);assert.ok(!html.includes('${'));assert.ok(html.includes('<测试>')); } 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,'--no-browser']); 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,'--no-browser']); 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 authenticated('/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 authenticated('/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,'--no-browser']); 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,'--no-browser']);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,'--no-browser'],{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,'--no-browser']);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();}