Files

211 lines
17 KiB
JavaScript
Raw Permalink 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',observed_at:100},saved={id:'b',attached:false,state:'unreachable',observed_at:100};
assert.deepEqual(visibleRouters({available:true,items:[saved,connected]},110000),[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,/Уровень сигнала неизвестен/);
});
test('reopened controls retain the policy refusal above timers, despite newer inspections',async()=>{
const {ClientRouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/ClientRouterControls.tsx');
const d={id:'x',state:'ready',active_mode:'direct',modems:[],client_api:{boot_id:'boot',revision:'r',rights:['policy','recovery'],policy:{mode:'aggregation',fail_seconds:60,recover_seconds:60,min_vpn_seconds:120},checks:[]}};
const results=[{operation_id:'inspect',device_id:'x',action:'inspect',state:'complete',at:102},{operation_id:'policy',device_id:'x',action:'policy',state:'error',error:'router_busy',at:101}];
const render=()=>renderToStaticMarkup(createElement(ClientRouterControls,{device:d,value:{control_version:1,runtime_id:'r',results},transport:{},ready:true}));
for(const html of [render(),render()]){
assert.match(html,/busy/);assert.match(html,/Сохранённый режим/);assert.doesNotMatch(html,/Не применён|Политика сохранена и применена/);
assert.ok(html.indexOf('(busy)')<html.indexOf('Ожидание отказа, с'));
assert.ok(html.indexOf('(busy)')<html.indexOf('Восстановление соединения'));
}
});
test('policy progress follows receipts and never turns missing or fallback routes into success',async()=>{
const {policyFeedback}=await server.ssrLoadModule('../../packages/router-ui/src/control.ts');
const device={selected_mode:'aggregation',active_mode:'aggregation',modems:[],client_api:{policy:{mode:'aggregation'},details:{pending:false}}};
const receipt={operation_id:'one',device_id:'x',action:'policy',state:'queued'};
assert.match(policyFeedback(device,true,receipt).label,/Команда отправлена/);
assert.equal(policyFeedback(device,true,receipt).busy,true);
assert.match(policyFeedback(device,true,{...receipt,state:'applying'}).label,/Применяются/);
assert.equal(policyFeedback(device,true,{...receipt,state:'complete'}).tone,'success');
assert.match(policyFeedback(device,true,{...receipt,state:'complete'}).message,/Агрегация/);
for(const state of ['error','unknown']){
const result=policyFeedback(device,true,{...receipt,state,error:'router_busy'});
assert.equal(result.busy,false);assert.equal(result.tone,'warning');
}
const offline=policyFeedback(device,false,{...receipt,state:'applying'});
assert.equal(offline.busy,false);assert.match(offline.label,/Нет свежих данных/);
const fallback={...device,active_mode:'direct',active_slots:[1],client_api:{...device.client_api,details:{fallback:true}}};
assert.equal(policyFeedback(fallback,true,{...receipt,state:'complete'}).tone,'warning');
assert.match(policyFeedback(fallback,true,{...receipt,state:'complete'}).message,/Агрегация задана, но сейчас выход идёт через/);
const settling={...device,client_api:{...device.client_api,details:{pending:true}}};
assert.equal(policyFeedback(settling,true,{...receipt,state:'complete'}).tone,'warning');
assert.equal(policyFeedback(device,false,{...receipt,state:'complete'}).tone,'warning');
});
test('queued and applying policy show one canonical action loader and visible status after reopening',async()=>{
const {ClientRouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/ClientRouterControls.tsx');
const device={id:'x',state:'ready',active_mode:'direct',modems:[],client_api:{boot_id:'b',revision:'r',rights:['policy','recovery','diagnostics','reboot'],policy:{mode:'aggregation',fail_seconds:60,recover_seconds:60,min_vpn_seconds:120},checks:[]}};
for(const state of ['queued','applying','complete','error','unknown']){
const results=[{operation_id:'one',device_id:'x',action:'policy',state,at:100,error:state==='error'?'router_busy':undefined}];
const html=renderToStaticMarkup(createElement(ClientRouterControls,{device,value:{control_version:1,runtime_id:'r',results},transport:{},ready:true}));
const pending=['queued','applying'].includes(state);
assert.equal((html.match(/aria-busy="true"/g)||[]).length,pending?1:0);
assert.ok(html.indexOf('role="status"')<html.indexOf('Ожидание отказа, с'));
if(pending){assert.doesNotMatch(html,/Не применён|Изменения ещё не применены/);assert.match(html,/disabled/);}
}
});
test('receipts survive out-of-order snapshots without mixing devices, actions or old successes',async()=>{
const {latestControlReceipt,controlMessage}=await server.ssrLoadModule('../../packages/router-ui/src/control.ts');
const base={operation_id:'old',device_id:'a',action:'policy',state:'complete',at:100};
const refused={...base,operation_id:'new',state:'error',error:'router_busy',at:102};
const rows=[{...refused,device_id:'other',at:500},{...base,action:'inspect',at:600},refused,base];
assert.deepEqual(latestControlReceipt(rows,'a','policy'),refused);
assert.deepEqual(latestControlReceipt([{...refused,state:'applying'}],'a','policy',refused),refused);
assert.deepEqual(latestControlReceipt([refused],'a','policy',{...refused,state:'queued',at:103}),refused);
assert.equal(latestControlReceipt(rows,'absent','policy'),null);
assert.match(controlMessage({state:'applying',error:'receipt_pending'}),/повторная команда не отправляется/);
assert.doesNotMatch(controlMessage({state:'unknown',action:'policy'}),/сохранена и применена/);
});
test('lost control response waits for the same receipt and never replays the write',async()=>{
const {sendControlOnce,controlBusy}=await server.ssrLoadModule('../../packages/router-ui/src/control.ts');
const initial={operation_id:'one',device_id:'router',action:'policy',state:'queued',at:100};
let writes=0;
const uncertain=await sendControlOnce({control:async()=>{writes++;throw Error('response lost');}}, {operation_id:'one'},initial);
assert.equal(writes,1);assert.equal(uncertain.operation_id,'one');assert.equal(uncertain.error,'receipt_pending');assert.equal(controlBusy(uncertain),true);
const refused=await sendControlOnce({control:async()=>({operation_id:'one',state:'error',error:'router_busy'})},{operation_id:'one'},initial);
assert.equal(refused.action,'policy');assert.equal(controlBusy(refused),false);
const accepted=await sendControlOnce({control:async()=>({operation_id:'one',state:'queued'})},{operation_id:'one'},initial);
assert.equal(controlBusy(accepted),true);
});