Files
MikrotikManager/tests/e2e/network-map-detail.spec.ts
T
Denozordec 2ca40fbb4d
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m33s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 2m2s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
fix(map): исправить маршруты и легенду, показать трафик пользователей
2026-11-26 11:58:31 +07:00

122 lines
13 KiB
TypeScript

import {test,expect} from "@playwright/test"
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
const wan={id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"192.0.2.1",maxDl:100,maxUl:100}
const home={id:1,name:"Домашний",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online",latency:2,wanUplinks:[wan]}
const jh={id:2,name:"Jump",host:"192.0.2.2",type:"jump-host",country:"RU",enabled:true,status:"online",latency:3}
const tunnel={id:"t1",serverId:"1",name:"gre-home",localAddress:"192.0.2.1",remoteAddress:"192.0.2.2",localInnerIp:"10.0.0.1",remoteInnerIp:"10.0.0.2",poolId:"",ipsec:null,mtu:1476,keepaliveInterval:10,keepaliveRetries:3,dscp:"inherit",clampTcpMss:true,allowFastPath:false,comment:"",enabled:true,status:"up"}
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
test("Карта: открытые детали обновляются вместе со снимком",async({page})=>{
let changed=false
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...jh,name:changed?"Новый Jump":"Jump",status:changed?null:"online",cpuLoad:changed?0:20}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map");await page.getByRole("button",{name:"Устройство Jump",exact:true}).click()
const metrics=page.getByText("CPU · RAM",{exact:true}).locator("..")
await expect(metrics).toContainText("20% · —")
await page.getByText("Ресурсы",{exact:true}).click()
const sessions=page.getByText("Сессий",{exact:true}).locator("..");await expect(sessions).toHaveText("Сессий—")
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(metrics).toContainText("0% · —");await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
await expect(page.getByText("Jump",{exact:true})).toHaveCount(0);await expect(page.getByText("Новый Jump",{exact:true}).last()).toBeVisible()
})
test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map")
const legend = page.getByRole("button", {name:"Легенда",exact:true})
await legend.click()
await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible()
await legend.click()
await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0)
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click()
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click();await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
await expect(page.getByText("primary",{exact:true})).toHaveCount(0);await expect(page.getByText("backup",{exact:true})).toHaveCount(0)
})
test("Карта: выбранный GRE обновляется и неизвестный IPsec не означает Plain",async({page})=>{
let changed=false
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map")
await page.locator("g").filter({has:page.locator("title",{hasText:"RTT неизвестен."})}).last().click()
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click();await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:/^GRE/}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
})
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
const probe={id:"measured-probe",srcServerId:"1",dstServerId:"2",srcInterface:"gre-home",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0.125,lastRxAvgMbps:null,lastPingAt:"2020-01-01T00:00:00Z"}
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map")
await page.locator("g").filter({has:page.locator("title",{hasText:"Проба measured-probe"})}).last().click()
await expect(page.getByText("0 мс",{exact:true}).last()).toBeVisible()
await expect(page.getByText("↓0.125 ↑—",{exact:true}).last()).toBeVisible()
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("2020")
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("время TX/RX неизвестно")
})
test("Карточки Exit, JumpHost и сервиса показывают измерения и обрабатывают действия", async ({ page }, info) => {
const exit = { ...jh, id: 3, type: "exit-node", name: "fra-exit02", host: "fra-exit02.rtnt.top", country: "DE", latency: 31, cpuLoad: 18, uptime: "23d9h", totalMemory: 100, freeMemory: 64, os: "7.16.1", polledAt: "2026-11-25T09:02:11Z" }
const jump = { ...exit, id: 2, name: "nov-gw01", host: "nov-gw01.rtnt.top", type: "jump-host", status: "degraded", country: "RU" }
const service = { id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 0.29 }
const edge = { fromId: "3", toId: service.id, bytes: service.bytes, bps: service.bps, bpsFwd: 8000, bpsRev: 16000 }
const path = { clientId: "u1", clientName: "msk-hr01", viaId: "2", viaName: jump.name, enId: "3", enName: exit.name, serviceId: service.id, bytes: edge.bytes, bps: edge.bps }
const record = {serverId:"3",serverName:exit.name,src:"10.20.4.18",dst:"142.250.74.14",proto:6,protoName:"TCP",srcPort:45000,dstPort:443,bytes:1000,packets:1,bps:8000,inIface:"gre1",service:"YouTube",dstAsn:15169}
const country = {...service, id:"cc:other", label:"Прочее", category:"Страна"}
const dns = {...service, id:"cc:other|svc:dns", label:"DNS", category:"DNS"}
const rows = [13,17,15,27,51,55,48,33,16,12,15,18]
const sample = { rxNow: 15, txNow: 12, rxPeak: 55, txPeak: 55, rxTotal: 1, txTotal: 1, rxSeries: rows, txSeries: rows, observations: { rxNow: true, txNow: true, rxSeries: rows.map(() => true), txSeries: rows.map(() => true), sampledAt: "2026-11-25T09:02:11Z" } }
await page.route("**/api/**", route => {
const url = new URL(route.request().url()), endpoint = url.pathname
const daily = url.searchParams.get("range") === "24h"
const data = endpoint === "/api/servers" ? [exit, jump]
: endpoint === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
: endpoint === "/api/uptime/speed-probes" ? {probes: []}
: endpoint === "/api/traffic/flow/map-hops" ? {...empty,rangeMinutes:daily?1440:5,windowSec:daily?86400:300,totalBytes:daily?4100000000:3103448,namedBytes:daily?4100000000:service.bytes,services:[{...service,bytes:daily?4100000000:service.bytes}],servicePaths:[path],serviceEdges:[edge],countries:[country],countryServiceGroups:[{countryId:country.id,services:[dns],paths:[{...path,serviceId:dns.id,bytes:100000,bps:100000*8/300}],edges:[]}]}
: endpoint === "/api/traffic/flow/analytics" ? {bpsNow:8000,bytes:1000,packets:1,conversations:3,uniqueSrc:1,uniqueDst:3,topProto:"TCP",rxSeries:[],txSeries:[],applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[record,...["unknown","US"].map(dstCountry=>({...record,service:"Прочее",category:"DNS",dstCountry,dst:dstCountry==="US"?"192.0.2.53":"198.51.100.53",dstPort:53}))],ifaces:[],live:true}
: endpoint === "/api/traffic/servers/3" ? {server:{...sample,id:"3"}}
: endpoint === "/api/traffic/servers/2" ? {server:{...sample,id:"2",observations:{...sample.observations,currentState:"error",error:"RouterOS API 401 на /interface",lastAttemptAt:"2026-11-25T09:31:08Z"}}}
: endpoint === "/api/auth/config" ? {required:false} : {}
return route.fulfill({json:data})
})
await page.goto("/network-map?server=3")
const card = page.getByRole("complementary",{name:"Детали объекта карты"})
await expect(card.getByRole("img",{name:"История измерений"})).toBeVisible()
await card.getByRole("button",{name:"Закрепить",exact:true}).click()
await expect(card.getByText("Закреплён",{exact:true}).locator("..")).toContainText("да")
await card.getByRole("button",{name:"Открепить",exact:true}).click()
await card.screenshot({path:info.outputPath("exit.png")})
await card.getByRole("button",{name:/YouTube/}).click()
await expect(card.getByText("Объём · 24 ч",{exact:true}).locator("..")).toContainText("4.10 ГБ")
await expect(card.getByText("10.20.4.18 → 142.250.74.14",{exact:true})).toBeVisible()
await expect(card.getByText("TCP/443",{exact:true})).toBeVisible()
await card.screenshot({path:info.outputPath("service.png")})
await card.getByRole("button",{name:"Фильтр по сервису"}).click()
await expect(page.getByText(/фильтр: YouTube/)).toBeVisible()
await card.getByRole("button",{name:"Снять фильтр"}).click()
await page.goto("/network-map?server=2")
await expect(card.getByText(/RouterOS API 401 на \/interface/)).toBeVisible()
await card.screenshot({path:info.outputPath("jump.png")})
await card.getByRole("button",{name:/fra-exit02/}).click()
await expect(card.getByRole("heading",{name:exit.name})).toBeVisible()
await page.getByRole("button",{name:"Страны",exact:true}).click()
await page.getByRole("button",{name:"Страна Прочее",exact:true}).press("Enter")
await card.getByRole("button",{name:/DNS/}).click()
await expect(card.getByText("Выход не определён", {exact:true})).toBeVisible()
await expect(card.getByText(/198\.51\.100\.53/)).toBeVisible()
await expect(card.getByText(/192\.0\.2\.53/)).toHaveCount(0)
})
test("Обновление NetFlow отображается внутри кнопки", async ({page}) => {
let release!: () => void
const wait = new Promise<void>(resolve => { release = resolve })
await page.route("**/api/**", async route => {
const path = new URL(route.request().url()).pathname
if (path === "/api/traffic/flow/map-hops") await wait
return route.fulfill({json:path === "/api/traffic/flow/map-hops" ? empty : path === "/api/servers" ? [jh] : path === "/api/filters/gre-tunnels" ? {tunnels:[],failures:[]} : path === "/api/uptime/speed-probes" ? {probes:[]} : path === "/api/auth/config" ? {required:false} : {}})
})
await page.goto("/network-map")
const refresh = page.getByRole("button",{name:"Обновить",exact:true})
await expect(refresh.locator("[data-slot=spinner]")).toBeVisible()
await expect(page.getByText("Обновление NetFlow…",{exact:true})).toHaveCount(0)
release()
await expect(refresh).toBeEnabled()
await expect(refresh.locator("[data-slot=spinner]")).toHaveCount(0)
})