Files
NODEDC_MISSION_CORE/apps/control-station/test/routers.test.mjs
T
DCCONSTRUCTIONS a49fb00b8e feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements
Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
2026-11-11 23:53:46 +03:00

138 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
let signalLevel,trafficSegments,trafficArea,trafficCeiling,smoothTrafficSegment;
let server,routerFresh,routerLabel,metric,collectTraffic,trafficPath,trafficRate,signalFraction,modemLabel;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});({routerFresh,routerLabel,metric}=await server.ssrLoadModule('../../packages/router-ui/src/contracts.ts'));({signalLevel,trafficSegments,trafficArea,trafficCeiling,smoothTrafficSegment,collectTraffic,trafficPath,trafficRate,signalFraction,modemLabel}=await server.ssrLoadModule('../../packages/router-ui/src/overview.ts'));});
after(async()=>{await server?.close();});
test('fresh board heartbeat cannot revive stale radio data',()=>{
const state={available:true,fresh:true},device={state:'ready',observed_at:100};
assert.equal(routerFresh(state,device,110000),true);
assert.equal(routerFresh(state,device,141000),false);
assert.equal(routerLabel(state,device,141000),'Нет свежих данных');
assert.equal(routerFresh({...state,fresh:false},device,110000),false);
});
test('missing radio sample is not displayed as zero or antenna health',()=>{
assert.equal(metric(null,'dB'),'Нет сведений');
assert.equal(metric(0,'dB'),'0 dB');
assert.equal(metric(-113,'dBm'),'-113 dBm');
});
test('overview distinguishes absent SIM, unavailable observations and missing measurements',()=>{
assert.equal(modemLabel({radio:'NOSIM'},true),'SIM не установлена');
assert.equal(modemLabel({radio:'NOSIM'},false),'Нет свежих данных');
assert.equal(modemLabel(undefined,true),'Нет сведений');
assert.equal(signalFraction(null),null);
assert.equal(trafficRate(null),'—');
assert.equal(trafficRate(0),'0 кбит/с');
assert.equal(trafficRate(1500),'1,5 Мбит/с');
});
test('live graph deduplicates repeated snapshots and never invents zero traffic on loss',()=>{
const device={observed_at:100,down_kbps:20,up_kbps:null};
const first=collectTraffic({key:'',day:0,points:[]},'a',device,true,100);
assert.deepEqual(first.points,[{at:100,down:20,up:null}]);
assert.equal(collectTraffic(first,'a',device,true,103).points.length,1);
assert.equal(collectTraffic(first,'a',{...device,observed_at:110},false,110).points.length,1);
assert.deepEqual(collectTraffic(first,'a',device,false,401).points,[]);
assert.deepEqual(collectTraffic(first,'new-runtime',device,false,110).points,[]);
assert.deepEqual(collectTraffic(first,'a',device,false,86401).points,[]);
});
test('traffic lines retain gaps and keep missing upload separate from recorded download',()=>{
const p=[{at:100,down:20,up:2},{at:110,down:21,up:null},{at:120,down:22,up:3},{at:200,down:23,up:4}];
assert.equal((trafficPath(p,'down',0,200,30).match(/M/g)||[]).length,2);
assert.equal((trafficPath(p,'up',0,200,30).match(/M/g)||[]).length,3);
assert.equal(trafficPath([{at:100,down:null,up:null}],'down',0,200,30),'');
});
test('overview renders three slots without implying internet or traffic from unknown samples',async()=>{
const {RouterOverview}=await server.ssrLoadModule('../../packages/router-ui/src/RouterOverview.tsx');
const device={active_mode:'direct',active_wan:'wan1',internet:'unknown',address:'192.168.100.1',modems:[{slot:1,operator:'Test carrier',radio:'OK',connectivity:'online',rsrp:-96,technology:'lte',band:'B40',down_kbps:null,up_kbps:null},{slot:2,radio:'NOSIM'}],down_kbps:null,up_kbps:null};
const html=renderToStaticMarkup(createElement(RouterOverview,{device,ready:true,points:[{at:100,down:null,up:null},{at:110,down:null,up:null}]}));
for(const slot of [1,2,3])assert.ok(html.includes(`<h2>Канал ${slot} (M${slot})</h2>`));
assert.match(html,/Интернет не подтверждён/);
assert.match(html,/SIM не установлена/);
assert.match(html,/Нет сведений/);
assert.match(html,/Скорость пока не получена от роутера/);
assert.doesNotMatch(html,/0 кбит\/с/);
});
test('router controls require fresh capable Node and block concurrent operations',async()=>{
const {controlEnabled,availableSlots,controlMessage}=await server.ssrLoadModule('../../packages/router-ui/src/control.ts');
const d={id:'router-test',state:'ready',modems:[{slot:1,radio:'OK',ip:'10.0.0.1'},{slot:2,radio:'NOSIM',ip:''}]};
const s={control_version:1,runtime_id:'runtime',results:[]};
assert.equal(controlEnabled(s,d,true),true);
assert.equal(controlEnabled({...s,control_version:0},d,true),false);
assert.equal(controlEnabled(s,d,false),false);
assert.equal(controlEnabled({...s,results:[{state:'applying'}]},d,true),false);
assert.deepEqual(availableSlots(d),[1]);
assert.match(controlMessage({state:'unknown'}),/не подтверждён/);
assert.match(controlMessage({state:'complete',action:'reboot'}),/Перезагрузка подтверждена/);
});
test('control surface uses shared controls and does not claim support on old Node',async()=>{
const {RouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/RouterControls.tsx');
const html=renderToStaticMarkup(createElement(RouterControls,{device:{id:'router-test',state:'ready',modems:[],active_mode:'direct'},value:{results:[]},transport:{},ready:true}));
assert.match(html,/требуется обновление Mission Core/);
assert.match(html,/Перезагрузить роутер/);
assert.match(html,/disabled/);
});
test('Client API overview preserves explicit M3 mapping and model name',async()=>{
const {RouterOverview}=await server.ssrLoadModule('../../packages/router-ui/src/RouterOverview.tsx');
const {modeLabel}=await server.ssrLoadModule('../../packages/router-ui/src/contracts.ts');
const device={model_id:'bananapi.bpi-r4-pro',model_name:'Banana Pi BPI-R4 Pro (8X)',slot_map:[{sim:1,slot:2,position:'right'},{sim:2,slot:3,position:'center'},{sim:3,slot:1,position:'left'}],client_api:{},active_mode:'direct',active_wan:'wwan',active_slots:[3],internet:'unknown',address:'192.168.1.1',modems:[{slot:3,operator:'Test carrier',radio:'enabled',connectivity:'online'}]};
const html=renderToStaticMarkup(createElement(RouterOverview,{device,ready:true,points:[]}));
assert.match(html,/<strong>Banana Pi BPI-R4 Pro \(8X\)<\/strong>/);
assert.match(html,/<strong>SIM2<\/strong>/);
assert.equal(modeLabel('whitelist'),'Белый список (whitelist)');
});
test('physical SIM labels are a profile projection, never array order or model-name inference',async()=>{
const {simChannels,simLabel,routerName,visibleRouters}=await server.ssrLoadModule('../../packages/router-ui/src/contracts.ts');
const device={family:'DexaFlow',model_name:'Banana Pi BPI-R4 Pro (8X)',slot_map:[{slot:1,sim:3,position:'left'},{slot:2,sim:1,position:'right'},{slot:3,sim:2,position:'center'}]};
assert.deepEqual(simChannels(device).map(x=>x.slot),[2,3,1]);assert.equal(simLabel(device,2),'SIM1');
assert.equal(simChannels({...device,slot_map:null})[0].label,'Канал 1');
assert.equal(routerName({...device,name:'My uplink'}),'My uplink');
const connected={id:'a',attached:true,state:'ready'},saved={id:'b',attached:false,state:'unreachable'};
assert.deepEqual(visibleRouters([saved,connected]),[connected]);
});
test('Client API controls sort physical SIMs and preserve wire identifiers',async()=>{
const {ClientRouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/ClientRouterControls.tsx');
const d={id:'x',state:'ready',active_mode:'direct',modems:[],slot_map:[{sim:1,slot:2,position:'right'},{sim:2,slot:3,position:'center'},{sim:3,slot:1,position:'left'}],client_api:{boot_id:'boot',revision:'r',rights:['policy','recovery'],policy:{mode:'direct',preferred_sim:'M2',fail_seconds:60,recover_seconds:60,min_vpn_seconds:120},checks:[]}};
const html=renderToStaticMarkup(createElement(ClientRouterControls,{device:d,value:{control_version:1,runtime_id:'r',results:[]},transport:{},ready:true}));
assert.match(html,/SIM1 \(M\.2 · right\)/);assert.doesNotMatch(html,/SIM M2/);
});
test('signal bands have deterministic boundaries and no quality estimate for missing values',()=>{
for(const [value,level] of [[-120,0],[-100.01,0],[-100,1],[-90.01,1],[-90,2],[-89,2],[-80.01,2],[-80,3],[-60,3]])assert.equal(signalLevel(value),level);
for(const value of [null,undefined,NaN,Infinity])assert.equal(signalLevel(value),null);
});
test('smooth traffic curves preserve all sample endpoints and stay within each measured range',()=>{
for(const values of [[0,0,0,0],[0,70,1,68,0],[2,3,60,61,70],[70,69,8,7,0]]){
const points=values.map((y,i)=>({x:[0,1,10,11,300][i],y}));
const path=smoothTrafficSegment(points),segments=[...path.matchAll(/C([\d.-]+),([\d.-]+) ([\d.-]+),([\d.-]+) ([\d.-]+),([\d.-]+)/g)];
assert.equal(segments.length,points.length-1);
segments.forEach((m,i)=>{
const [x1,y1,x2,y2,x,y]=m.slice(1).map(Number),a=points[i],b=points[i+1];
assert.equal(x,b.x);assert.equal(y,b.y);assert.ok(x1>=a.x&&x2<=b.x);
for(let step=0;step<=100;step++){
const t=step/100,u=1-t,sampled=u*u*u*a.y+3*u*u*t*y1+3*u*t*t*y2+t*t*t*y;
assert.ok(sampled>=Math.min(a.y,b.y)-.01&&sampled<=Math.max(a.y,b.y)+.01,`${sampled} outside measured interval`);
}
});
}
});
test('traffic fill preserves missing samples and pauses, including real zero traffic',()=>{
const points=[{at:100,down:0,up:null},{at:110,down:0,up:null},{at:120,down:null,up:3},{at:130,down:5,up:4},{at:170,down:2,up:5},{at:180,down:3,up:6}];
assert.deepEqual(trafficSegments(points,'down',0,180,10).map(s=>s.length),[2,1,2]);
assert.equal((trafficArea(points,'down',0,180,10).match(/Z/g)||[]).length,2);
assert.equal(trafficSegments(points,'down',0,180,10)[0][0].y,78);
assert.equal(trafficCeiling(points),10);assert.equal(trafficCeiling([]),1);
});
test('signal scale exposes four keyboard targets, an honest current level and no editable slider',async()=>{
const {RouterSignal}=await server.ssrLoadModule('../../packages/router-ui/src/RouterSignal.tsx');
const html=renderToStaticMarkup(createElement(RouterSignal,{rsrp:-89}));
assert.equal((html.match(/tabindex="0"/g)||[]).length,4);assert.match(html,/Хороший сигнал · RSRP -89 dBm/);
assert.equal((html.match(/class="router-signal-marker"/g)||[]).length,1);assert.doesNotMatch(html,/role="slider"/);
const missing=renderToStaticMarkup(createElement(RouterSignal,{rsrp:null}));
assert.doesNotMatch(missing,/class="router-signal-marker"/);assert.match(missing,/Уровень сигнала неизвестен/);
});