```
feat(geofences): 新增地理围栏模块并优化地图瓦片缓存 在 rid-shared 中实现二维 WGS84 地理围栏核心逻辑,支持圆形与多边形 两种几何体,包含坐标合法性校验、边界包含判断及自相交检测。 realtime-core 的 Store 新增观察者回调,在观测数据接受后按到达顺序 通知监听器。 前端方面,新增 geofence-map-adapter.js 提供基于 MapLibre 的围栏绘制 与编辑能力,配套 geofences.css 完成响应式布局样式。map-loader.js 增加懒加载入口,仅在实时工作区按需引入围栏地图模块。 同时引入 map-tile-buffer 瓦片缓冲机制,改善地图切换与刷新时的加载 体验;将默认缩放级别从 11 调整为 15,使初始视图更贴近实际监测场景。 ```
This commit is contained in:
@@ -136,7 +136,7 @@ func store(path string, data []byte) error {
|
||||
}
|
||||
return os.Rename(name, path)
|
||||
}
|
||||
func fetch(client *http.Client, r request, t tile) error {
|
||||
func fetch(client *http.Client, r request, t tile, limiter <-chan time.Time) error {
|
||||
path := filepath.Join(r.Output, t.layer, fmt.Sprint(t.z), fmt.Sprint(t.x), fmt.Sprintf("%d.png", t.y))
|
||||
if !safePath(path) {
|
||||
return fmt.Errorf("invalid output")
|
||||
@@ -146,6 +146,8 @@ func fetch(client *http.Client, r request, t tile) error {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// Valid local tiles do not consume network rate-limit slots.
|
||||
<-limiter
|
||||
resp, err := client.Get(fmt.Sprintf("%s/%s/%d/%d/%d", strings.TrimRight(r.BaseURL, "/"), t.layer, t.z, t.x, t.y))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -195,8 +197,7 @@ func run(input io.Reader, output io.Writer) error {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for t := range jobs {
|
||||
<-ticker.C
|
||||
err := fetch(client, r, t)
|
||||
err := fetch(client, r, t, ticker.C)
|
||||
mu.Lock()
|
||||
p.Done++
|
||||
if err != nil {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCoverageBoundaries(t *testing.T) {
|
||||
@@ -28,6 +29,28 @@ func TestCoverageBoundaries(t *testing.T) {
|
||||
t.Fatal("zoom accepted")
|
||||
}
|
||||
}
|
||||
func TestCachedTileDoesNotWaitForNetworkPermission(t *testing.T) {
|
||||
var b bytes.Buffer
|
||||
_ = png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 256, 256)))
|
||||
r := request{Output: t.TempDir()}
|
||||
item := tile{layer: "vec_w", x: 1, y: 2, z: 3}
|
||||
file := filepath.Join(r.Output, "vec_w", "3", "1", "2.png")
|
||||
if err := store(file, b.Bytes()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// An unfulfilled limiter would block forever if a cache hit consumed a network slot.
|
||||
limiter := make(chan time.Time)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- fetch(nil, r, item, limiter) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("valid offline tile waited for network rate limiter")
|
||||
}
|
||||
}
|
||||
func TestDownloadValidatesAndResumes(t *testing.T) {
|
||||
var imageBytes bytes.Buffer
|
||||
_ = png.Encode(&imageBytes, image.NewRGBA(image.Rect(0, 0, 256, 256)))
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ try {
|
||||
$ridInitialManifestJson = ConvertTo-Json -InputObject $ridInitialManifest -Depth 5 -Compress
|
||||
cargo xtask web
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Rust frontend build failed' }
|
||||
cargo build --release --locked
|
||||
cargo build --release --locked -p fpv-rid-registry
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Release build failed' }
|
||||
$ridMetadata = cargo metadata --locked --format-version 1 --no-deps | ConvertFrom-Json
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cargo metadata failed' }
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// 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 http from 'node:http';
|
||||
import net from 'node:net';
|
||||
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';
|
||||
const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const backend=probe.address().port;await new Promise(r=>probe.close(r));
|
||||
let base,child,browser,heartbeat,output='';const errors=[],csp=[],sockets=new Set();
|
||||
const proxy=http.createServer(async(req,res)=>{if(process.env.RID_SOURCE_ASSETS==='1'&&!req.url.startsWith('/api/')){const pathname=new URL(req.url,'http://localhost').pathname;const relative=pathname==='/'||pathname==='/realtime'?'index.html':pathname.slice(1);if(!relative.includes('..'))try{let bytes;try{bytes=await readFile(path.join('crates/web-ui/public',relative));}catch{bytes=await readFile(path.join('dist/web-ui',relative));}res.writeHead(200,{'content-type':relative.endsWith('.html')?'text/html':relative.endsWith('.css')?'text/css':relative.endsWith('.wasm')?'application/wasm':relative.endsWith('.svg')?'image/svg+xml':relative.endsWith('.png')?'image/png':'text/javascript'});res.end(bytes);return}catch{}}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:backend,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(backend,'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';const nl=String.fromCharCode(13,10);upstream.write(['GET '+req.url+' HTTP/1.1',...Object.entries(headers).map(([k,v])=>k+': '+v),'',''].join(nl));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)})});
|
||||
const wait=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,RID_TEST_PORT:String(backend),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{
|
||||
await new Promise(r=>proxy.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+proxy.address().port;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('园区 <script>安全名称</script>');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();for(const socket of sockets)socket.destroy();proxy.closeAllConnections();await new Promise(r=>proxy.close(r));await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output);}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Real MapLibre + HTTP cache regression; synthetic tiles, no external maps or receivers.
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile,writeFile,mkdtemp} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import {createRequire} from 'node:module';
|
||||
const {chromium}=createRequire(import.meta.url)('playwright');
|
||||
const root=await mkdtemp(path.join(tmpdir(),'RID-map-buffer-'));
|
||||
const source=await readFile('crates/web-ui/public/map-adapter.js','utf8');
|
||||
const baseline=source.replace(/import \{attachTileBuffer\} from '[^']+';/,'').replace(/tileBuffer=attachTileBuffer\([^;]+;/,'').replace("basemap=next;for(const", "basemap=next;tileRevision++;for(const");
|
||||
const tile=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==','base64');
|
||||
let hits=[],prefetchDelay=0;
|
||||
const server=http.createServer(async(req,res)=>{try{
|
||||
const u=new URL(req.url,'http://localhost');
|
||||
if(u.pathname.startsWith('/api/maps/tile/')){hits.push({url:req.url,prefetch:!!req.headers['x-rid-prefetch']});if(req.headers['x-rid-prefetch']&&prefetchDelay)await new Promise(r=>setTimeout(r,prefetchDelay));res.writeHead(200,{'content-type':'image/png','cache-control':'public,max-age=300'});res.end(tile);return;}
|
||||
let data,type='text/javascript';
|
||||
if(u.pathname==='/'){type='text/html';data=`<link rel="stylesheet" href="/vendor/maplibre-gl.css"><style>html,body,#map{margin:0;width:100%;height:100%;overflow:hidden}</style><div id="map"></div><script type="module">import '/map-adapter.js?mode=${u.searchParams.get('mode')}';window.ridMap.create('map','imagery',{longitude:120.1538,latitude:30.2874,zoom:15});setInterval(()=>window.testMap?.triggerRepaint(),30);</script>`;}
|
||||
else if(u.pathname==='/map-adapter.js')data=u.searchParams.get('mode')==='baseline'?baseline:source;
|
||||
else if(u.pathname==='/vendor/maplibre-gl.mjs')data="import * as real from './maplibre-real.mjs';export * from './maplibre-real.mjs';export class Map extends real.Map{constructor(p){super(p);window.testMap=this;}}";
|
||||
else {let file=u.pathname==='/vendor/maplibre-real.mjs'?'/vendor/maplibre-gl.mjs':u.pathname;if(!/^\/(vendor\/[a-zA-Z0-9.-]+|map-tile-buffer.js)$/.test(file)){res.writeHead(404);res.end();return;}data=await readFile('crates/web-ui/public'+file);if(file.endsWith('.css'))type='text/css';}
|
||||
res.writeHead(200,{'content-type':type});res.end(data);
|
||||
}catch(e){res.writeHead(500);res.end(String(e));}});
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;
|
||||
const browser=await chromium.launch({channel:'msedge',headless:true});const report={root};
|
||||
async function loaded(page){await page.waitForFunction(()=>window.testMap?.loaded()&&window.ridMap.metrics().mapReady);}
|
||||
async function warmed(page){await page.waitForTimeout(350);await page.waitForFunction(()=>{const b=window.ridMap.metrics().tileBuffer;return b&&b.requested>0&&b.queued===0&&b.running===0;},{},{timeout:60000});}
|
||||
try{
|
||||
for(const mode of ['baseline','buffer']){
|
||||
const context=await browser.newContext({viewport:{width:1200,height:800}});const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));hits=[];
|
||||
await page.goto(base+'/?mode='+mode);await loaded(page);if(mode==='buffer')await warmed(page);
|
||||
const initial=hits.length,initialTiles=[...hits];hits=[];
|
||||
await page.evaluate(()=>window.testMap.panBy([450,0],{duration:300}));await page.waitForFunction(()=>!window.testMap.isMoving()&&window.testMap.areTilesLoaded());
|
||||
const panVisible=hits.filter(h=>!h.prefetch).length;const panUrls=hits.filter(h=>!h.prefetch);
|
||||
if(mode==='buffer'){
|
||||
await warmed(page);const warm=await page.evaluate(()=>window.ridMap.metrics().tileBuffer);assert.ok(warm.requested>0);assert.ok(warm.running<=4);
|
||||
hits=[];await page.evaluate(()=>window.ridMap.setBasemap('road'));await loaded(page);const switchVisible=hits.filter(h=>!h.prefetch).length;
|
||||
const tiles=await page.evaluate(()=>window.ridMap.metrics().baseTiles);assert.ok(tiles.every(t=>!t.includes('?v=')));
|
||||
await warmed(page);hits=[];await page.evaluate(()=>window.testMap.setZoom(14));await loaded(page);await warmed(page);assert.ok(hits.some(h=>/\/15\//.test(h.url)));
|
||||
await page.evaluate(()=>window.ridMap.refresh());await loaded(page);assert.ok((await page.evaluate(()=>window.ridMap.metrics().baseTiles))[0].includes('?v=1'));
|
||||
// Leaving the warmed area legitimately needs new visible tiles.
|
||||
await warmed(page);hits=[];await page.evaluate(()=>window.testMap.panBy([4000,0],{duration:200}));await loaded(page);const outsideVisible=hits.filter(h=>!h.prefetch).length;assert.ok(outsideVisible>0);
|
||||
await warmed(page);prefetchDelay=120;
|
||||
await page.evaluate(()=>window.testMap.setZoom(13));await loaded(page);await page.waitForFunction(()=>window.ridMap.metrics().tileBuffer.running>0);
|
||||
await page.evaluate(()=>{window.testMap.panBy([600,0],{duration:200});window.testMap.setZoom(12);});await loaded(page);await warmed(page);
|
||||
const afterCancel=await page.evaluate(()=>window.ridMap.metrics().tileBuffer);assert.ok(afterCancel.cancelled>0);assert.ok(afterCancel.running<=4);prefetchDelay=0;
|
||||
// Browser offline panning inside a known warmed region sends no server requests.
|
||||
const cachedCenter=await page.evaluate(()=>window.testMap.getCenter().toArray());await context.setOffline(true);hits=[];
|
||||
await page.evaluate(c=>window.testMap.jumpTo({center:[c[0]+0.0001,c[1]]}),cachedCenter);await page.waitForFunction(()=>window.testMap.areTilesLoaded());assert.equal(hits.length,0);await page.screenshot({path:path.join(root,'offline-buffer.png')});await context.setOffline(false);
|
||||
report.extended={outsideVisible,cancelled:afterCancel.cancelled,offlineServerRequests:hits.length};
|
||||
await page.evaluate(()=>window.ridMap.destroy());
|
||||
report.buffer={initial,panVisible,panUrls,switchVisible,warm,initialLevels:[...new Set(initialTiles.map(t=>t.url.split('/')[5]))]};
|
||||
}else report.baseline={initial,panVisible};
|
||||
assert.deepEqual(errors,[]);await context.close();
|
||||
}
|
||||
assert.ok(report.buffer.panVisible<report.baseline.panVisible,JSON.stringify(report));assert.ok(report.buffer.panVisible<=2);assert.equal(report.buffer.switchVisible,0);
|
||||
report.status='PASS';console.log(JSON.stringify(report));
|
||||
}finally{await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await browser.close();server.closeAllConnections();await new Promise(r=>server.close(r));}
|
||||
@@ -0,0 +1,41 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
let serial=0;
|
||||
async function fixture(run){
|
||||
const names=['document','window','ResizeObserver','CustomEvent','testMapLibre'];const saved=new Map(names.map(k=>[k,globalThis[k]]));
|
||||
const emitted=[];let current;
|
||||
const canvas=()=>({handlers:{},addEventListener(k,f){this.handlers[k]=f},getBoundingClientRect(){return {left:0,top:0,width:800,height:500}},setPointerCapture(){},style:{},focus(){this.focused=true}});
|
||||
const root={appendChild(e){this.selection=e}};
|
||||
class FakeMap{
|
||||
constructor(p){current=this;this.options=p;this.handlers={};this.canvas=canvas();this.sources=structuredClone(p.style.sources);this.loadedStyle=false;this.container={clientWidth:800};}
|
||||
addControl(){}on(name,f){(this.handlers[name]??=[]).push(f)}getCanvasContainer(){return this.canvas}getCanvas(){return this.canvas}getContainer(){return this.container}
|
||||
getSource(k){if(!this.loadedStyle)return;return {setTiles:tiles=>this.sources[k].tiles=tiles}}
|
||||
load(){this.loadedStyle=true;for(const f of this.handlers.load??[])f()}
|
||||
dragPan={disable(){},enable(){}};unproject([x,y]){return {lng:x/100,lat:10-y/100}}remove(){}resize(){}
|
||||
}
|
||||
class Marker{setLngLat(){return this}addTo(){return this}}
|
||||
globalThis.testMapLibre={Map:FakeMap,Marker,NavigationControl:class{},AttributionControl:class{},setWorkerUrl(){}};
|
||||
globalThis.document={getElementById(){return root},createElement(){return {style:{},hidden:false}}};
|
||||
globalThis.window={dispatchEvent:e=>emitted.push(e)};globalThis.CustomEvent=class{constructor(type,p){this.type=type;this.detail=p.detail}};
|
||||
globalThis.ResizeObserver=class{observe(){}disconnect(){}};
|
||||
try{
|
||||
const source=(await readFile('crates/web-ui/public/map-settings-adapter.js','utf8')).replace(/import \{attachTileBuffer\} from '[^']+';/, 'const attachTileBuffer=()=>({destroy(){},schedule(){},metrics(){return {}}});').replace(/import \* as ml from '[^']+';/,'const ml=globalThis.testMapLibre;');
|
||||
const api=await import('data:text/javascript;base64,'+Buffer.from(source+`\n// test ${serial++}`).toString('base64'));
|
||||
api.open({basemap:'imagery',longitude:120.15,latitude:30.28,zoom:11});
|
||||
await run({api,map:()=>current,root,emitted});api.close();
|
||||
}finally{for(const k of names){if(saved.get(k)===undefined)delete globalThis[k];else globalThis[k]=saved.get(k)}}
|
||||
}
|
||||
test('basemap selected before style load is applied when ready',()=>fixture(({api,map})=>{
|
||||
api.setBasemap('road');map().load();assert.match(map().sources.base.tiles[0],/vec_w/);assert.match(map().sources.labels.tiles[0],/cva_w/);
|
||||
}));
|
||||
test('closing during selection cannot leak a rectangle into the next map',()=>fixture(({api,map,emitted})=>{
|
||||
api.tool('box');map().canvas.handlers.pointerdown({button:0,clientX:20,clientY:30,pointerId:1,preventDefault(){}});
|
||||
map().canvas.handlers.pointermove({clientX:160,clientY:170});api.close();api.open({basemap:'imagery',longitude:120,latitude:30,zoom:11});
|
||||
map().canvas.handlers.pointermove({clientX:200,clientY:210});map().canvas.handlers.pointerup();assert.equal(emitted.filter(e=>e.type==='rid-map-bounds').length,0);
|
||||
}));
|
||||
test('Escape is reachable after selecting a toolbar tool',()=>fixture(({api,map})=>{api.tool('point');assert.equal(map().canvas.focused,true);}));
|
||||
test('panning does not leave an obsolete screen rectangle over another area',()=>fixture(({api,map,root})=>{
|
||||
api.tool('box');map().canvas.handlers.pointerdown({button:0,clientX:20,clientY:30,pointerId:1,preventDefault(){}});map().canvas.handlers.pointermove({clientX:160,clientY:170});map().canvas.handlers.pointerup();
|
||||
for(const f of map().handlers.movestart??[])f();assert.equal(root.selection.hidden,true);
|
||||
}));
|
||||
@@ -6,28 +6,50 @@ import path from 'node:path';
|
||||
import {spawn} from 'node:child_process';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createRequire} from 'node:module';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
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 base='http://127.0.0.1:8787';
|
||||
try{await fetch(base,{signal:AbortSignal.timeout(800)});throw Error('8787 is occupied; existing service preserved');}catch(e){if(e.message.includes('occupied'))throw e;}
|
||||
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 backendPort=await new Promise((resolve,reject)=>{const socket=net.createServer();socket.on('error',reject);socket.listen(0,'127.0.0.1',()=>{const port=socket.address().port;socket.close(()=>resolve(port));});});
|
||||
let base;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)});});
|
||||
const env={...process.env,RID_TEST_PORT:String(backendPort),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],{env,windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);}
|
||||
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{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{
|
||||
await new Promise((resolve,reject)=>{proxy.on('error',reject);proxy.listen(0,'127.0.0.1',()=>{base='http://127.0.0.1:'+proxy.address().port;resolve();})});
|
||||
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());});
|
||||
await page.goto(base);await page.locator('#home-app-settings').click();await page.locator('#appearance-view [data-open=maps]').click();await page.locator('#map-save').waitFor();await page.waitForFunction(()=>!document.querySelector('#map-save').disabled);
|
||||
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('#appearance-view [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('#appearance-view [data-open=maps]').click();await loadSeen;await page.locator('#map-settings-view [data-open=settings]').click();await page.locator('#appearance-view [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-settings-drawer [data-map-action=drawer]').click();assert.equal(await page.locator('#map-settings-drawer').isHidden(),true);await page.locator('.map-settings-head [data-map-action=drawer]').click();
|
||||
await page.locator('.map-settings-head [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(),/起始点已选定/);
|
||||
@@ -36,6 +58,8 @@ try{
|
||||
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('#map-settings-view [data-open=settings]').click();await page.locator('#appearance-view [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('#map-settings-view [data-open=settings]').click();await page.locator('#appearance-view [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-settings-head [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()));
|
||||
for(const [id,v]of Object.entries({'map-west':'120.15','map-south':'30.28','map-east':'120.16','map-north':'30.29','map-min-zoom':'11','map-max-zoom':'11'}))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-save').click();await page.waitForFunction(()=>document.querySelector('#map-save-message').textContent.includes('已保存'));
|
||||
await page.locator('#map-estimate').click();await page.waitForFunction(()=>document.querySelector('#map-estimate-message').textContent.includes('共 4 张'));
|
||||
@@ -54,10 +78,14 @@ try{
|
||||
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('#appearance-view [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.screenshot({path:path.resolve('previews/map-settings-live-C-20261023.png')});
|
||||
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.screenshot({path:path.resolve('previews/map-settings-live-C-20261023.png')});
|
||||
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:['actual C drawer and MapLibre point selection','invalid coordinates','persistent default camera','draft 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','foreign origin rejection','800px width','no page errors or CSP violations']};console.log(JSON.stringify(report));
|
||||
}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));}
|
||||
report={status:'PASS',root,camera,download:done,scenarios:['actual C drawer and MapLibre point selection','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));
|
||||
}finally{await browser?.close();await stop();for(const socket of sockets)socket.destroy();proxy.closeAllConnections();await new Promise(r=>proxy.close(r));await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// Real SQLite and server monitor, without a browser or physical receiver.
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdtemp,writeFile} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import path from 'node:path';
|
||||
import net from 'node:net';
|
||||
import {spawn} from 'node:child_process';
|
||||
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
|
||||
const root=await mkdtemp(path.join(tmpdir(),'RID-monitoring-'));
|
||||
const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const port=probe.address().port;await new Promise(r=>probe.close(r));const base='http://127.0.0.1:'+port;
|
||||
let child,output='',seq=0;const delay=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,RID_TEST_PORT:String(port)},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);}
|
||||
async function stop(){if(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++){try{if((await fetch(base+'/api/geofences')).ok)return}catch{}await delay(100)}throw Error(output);}
|
||||
async function json(url,method='GET',body){const r=await fetch(base+url,{method,headers:body?{'content-type':'application/json'}:{},body:body?JSON.stringify(body):undefined});assert.equal(r.status,200,await r.clone().text());return r.json();}
|
||||
async function list(kind){const s=await json('/api/target-lists');return json('/api/target-lists/DRONE-A','PUT',{list_kind:kind,note:'测试',expected_revision:s.revision});}
|
||||
async function ingest(lon=120.0){return json('/api/realtime/ingest','POST',[{target_id:'DRONE-A',receiver_id:'TEST',source_epoch:1,sequence:++seq,longitude:lon,latitude:30.0,altitude_m:100,heading_deg:30}]);}
|
||||
async function events(){return (await json('/api/monitoring/events?limit=200')).entries;}
|
||||
async function count(expected){for(let i=0;i<80;i++){const es=await events();if(es.length===expected)return es;await delay(50)}throw Error('event count '+JSON.stringify(await events()));}
|
||||
let report={root,exe};
|
||||
try{
|
||||
start();await ready();assert.equal((await json('/api/maps/preferences')).zoom,15);
|
||||
let fences=await json('/api/geofences');assert.equal(fences.entries.length,0);
|
||||
const fence={id:'TEST-FENCE',name:'隔离验收区域',enabled:true,geometry:{type:'circle',center:[120,30],radius_m:500}};
|
||||
fences=await json('/api/geofences/TEST-FENCE','PUT',{fence,expected_revision:0});assert.equal(fences.revision,1);
|
||||
assert.equal((await fetch(base+'/api/geofences/TEST-FENCE',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({fence,expected_revision:0})})).status,400);
|
||||
const bad={...fence,geometry:{type:'polygon',vertices:[[0,0],[1,1],[0,1],[1,0]]}};
|
||||
assert.equal((await fetch(base+'/api/geofences/TEST-FENCE',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({fence:bad,expected_revision:1})})).status,400);
|
||||
await list('white');await ingest();await delay(400);await count(0);
|
||||
await list('black');let es=await count(2);assert.deepEqual(new Set(es.map(e=>e.event_type)),new Set(['blacklist','geofence_enter']));
|
||||
for(let i=0;i<6;i++)await ingest();await delay(400);await count(2);
|
||||
// Multiple accepted crossings faster than the monitor interval must not be coalesced away.
|
||||
await ingest(121);await ingest(120);await ingest(121);await ingest(120);es=await count(4);
|
||||
assert.equal((await json('/api/monitoring/events?type=blacklist&target_id=DRONE-A')).entries.length,1);
|
||||
assert.equal((await json('/api/monitoring/events?fence_id=TEST-FENCE&limit=2')).entries.length,2);
|
||||
const page1=(await json('/api/monitoring/events?limit=2')).entries;const page2=(await json('/api/monitoring/events?limit=2&before='+page1.at(-1).id)).entries;assert.equal(new Set([...page1,...page2].map(e=>e.id)).size,4);
|
||||
assert.equal((await fetch(base+'/api/monitoring/events',{headers:{origin:'https://foreign.invalid'}})).status,403);
|
||||
await stop();start();await ready();await ingest();await delay(400);assert.equal((await events()).length,4);assert.equal((await json('/api/geofences')).entries[0].name,fence.name);
|
||||
const h=await json('/api/monitoring/status');assert.deepEqual(h,{droppedObservations:0,error:null});
|
||||
await list('white');await delay(400);await list('black');await count(6);
|
||||
await json('/api/geofences/TEST-FENCE?revision=1','DELETE');await ingest(121);await ingest(120);await delay(400);await count(6);
|
||||
report={...report,status:'PASS',events:(await events()).length,health:h,checks:['default zoom15','versioned CRUD','invalid geometry rejected','white exemption','blacklist + fence enter','dedup frames','rapid crossings','filter and cursor pagination','foreign origin rejected','restart durable history and dedup','list transitions','deleted fence silent','no browser required']};console.log(JSON.stringify(report));
|
||||
}finally{await stop();await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output);}
|
||||
@@ -0,0 +1,44 @@
|
||||
// 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 http from 'node:http';
|
||||
import net from 'node:net';
|
||||
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-menu-status-'));
|
||||
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
|
||||
const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const backend=probe.address().port;await new Promise(r=>probe.close(r));
|
||||
let base,child,browser,output='';const errors=[],csp=[],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:backend,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(backend,'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';const nl=String.fromCharCode(13,10);upstream.write(['GET '+req.url+' HTTP/1.1',...Object.entries(headers).map(([k,v])=>k+': '+v),'',''].join(nl));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)})});
|
||||
const wait=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,RID_TEST_PORT:String(backend),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{
|
||||
await new Promise(r=>proxy.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+proxy.address().port;start();await ready();
|
||||
for(const asset of ['workspace-native.css','index.html']){const response=await fetch(base+'/'+(asset==='index.html'?'realtime':asset));assert.equal(await response.text(),await readFile(path.join('dist/web-ui',asset),'utf8'));}
|
||||
await save('MENU-BLACK','black');await save('MENU-WHITE','white');const before=await snapshot();
|
||||
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())});
|
||||
await page.goto(base+'/realtime');await page.waitForFunction(()=>document.querySelector('.rt-status')?.textContent.includes('已连接'));await page.waitForFunction(()=>!document.querySelector('#rt-list-manager-from-directory')?.disabled);await wait(300);
|
||||
const nav=page.getByRole('navigation',{name:'主菜单'});assert.equal(await nav.locator('button:visible').count(),1);assert.equal(await nav.locator('button:visible').getAttribute('aria-label'),'黑名单管理');
|
||||
for(const name of ['应用首页','应用总览','设备登记','实时目标工作台','壁纸与外观'])assert.equal(await nav.getByRole('button',{name,exact:true}).isVisible(),false);
|
||||
await page.getByRole('button',{name:'黑名单管理',exact:true}).click();await page.locator('#rt-list-manager').waitFor();await page.getByRole('heading',{name:'黑名单管理',exact:true}).waitFor();
|
||||
const managerTabs=page.getByRole('group',{name:'管理名单分类'});assert.equal(await managerTabs.getByRole('button',{name:/^黑名单/}).getAttribute('aria-pressed'),'true');await page.locator('.rt-list-row[data-target-id="MENU-BLACK"]').waitFor();assert.equal(await page.locator('.rt-list-row[data-target-id="MENU-WHITE"]').count(),0);assert.equal(await page.locator('#rt-list-entry-kind').inputValue(),'black');
|
||||
await page.keyboard.press('Escape');await page.locator('#rt-list-manager').waitFor({state:'hidden'});await page.waitForFunction(()=>document.activeElement.id==='rt-blacklist-menu');assert.equal(await page.locator('#rt-blacklist-menu').getAttribute('aria-expanded'),'false');
|
||||
await page.getByRole('button',{name:'黑名单管理',exact:true}).press('Enter');await page.locator('#rt-list-manager').waitFor();await page.getByRole('button',{name:'关闭名单管理'}).click();await page.locator('#rt-list-manager').waitFor({state:'hidden'});
|
||||
async function corner(){const result=await page.evaluate(()=>{const root=document.getElementById('rt-layout'),e=root.querySelector('.mc-map-infobar'),r=root.getBoundingClientRect(),b=e.getBoundingClientRect(),scale=r.width/root.clientWidth;return {right:(r.right-b.right)/scale,bottom:(r.bottom-b.bottom)/scale,z:Number(getComputedStyle(e).zIndex),pointer:getComputedStyle(e).pointerEvents,rootOverflow:document.documentElement.scrollWidth>innerWidth}});assert.ok(Math.abs(result.right-16)<1,JSON.stringify(result));assert.ok(Math.abs(result.bottom-16)<1,JSON.stringify(result));assert.ok(result.z>10);assert.equal(result.pointer,'none');assert.equal(result.rootOverflow,false);return result;}
|
||||
await corner();await page.getByRole('button',{name:'隐藏事件面板',exact:true}).click();await page.locator('#rt-dock-restore').waitFor();await corner();await page.getByRole('button',{name:'收起目标目录',exact:true}).click();await page.getByRole('button',{name:'收起详情',exact:true}).click();await corner();await page.screenshot({path:path.join(root,'desktop-collapsed.png')});
|
||||
await page.locator('#rt-dock-restore').click();await page.locator('#rt-dock').waitFor();await corner();const overDock=await page.evaluate(()=>{const info=document.querySelector('.mc-map-infobar').getBoundingClientRect(),dock=document.querySelector('#rt-dock').getBoundingClientRect();return info.left>=dock.left&&info.right<=dock.right&&info.top>=dock.top&&info.bottom<=dock.bottom});assert.ok(overDock,'Status must overlay the dock rather than avoiding it');
|
||||
await page.getByRole('button',{name:'隐藏事件面板',exact:true}).click();await page.locator('#rt-dock-restore').waitFor();await page.locator('#toggle-menu').click();await corner();assert.equal(await nav.isVisible(),false);await page.locator('#toggle-menu').click();assert.equal(await nav.locator('button:visible').count(),1);
|
||||
const frames=[];for(const[width,height]of [[1600,1000],[1280,720],[390,844],[360,740]]){await page.setViewportSize({width,height});await wait(300);frames.push({width,height,...await corner()});assert.equal(await nav.locator('button:visible').count(),1);await page.screenshot({path:path.join(root,`menu-status-${width}.png`)});}
|
||||
await page.setViewportSize({width:1600,height:1000});await wait(300);await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('body[data-screen=home]').waitFor();assert.equal(await page.locator('#rt-blacklist-menu').isVisible(),false);await page.locator('#home-app-register').click();await page.locator('body[data-screen=register]').waitFor();assert.equal(await page.locator('.reference-rail [data-open=register]').isVisible(),true);assert.equal(await page.locator('#rt-blacklist-menu').isVisible(),false);
|
||||
await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-realtime').click();await page.waitForFunction(()=>document.querySelector('.rt-status')?.textContent.includes('已连接'));assert.equal(await nav.locator('button:visible').count(),1);await corner();
|
||||
assert.deepEqual(await snapshot(),before);assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);report={status:'PASS',root,exe,frames,checks:['one-blacklist-menu','blacklist-filter-and-default-kind','keyboard-open-and-return-focus','fixed-bottom-right-dock-and-panels','overlays-dock','menu-collapse','four-window-sizes','other-app-navigation-preserved','list-data-unchanged'],errors,csp};console.log(JSON.stringify(report));
|
||||
}finally{if(browser){if(report.status!=='PASS'){const p=browser.contexts()[0]?.pages()[0];if(p){await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});console.log(JSON.stringify({root,errors,csp,diagnostic:await p.evaluate(()=>({screen:document.body.dataset.screen,menu:[...document.querySelectorAll('.reference-rail button')].map(e=>({id:e.id,label:e.getAttribute('aria-label'),height:e.getBoundingClientRect().height})),manager:document.getElementById('rt-list-manager')?.hidden})).catch(()=>null)}));}}await browser.close();}if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}for(const socket of sockets)socket.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output);}
|
||||
@@ -45,6 +45,7 @@ try{
|
||||
await page.getByRole('button',{name:'加入黑名单',exact:true}).click();
|
||||
await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'black');
|
||||
await page.locator('.rt-detail-classification').getByRole('button',{name:'加入黑名单',exact:true}).click();await wait(350);
|
||||
await page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-WHITE'}).waitFor();
|
||||
assert.equal(await page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-WHITE'}).count(),1);
|
||||
await page.getByRole('button',{name:'管理黑白名单',exact:true}).click();await page.locator('#rt-list-manager').waitFor();assert.equal((await page.locator('#rt-list-manager').innerText()).includes('rows.get'),false);assert.equal(await page.locator('.rt-list-pagination').getByRole('button',{name:'下一页',exact:true}).isDisabled(),true);
|
||||
await page.locator('#rt-list-entry-id').fill('OFFLINE_002');await page.locator('#rt-list-entry-kind').selectOption('white');await page.locator('#rt-list-entry-note').fill('离线条目');await page.locator('#rt-list-entry-form .primary').click();
|
||||
@@ -95,4 +96,4 @@ try{
|
||||
assert.equal(await page.locator('.mc-map-toolstrip').count(),0);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);
|
||||
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
|
||||
report={status:'PASS',root,exe,geometry,errors,csp,revision:persisted.revision,entries:persisted.entries.length,checks:['exact persisted membership independent of registration','online quick marking and offline entry','map and directory filtering without telemetry loss','black alert deduplication','safe notes and reactive remote updates','cross-browser sync preserves unsaved draft','optimistic concurrency and failed save rollback','busy controls and ID validation','removal restores unclassified','four viewports and 200% zoom','escape return focus','restart persistence','failed initial load and stale snapshot recovery','topdown map and removed toolbar preserved']};console.log(JSON.stringify(report));
|
||||
}catch(error){console.log('FAILED ROOT',root,error.stack);if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});}throw error;}finally{clearInterval(heartbeat);if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output)}
|
||||
}catch(error){console.log('FAILED ROOT',root,error.stack,JSON.stringify({errors,csp}));if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)console.log('MAP',await p.evaluate(()=>window.ridMap?.metrics()).catch(()=>null));}if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});}throw error;}finally{clearInterval(heartbeat);if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output)}
|
||||
|
||||
Reference in New Issue
Block a user