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-geofences-')); 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 report={}; try{ start();await ready(); 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())});page.on('dialog',d=>d.accept()); await page.goto(base+'/realtime');await page.getByRole('button',{name:'电子围栏',exact:true}).click();await page.locator('#gf-new').waitFor();await page.waitForFunction(()=>!document.querySelector('#gf-new').disabled);await page.waitForFunction(()=>window.ridGeofences.metrics()?.ready); assert.equal(await page.evaluate(()=>window.ridGeofences.metrics().camera.zoom),15); await page.locator('#gf-new').click();await page.locator('#gf-name').fill('园区 ');await page.locator('#gf-longitude').fill('120');await page.locator('#gf-latitude').fill('30');await page.locator('#gf-radius').fill('500');await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'已保存'}).waitFor();assert.equal(await page.locator('#gf-list .gf-entry').count(),1);assert.equal(await page.locator('#gf-list script').count(),0); let fences=await(await fetch(base+'/api/geofences')).json();const circleId=fences.entries[0].id; let seq=0;async function ingest(target_id,lon,lat){const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify([{target_id,receiver_id:'TEST',source_epoch:1,sequence:++seq,longitude:lon,latitude:lat,altitude_m:100,heading_deg:30}])});assert.equal(r.status,200);} await save('WHITE-FENCE','white');await ingest('WHITE-FENCE',120,30);await ingest('OTHER-FENCE',120,30);await wait(400);await page.locator('#gf-events-refresh').click();await page.locator('#gf-events li').filter({hasText:'OTHER-FENCE'}).waitFor();assert.equal(await page.locator('#gf-events li').filter({hasText:'WHITE-FENCE'}).count(),0); await page.locator('#gf-circle').click();await page.locator('#geofence-map canvas').first().click({position:{x:600,y:300}});await page.waitForFunction(()=>window.ridGeofences.metrics().mode==='');assert.notEqual(await page.locator('#gf-longitude').inputValue(),'120');await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'已保存'}).waitFor(); await page.locator('#gf-new').click();await page.locator('#gf-name').fill('多边形区域');await page.locator('#gf-polygon').click();for(const p of [{x:620,y:350},{x:820,y:350},{x:720,y:520}])await page.locator('#geofence-map canvas').first().click({position:p});await page.locator('#gf-finish').click();assert.equal(await page.locator('#gf-shape').inputValue(),'polygon');await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'已保存'}).waitFor();assert.equal(await page.locator('#gf-list .gf-entry').count(),2); // Invalid vertex drag restores the handle and never changes persisted geometry. const beforeDrag=await page.locator('#gf-vertices').inputValue();const h1=await page.locator('.gf-handle').nth(0).boundingBox(),h2=await page.locator('.gf-handle').nth(1).boundingBox(); await page.mouse.move(h1.x+h1.width/2,h1.y+h1.height/2);await page.mouse.down();await page.mouse.move(h2.x+h2.width/2,h2.y+h2.height/2,{steps:8});await page.mouse.up();await page.locator('#gf-message').filter({hasText:'范围无效'}).waitFor();assert.equal(await page.locator('#gf-vertices').inputValue(),beforeDrag); const restored=await page.locator('.gf-handle').nth(0).boundingBox();assert.ok(Math.abs(restored.x-h1.x)<2&&Math.abs(restored.y-h1.y)<2); // Escape cancels drawing without changing saved geometry. await page.locator('#gf-polygon').click();await page.keyboard.press('Escape');assert.equal(await page.evaluate(()=>window.ridGeofences.metrics().mode),''); await page.locator('#gf-vertices').fill('[[0,0],[1,1],[0,1],[1,0]]');await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'范围'}).waitFor();assert.equal((await(await fetch(base+'/api/geofences')).json()).entries.length,2); await page.locator('#gf-list .gf-entry').filter({hasText:'多边形区域'}).click();await page.locator('#gf-enabled').uncheck();await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'已保存'}).waitFor();assert.equal((await(await fetch(base+'/api/geofences')).json()).entries.find(e=>e.name==='多边形区域').enabled,false); // Concurrent revision conflicts retain the draft. await page.locator('#gf-name').fill('保留本地草稿');fences=await(await fetch(base+'/api/geofences')).json();const remote={...fences.entries.find(e=>e.id===circleId),name:'远端更新'};assert.equal((await fetch(base+'/api/geofences/'+remote.id,{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({fence:remote,expected_revision:fences.revision})})).status,200);await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'草稿已保留'}).waitFor();assert.equal(await page.locator('#gf-name').inputValue(),'保留本地草稿'); await page.getByRole('button',{name:'应用总览',exact:true}).click();await page.getByRole('button',{name:'电子围栏',exact:true}).click();assert.equal(await page.locator('#gf-name').inputValue(),'保留本地草稿');await page.waitForFunction(()=>window.ridGeofences.metrics()?.ready); await page.locator('#gf-refresh').click();await page.locator('#gf-list .gf-entry').filter({hasText:'远端更新'}).click();await page.locator('#gf-name').fill('故障时保留');await page.route('**/api/geofences/*',r=>r.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'测试保存失败'})}));await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'测试保存失败'}).waitFor();assert.equal(await page.locator('#gf-name').inputValue(),'故障时保留');await page.unroute('**/api/geofences/*'); await page.locator('#gf-list .gf-entry').filter({hasText:'远端更新'}).click(); for(const [width,height]of [[1600,1000],[1366,768],[900,700],[390,844],[1200,560]]){await page.setViewportSize({width,height});await wait(200);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);await page.locator('#gf-save').scrollIntoViewIfNeeded();const b=await page.locator('#gf-save').boundingBox();assert.ok(b.width>20&&b.x>=0&&b.x+b.width<=width);await page.screenshot({path:path.join(root,'fence-'+width+'x'+height+'.png'),fullPage:true});} await page.setViewportSize({width:1600,height:1000});await page.evaluate(()=>document.documentElement.style.zoom='2');await page.locator('#gf-save').scrollIntoViewIfNeeded();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);await page.screenshot({path:path.join(root,'fence-200percent.png'),fullPage:true});await page.evaluate(()=>document.documentElement.style.zoom='');await page.locator('#gf-delete').click();await page.locator('#gf-message').filter({hasText:'已删除'}).waitFor();assert.equal((await(await fetch(base+'/api/geofences')).json()).entries.length,1); await page.getByRole('button',{name:'实时目标工作台',exact:true}).click();await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);assert.equal(await page.locator('.mc-map-toolstrip').count(),0); assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);report={status:'PASS',root,exe,checks:['A sidebar navigation','default15','circle numeric and map edit','polygon drawing','invalid drag restores vertex','safe names','white exemption','persistent events','Escape','invalid geometry','enable/disable','conflict preserves draft','page change preserves draft','failed save preserves draft','five viewports','delete','realtime preserved'],errors,csp};console.log(JSON.stringify(report)); }catch(error){console.log('FAILED ROOT',root,error.stack,JSON.stringify(errors));if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png'),fullPage:true}).catch(()=>{});}throw error;}finally{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);}