test(scripts): 更新测试脚本以适配无头模式和接收器重构 - 所有测试脚本的 spawn 调用添加 --no-browser 参数,避免自动打开浏览器 - 更新 test-browser.mjs 导航流程,改为从 archives 页面通过 reference-rail 进入注册模块 - 更新 test-receiver.mjs 断言以适配多接收器架构(receivers.json 数组格式、 接收器前缀 target_id、默认 receiver_id) - test-module-navigation.mjs 新增设备管理模块的导航标签断言 ```
134 lines
21 KiB
JavaScript
134 lines
21 KiB
JavaScript
import {UI_URL, assertUiPortAvailable} from './ui-test-port.mjs';
|
||
const base=UI_URL;
|
||
await assertUiPortAvailable();
|
||
// Actual Rust/Wasm + Go integration against an isolated data root and local fixtures.
|
||
// Does not use a real TianDiTu key or open any receiver transport.
|
||
import {mkdtemp,mkdir,writeFile,readFile} 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 {createRequire} from 'node:module';
|
||
const require=createRequire(import.meta.url);
|
||
const {chromium}=require('C:/Users/20143/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||
const {PNG}=require('C:/Users/20143/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/pngjs');
|
||
const root=await mkdtemp(path.join(tmpdir(),'RID-map-settings-'));
|
||
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
|
||
|
||
const env={...process.env,RID_MAP_DOWNLOADER:process.env.RID_MAP_DOWNLOADER||'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0/rid-map-downloader.exe'};delete env.TIANDITU_TOKEN;
|
||
const fixture=new PNG({width:256,height:256});for(let i=0;i<fixture.data.length;i+=4){fixture.data[i]=25;fixture.data[i+1]=45;fixture.data[i+2]=65;fixture.data[i+3]=255;}const png=PNG.sync.write(fixture);
|
||
function xy(lon,lat,z){const n=2**z,r=lat*Math.PI/180;return [Math.floor((lon+180)/360*n),Math.floor((1-Math.log(Math.tan(r)+1/Math.cos(r))/Math.PI)/2*n)];}
|
||
const [x,y]=xy(120.155,30.285,11);
|
||
for(const layer of ['vec_w','cva_w','img_w','cia_w']){const dir=path.join(root,`maps/cache/${layer}/11/${x}`);await mkdir(dir,{recursive:true});await writeFile(path.join(dir,y+'.tile'),png);}
|
||
let child,browser,output='';const errors=[],csp=[];let report={};
|
||
function start(){child=spawn(exe,['--data-root',root,'--simulation-api','--no-browser'],{env,windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);}
|
||
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/maps/preferences')).ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('server timeout');}
|
||
async function stop(){if(child?.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
|
||
const json=async(url,method='GET',body)=>{const r=await fetch(base+url,{method,headers:{'content-type':'application/json'},...(body?{body:JSON.stringify(body)}:{})});const v=await r.json();return {status:r.status,value:v};};
|
||
async function job(state){for(let i=0;i<150;i++){const v=(await json('/api/maps/downloads')).value.job;if(v?.state===state)return v;if(v?.state==='failed'&&state==='completed')throw Error(JSON.stringify(v));await new Promise(r=>setTimeout(r,100));}throw Error('job timeout '+state);}
|
||
try{
|
||
|
||
start();await ready();browser=await chromium.launch({headless:true,channel:'msedge'});const page=await browser.newPage({viewport:{width:1600,height:1000}});
|
||
for(const name of ['map-settings.css','map-settings-adapter.js','map-loader.js','map-adapter.js'])assert.equal(await(await fetch(base+'/'+name)).text(),await readFile(path.resolve('crates/web-ui/public',name),'utf8'),'stale embedded asset: '+name);
|
||
page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/Content Security Policy|Refused to/i.test(m.text()))csp.push(m.text());});
|
||
const retryPage=await browser.newPage();let initialAttempts=0;await retryPage.route('**/api/maps/preferences',route=>++initialAttempts===1?route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'模拟首次读取失败'})}):route.continue());
|
||
await retryPage.goto(base);await retryPage.locator('#home-app-settings').click();await retryPage.locator('.reference-rail [data-open=maps]').click();await retryPage.waitForFunction(()=>document.querySelector('#map-save-message').textContent.includes('模拟首次读取失败'));assert.equal(await retryPage.locator('[data-map-action=reload]').isEnabled(),true,'initial load failure disabled retry');await retryPage.locator('[data-map-action=reload]').click();await retryPage.waitForFunction(()=>!document.querySelector('#map-save').disabled);assert.equal(initialAttempts,2);await retryPage.close();
|
||
// Switching away and back during the first load must not create competing responses.
|
||
let releaseLoad,firstLoad,loadRequests=0;const loadGate=new Promise(r=>releaseLoad=r),loadSeen=new Promise(r=>firstLoad=r);const pendingLoads=[];
|
||
const holdLoad=route=>{const work=(async()=>{loadRequests++;firstLoad();const response=await route.fetch();await loadGate;await route.fulfill({response});})();pendingLoads.push(work);return work;};
|
||
await page.route('**/api/maps/preferences',holdLoad);
|
||
try{await page.goto(base);await page.locator('#home-app-settings').click();await page.locator('.reference-rail [data-open=maps]').click();await loadSeen;await page.locator('.reference-rail [data-open=settings]').click();await page.locator('.reference-rail [data-open=maps]').click();await page.waitForTimeout(250);assert.equal(loadRequests,1,'first load duplicated by rapid settings navigation');}
|
||
finally{releaseLoad();await Promise.all(pendingLoads);await page.unroute('**/api/maps/preferences',holdLoad);}
|
||
await page.locator('#map-save').waitFor();await page.waitForFunction(()=>!document.querySelector('#map-save').disabled);
|
||
assert.equal(await page.locator('#map-settings-view').getAttribute('tabindex'),'-1');
|
||
// A delayed save must not allow edits that its response could silently overwrite.
|
||
let releaseSave,saveArrived,saveFinished;const saveGate=new Promise(r=>releaseSave=r),saveSeen=new Promise(r=>saveArrived=r),saveSent=new Promise(r=>saveFinished=r);
|
||
const holdSave=async route=>{if(route.request().method()!=='PUT'){await route.continue();return;}try{const response=await route.fetch();saveArrived();await saveGate;await route.fulfill({response});}finally{saveFinished();}};
|
||
await page.route('**/api/maps/preferences',holdSave);
|
||
try{await page.locator('#map-save').click();await saveSeen;assert.equal(await page.locator('#map-longitude').isDisabled(),true,'coordinates editable during pending save');assert.equal(await page.locator('[data-map-action=region-save]').isDisabled(),true,'region can be changed during pending save');const coordinate=await page.locator('#map-longitude').inputValue();await page.evaluate(()=>window.dispatchEvent(new CustomEvent('rid-map-point',{detail:{longitude:0,latitude:0,zoom:1}})));assert.equal(await page.locator('#map-longitude').inputValue(),coordinate,'late map event changed a pending save');}
|
||
finally{releaseSave();await saveSent;await page.unroute('**/api/maps/preferences',holdSave);}
|
||
await page.waitForFunction(()=>!document.querySelector('#map-save').disabled);
|
||
await page.waitForFunction(()=>window.ridMapSettings?.metrics()?.camera);
|
||
await page.locator('#map-tab-location').focus();await page.keyboard.press('ArrowRight');assert.equal(await page.locator('#map-tab-downloads').getAttribute('aria-selected'),'true');
|
||
await page.locator('#map-step-next').click();assert.match(await page.locator('#map-step-message').textContent(),/有效范围/);assert.equal(await page.locator('#map-step-region').isVisible(),true);
|
||
await page.keyboard.press('Home');await page.locator('#map-tab-location').click();
|
||
await page.locator('#map-location-panel [data-map-action=point]').click();await page.locator('#settings-map').click({position:{x:220,y:220}});assert.match(await page.locator('#map-save-message').textContent(),/起始点已选定/);
|
||
await page.locator('#map-longitude').fill('181');await page.locator('#map-save').click();assert.match(await page.locator('#map-save-message').textContent(),/有效经纬度/);
|
||
await page.locator('#map-longitude').fill('116.4');await page.locator('#map-latitude').fill('39.9');await page.locator('#map-zoom').fill('12');await page.locator('#map-basemap').selectOption('road');await page.locator('#map-save').click();await page.waitForFunction(()=>document.querySelector('#map-save-message').textContent.includes('已保存'));
|
||
assert.equal((await json('/api/maps/preferences')).value.longitude,116.4);
|
||
// Unsaved fields survive a settings navigation within this document.
|
||
await page.locator('#map-longitude').fill('116.41');await page.locator('.reference-rail [data-open=settings]').click();await page.locator('.reference-rail [data-open=maps]').click();assert.equal(await page.locator('#map-longitude').inputValue(),'116.41');await page.locator('#map-longitude').fill('116.4');
|
||
await page.locator('#map-basemap').selectOption('imagery');await page.locator('.reference-rail [data-open=settings]').click();await page.locator('.reference-rail [data-open=maps]').click();await page.waitForFunction(()=>window.ridMapSettings?.metrics()?.camera);assert.equal(await page.locator('#map-basemap').inputValue(),'imagery');assert.equal(await page.evaluate(()=>window.ridMapSettings.metrics().basemap),'imagery','unsaved basemap disagrees with preview after navigation');await page.locator('#map-basemap').selectOption('road');
|
||
await page.locator('#map-tab-downloads').click();await page.locator('[data-map-action=box]').click();const rect=await page.locator('#settings-map').boundingBox();await page.mouse.move(rect.x+100,rect.y+100);await page.mouse.down();await page.mouse.move(rect.x+260,rect.y+230,{steps:8});await page.mouse.up();assert.ok(Number(await page.locator('#map-west').inputValue())<Number(await page.locator('#map-east').inputValue()));
|
||
await page.locator('.map-advanced summary').click();
|
||
for(const [id,v]of Object.entries({'map-west':'120.15','map-south':'30.28','map-east':'120.16','map-north':'30.29'}))await page.locator('#'+id).fill(v);
|
||
await page.locator('#map-region-name').fill('验收常用区域');await page.locator('[data-map-action=region-save]').click();
|
||
await page.locator('#map-tab-location').click();await page.locator('#map-longitude').fill('117.5');await page.locator('#map-tab-downloads').click();
|
||
await page.locator('#map-region-persist').click();await page.waitForFunction(()=>document.querySelector('#map-region-persist').disabled && document.querySelector('#map-region-message').textContent.includes('已保存'));
|
||
assert.equal((await json('/api/maps/preferences')).value.longitude,116.4,'region save persisted location draft');
|
||
await page.locator('#map-region').selectOption('0');await page.locator('[data-map-action=region-delete]').click();assert.equal(await page.locator('#map-region option').count(),1);await page.locator('#map-region-persist').click();await page.waitForFunction(()=>document.querySelector('#map-region-persist').disabled);assert.equal((await json('/api/maps/preferences')).value.regions.length,0);
|
||
await page.locator('[data-map-action=region-save]').click();await page.locator('#map-region-persist').click();await page.waitForFunction(()=>document.querySelector('#map-region-persist').disabled);assert.equal((await json('/api/maps/preferences')).value.regions[0].name,'验收常用区域');
|
||
|
||
await page.locator('#map-tab-location').click();assert.equal(await page.locator('#map-longitude').inputValue(),'117.5');await page.locator('#map-longitude').fill('116.4');await page.locator('#map-tab-downloads').click();
|
||
await page.locator('#map-step-next').click();await page.locator('#map-min-zoom').fill('19');await page.locator('#map-step-next').click();assert.equal(await page.locator('#map-step-layers').isVisible(),true);assert.match(await page.locator('#map-step-message').textContent(),/0–18/);
|
||
await page.locator('#map-min-zoom').fill('11');await page.locator('#map-max-zoom').fill('11');
|
||
let starts=0;page.on('request',r=>{if(r.method()==='POST'&&new URL(r.url()).pathname==='/api/maps/downloads')starts++});
|
||
let failEstimate=true;await page.route('**/api/maps/downloads/estimate',route=>failEstimate?(failEstimate=false,route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'模拟核算失败'})})):route.continue());
|
||
await page.locator('#map-step-next').click();await page.waitForFunction(()=>document.querySelector('#map-step-message').textContent.includes('模拟核算失败'));assert.equal(await page.locator('#map-download-start').isDisabled(),true);
|
||
await page.locator('#map-estimate').click();await page.waitForFunction(()=>document.querySelector('#map-estimate-message').textContent.includes('共 4 张'));assert.equal(starts,0,'estimate started download');
|
||
await page.locator('#map-step-back').click();await page.locator('#map-max-zoom').fill('12');await page.locator('#map-max-zoom').fill('11');assert.equal(await page.locator('#map-download-start').isDisabled(),true,'changed draft kept old estimate');
|
||
await page.locator('#map-step-next').click();await page.waitForFunction(()=>!document.querySelector('#map-download-start').disabled);await page.unroute('**/api/maps/downloads/estimate');
|
||
await page.locator('#map-download-start').click();const done=await job('completed');assert.equal(done.done,4);assert.equal(done.failed,0);
|
||
for(const layer of ['vec_w','cva_w','img_w','cia_w'])assert.deepEqual(await readFile(path.join(root,`maps/offline/${layer}/11/${x}/${y}.png`)),png);
|
||
// UI state for an already-running task, including re-entry and explicit cancellation.
|
||
let uiRunning=true,cancelClicks=0;
|
||
await page.route('**/api/maps/downloads',route=>route.request().method()==='GET'?route.fulfill({contentType:'application/json',body:JSON.stringify({available:true,job:{state:uiRunning?'running':'cancelled',message:uiRunning?'测试任务下载中':'测试任务已取消',done:1,total:4}})}):route.continue());
|
||
await page.route('**/api/maps/downloads/cancel',route=>{cancelClicks++;uiRunning=false;return route.fulfill({contentType:'application/json',body:JSON.stringify({message:'已请求取消'})})});
|
||
await page.waitForFunction(()=>!document.querySelector('#map-download-cancel').hidden);
|
||
assert.equal(await page.locator('[data-map-action=step-region]').isDisabled(),true);assert.equal(await page.locator('#map-west').isDisabled(),true);
|
||
await page.locator('#map-tab-location').click();await page.locator('#map-tab-downloads').click();assert.equal(await page.locator('#map-step-review').isVisible(),true);
|
||
await page.locator('#map-download-cancel').click();await page.waitForFunction(()=>document.querySelector('#map-download-message').textContent.includes('测试任务已取消'));assert.equal(cancelClicks,1);
|
||
await page.unroute('**/api/maps/downloads');await page.unroute('**/api/maps/downloads/cancel');
|
||
|
||
// Offline files remain readable even after the online cache is no longer needed.
|
||
const tile=await fetch(base+`/api/maps/tile/vec_w/11/${x}/${y}`);assert.equal(tile.status,200);
|
||
const task={bounds:{west:120.15,south:30.28,east:120.16,north:30.29},minZoom:16,maxZoom:16,road:true,imagery:true};
|
||
assert.equal((await json('/api/maps/downloads','POST',task)).status,202);
|
||
assert.equal((await json('/api/maps/downloads','POST',task)).status,409);
|
||
await json('/api/maps/downloads/cancel','POST',{});await job('cancelled');
|
||
const failing={...task,bounds:{west:116.4,south:39.9,east:116.401,north:39.901},minZoom:11,maxZoom:11};await json('/api/maps/downloads','POST',failing);await job('failed');
|
||
assert.equal((await json('/api/maps/downloads/estimate','POST',{...task,minZoom:19})).status,400);
|
||
assert.equal((await fetch(base+'/api/maps/preferences',{headers:{origin:'https://foreign.invalid'}})).status,403);
|
||
// Real live renderer reads the persisted default; no telemetry is injected.
|
||
await page.goto(base+'/realtime');await page.waitForFunction(()=>window.ridMap?.metrics()?.mapReady);
|
||
const camera=await page.evaluate(()=>window.ridMap.metrics().camera);assert.ok(Math.abs(camera.center[0]-116.4)<.0001,JSON.stringify(camera));assert.ok(Math.abs(camera.center[1]-39.9)<.0001,JSON.stringify(camera));assert.equal(camera.zoom,12);
|
||
assert.equal(await page.evaluate(()=>window.ridMap.metrics().basemap),'road');
|
||
assert.equal((await json('/api/realtime/ingest','POST',[{target_id:'MAP-REVIEW-001',receiver_id:'MAP-REVIEW',source_epoch:1,sequence:1,longitude:120.1538,latitude:30.2874,altitude_m:120,heading_deg:0}])).status,200);await page.waitForFunction(()=>window.ridMap.metrics().targets>0);const populatedCamera=await page.evaluate(()=>window.ridMap.metrics().camera);assert.ok(Math.abs(populatedCamera.center[0]-116.4)<.0001,'initial telemetry replaced configured map center');
|
||
await page.getByRole('button',{name:'MAP-REVIEW-001',exact:true}).click();await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await page.waitForFunction(()=>{const c=window.ridMap.metrics().camera.center;return Math.abs(c[0]-120.1538)<.1&&Math.abs(c[1]-30.2874)<.1});
|
||
await page.locator('[data-open=settings]').first().click();await page.locator('.reference-rail [data-open=maps]').click();await page.waitForFunction(()=>!document.querySelector('#map-save').disabled);await page.waitForFunction(()=>window.ridMapSettings?.metrics()?.camera);
|
||
assert.equal(await page.locator('#map-region option').count(),2);await page.waitForFunction(()=>!document.querySelector('#map-network-note').textContent.includes('正在检查'));
|
||
await page.route('**/api/maps/status',route=>route.abort('connectionfailed'));await page.waitForFunction(()=>document.querySelector('#map-network-note').textContent.includes('无法连接本机地图服务'));await page.unroute('**/api/maps/status');await page.waitForFunction(()=>document.querySelector('#map-network-note').textContent.includes('密钥未配置'));
|
||
await page.locator('#map-tab-downloads').click();await page.locator('[data-map-action=step-region]').click();await page.locator('#map-region').selectOption('0');await page.locator('#map-step-next').click();await page.locator('#map-min-zoom').fill('11');await page.locator('#map-max-zoom').fill('11');await page.locator('#map-step-next').click();await page.waitForFunction(()=>!document.querySelector('#map-download-start').disabled);
|
||
await page.locator('#map-tab-location').click();
|
||
for(const [width,height]of [[1600,900],[1366,768],[900,700],[390,844],[1200,540]]){
|
||
await page.setViewportSize({width,height});
|
||
for(const tab of ['location','downloads']){
|
||
await page.locator('#map-tab-'+tab).click();
|
||
if(tab==='downloads')await page.locator('[data-map-action=step-review]').click();
|
||
const button=page.locator(tab==='location'?'#map-save':'#map-download-start');await button.scrollIntoViewIfNeeded();
|
||
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true,`${width} ${tab} overflow`);
|
||
if(tab==='location'&&width>=1366)assert.equal(await page.locator('#map-location-panel .map-settings-scroll').evaluate(e=>e.scrollHeight<=e.clientHeight+1),true,'common map settings still require scrolling');
|
||
const b=await button.boundingBox();assert.ok(b.x>=0&&b.x+b.width<=width+1&&b.y>=48&&b.y+b.height<=height+1,JSON.stringify({width,tab,b}));
|
||
await page.screenshot({path:path.resolve(`previews/map-settings-${tab}-${width}x${height}.png`)});
|
||
}
|
||
}
|
||
await page.setViewportSize({width:1366,height:768});await page.evaluate(()=>document.documentElement.style.zoom='2');await page.locator('#map-tab-location').click();await page.locator('#map-save').scrollIntoViewIfNeeded();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.evaluate(()=>document.documentElement.style.zoom='');
|
||
|
||
await page.setViewportSize({width:800,height:1000});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||
await stop();start();await ready();const reloaded=(await json('/api/maps/preferences')).value;assert.equal(reloaded.longitude,116.4);assert.equal(reloaded.regions[0].name,'验收常用区域');
|
||
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
|
||
report={status:'PASS',root,camera,download:done,scenarios:['A layout and C wizard with real MapLibre','step validation and estimate retry','region save preserves location draft','parameter edits invalidate estimate','five viewport sizes and 200percent zoom','pending save locks edits and ignores late map callbacks','invalid coordinates','default camera survives first telemetry','coordinates and unsaved basemap retained across navigation','saved region reload','actual Go sidecar and four-layer offline raster validation','download cancellation and single-job limit','unavailable tiles fail honestly','local service failure and automatic recovery','foreign origin rejection','800px width','no page errors or CSP violations']};console.log(JSON.stringify(report));
|
||
}catch(error){console.error('MAP TEST FAILED',root,error.stack);const page=browser?.contexts()[0]?.pages()[0];if(page)await page.screenshot({path:path.resolve('previews/map-settings-failure.png'),fullPage:true}).catch(()=>{});throw error;}finally{await browser?.close();await stop();await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));}
|
||
|
||
|