Files
MikrotikManager/tests/e2e/network-map-overlap.spec.ts
T
Denozordec 545a9bbcd2
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m8s
Docker images / frontend-image (push) Successful in 2m25s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 2m1s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
feat(network-map): добавить сворачивание групп и категории трафика
2026-12-03 09:58:24 +07:00

195 lines
15 KiB
TypeScript
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 { test, expect, type Page } from "@playwright/test"
// Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы.
import { emptyMapFlow } from "./fixtures/map-flow"
const srv = (id: number, name: string, type: string, country = "RU", status = "online") =>
({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id })
const gre = (id: string, owner: number, peer: number, status = "up") => ({
id, serverId: String(owner), name: id, localAddress: `192.0.2.${owner}`, remoteAddress: `192.0.2.${peer}`, localInnerIp: "", remoteInnerIp: "",
poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit", clampTcpMss: true, allowFastPath: false, comment: "", enabled: true, status,
})
async function serve(page: Page, servers: unknown[], tunnels: ReturnType<typeof gre>[], flow: Record<string, unknown>) {
await page.route("**/health", (r) => r.fulfill({ json: { ok: true } }))
await page.route("**/api/**", (r) => {
const p = new URL(r.request().url()).pathname
const json = p === "/api/servers" ? servers : p === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
: p === "/api/uptime/speed-probes" ? { probes: [] } : p === "/api/traffic/flow/map-hops" ? { ...emptyMapFlow(r.request().url()), live: true, mapServiceMinSharePct: 0, ...flow }
: p === "/api/ix/topology" ? { links: [] } : p === "/api/auth/config" ? { required: false } : {}
return r.fulfill({ json })
})
}
async function overlaps(page: Page) {
return page.getByRole("group", { name: "Интерактивная карта сети" }).evaluate((svg) => {
const boxes = [...svg.querySelectorAll("[data-map-box]")].map((el) => ({ kind: el.getAttribute("data-map-box")!, label: el.closest("[aria-label]")?.getAttribute("aria-label") ?? el.parentElement?.textContent ?? "", text: el.parentElement?.querySelector(":scope > text")?.textContent ?? "", r: el.getBoundingClientRect() }))
// Панель масштаба и миникарта лежат поверх холста — они тоже не должны закрывать карточки и подписи.
const overlays = [...document.querySelectorAll("[data-map-overlay]")].map((el) => ({ kind: el.getAttribute("data-map-overlay")!, label: "", r: el.getBoundingClientRect() }))
const hits: string[] = []
const pairs = [...boxes.flatMap((a, i) => boxes.slice(i + 1).map((b) => [a, b] as const)), ...overlays.flatMap((o) => boxes.map((b) => [o, b] as const))]
for (const [a, b] of pairs) {
const ix = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left), iy = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top)
if (ix > 1 && iy > 1) hits.push(`${a.kind} «${a.label}» × ${b.kind} «${b.label}»`)
}
return { overlays: overlays.length, rates: boxes.filter((b) => b.kind === "pill" && /бит\/с/.test(b.text)).length, pills: boxes.filter((b) => b.kind === "pill").length, cards: boxes.filter((b) => b.kind === "card").length, hits }
})
}
test("Категория открывает сервисы, фильтрует потоки и сохраняет контекст при возврате", async ({ page }) => {
const services = [
{ id: "svc:video", label: "Видео A", category: "Видео", bytes: 900, bps: 120, share: 0.9 },
{ id: "svc:tiny", label: "Видео B", category: "Видео", bytes: 50, bps: 6, share: 0.05 },
{ id: "svc:dns", label: "DNS", category: "DNS", bytes: 50, bps: 6, share: 0.05 },
]
const paths = services.map(s => ({clientId: "a", clientName: "A", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: s.id, bytes: s.bytes, bps: s.bps}))
const edges = services.map(s => ({fromId: "1", toId: s.id, observedOnly: true, bytes: s.bytes, bps: s.bps, bpsFwd: s.bps, bpsRev: 0}))
await serve(page, [srv(1, "Вход", "jump-host")], [], {services, servicePaths: paths, serviceEdges: edges, totalBytes: 1000, namedBytes: 1000})
await page.goto("/network-map")
await page.getByRole("button", {name: "Категории", exact: true}).click()
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
const category = map.getByRole("button", {name: "Категория Видео", exact: true})
await expect(category).toContainText("95%")
await category.press("Enter")
const details = page.getByRole("complementary", {name: "Детали объекта карты"})
await expect(details.getByRole("heading", {name: "Видео", exact: true})).toBeVisible()
await details.getByRole("button", {name: "Потоки категории (2)"}).click()
const panel = page.getByRole("region", {name: "Рабочая панель карты"})
await expect(panel.getByText("Видео A", {exact: true})).toBeVisible()
await expect(panel.getByText("DNS", {exact: true})).toHaveCount(0)
await details.getByRole("button", {name: /Видео B/}).click()
await expect(page).toHaveURL(/service=svc%3Atiny/)
await expect(map.getByRole("button", {name: "Сервис Видео B", exact: true})).toBeVisible()
await page.goBack()
await expect(details.getByRole("heading", {name: "Видео", exact: true})).toBeVisible()
})
test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 сервисов без наложений", async ({ page }) => {
const servers = [
srv(1, "msk-gw01.example.net", "jump-host"), srv(2, "msk-gw02.example.net", "jump-host"), srv(3, "nov-gw01.example.net", "jump-host"),
srv(4, "arn-gw01.example.net", "exit-node", "SE"), srv(5, "chr-ix.example.net", "ix-node", "PL"),
]
// У каждого JH два туннеля до выхода и запись встречного конца на выходе; один JH ещё и до IX.
const tunnels = [1, 2, 3].flatMap((jh) => [gre(`gre-${jh}a`, jh, 4), gre(`gre-${jh}b`, jh, 4, jh === 3 ? "down" : "up"), gre(`gre-4-${jh}`, 4, jh)])
tunnels.push(gre("gre-ix", 1, 5))
const names = ["Прочее", "YouTube", "Cloudflare", "main", "AWS", "Akamai", "Google", "Telegram"]
const services = names.map((label, i) => ({ id: "svc:" + i, label, category: "Веб", bytes: 9e6 - i * 1e6, bps: 6e6 - i * 7e5, share: 0.2 - i * 0.02 }))
const serviceEdges = services.map((s) => ({ fromId: "4", toId: s.id, bytes: s.bytes, bps: s.bps, bpsFwd: s.bps / 4, bpsRev: (s.bps * 3) / 4 }))
const interfaceTraffic = tunnels.map((t, i) => ({ serverId: t.serverId, iface: t.name, rxBytes: 4e6 + i * 1e5, txBytes: 1e6, rxPackets: 10, txPackets: 5, inWindow: true, lastBucketAt: "2026-11-23T07:00:00Z" }))
await serve(page, servers, tunnels, { services, serviceEdges, interfaceTraffic, totalBytes: 5e7, namedBytes: 5e7 })
await page.goto("/network-map")
await page.getByRole("button", { name: /^Остальные сервисы \(/ }).first().click()
await expect(page.getByRole("button", { name: "Сервис Telegram", exact: true })).toBeVisible()
await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
const result = await overlaps(page)
expect(result.cards).toBe(5)
expect(result.overlays).toBe(2)
expect(result.hits).toEqual([])
// Скорость NetFlow пары не теряется: она на подписи или, если не влезла между карточками, — в title линии.
expect(result.rates + await page.locator("path > title", { hasText: /^Связь .*бит\/с/ }).count()).toBeGreaterThan(0)
// Имя хоста без домена, параллельные туннели — одной подписью.
await expect(page.getByRole("group", { name: "Интерактивная карта сети" }).getByText("msk-gw01", { exact: true })).toBeVisible()
const pair = /^Связь msk-gw01\.example\.net → arn-gw01\.example\.net: .*GRE ×2/
expect(await page.getByRole("button", { name: pair }).count()).toBeLessThanOrEqual(1)
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
})
test("Карта: группа сервисов сворачивается на холсте, IPFIX огибает карточки", async ({ page }, info) => {
await page.setViewportSize({ width: 867, height: 914 })
const servers = [srv(1, "Узел доступа", "jump-host"), srv(2, "Интернет-выход", "exit-node", "DE")]
const major = { id: "svc:dns", label: "DNS", category: "DNS", bytes: 9_500, bps: 760, share: 0.95 }
const minor = { id: "svc:ntp", label: "NTP", category: "NTP", bytes: 500, bps: 40, share: 0.05 }
const serviceEdges = [major, minor].map(service => ({ fromId: "1", toId: service.id,
bytes: service.bytes, bps: service.bps, bpsFwd: service.bps, bpsRev: 0, observedOnly: true }))
await serve(page, servers, [gre("gre-exit", 1, 2)], { services: [major, minor], serviceEdges, namedBytes: 10_000, totalBytes: 10_000 })
await page.goto("/network-map")
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
const group = map.getByRole("button", { name: /^Остальные сервисы/ })
const closeGroup = map.getByRole("button", { name: "Свернуть остальные", exact: true })
const ntp = map.getByRole("button", { name: "Сервис NTP" })
await expect(group).toHaveAttribute("aria-expanded", "false")
await expect(ntp).toHaveCount(0)
await group.press("Enter")
await expect(closeGroup).toHaveAttribute("aria-expanded", "true")
await expect(ntp).toBeVisible()
await expect(map.locator('[data-map-route="observation"]')).toHaveCount(2)
const intersectsCards = await map.evaluate(svg => {
const cards = [...svg.querySelectorAll('[data-map-box="card"], [data-map-box="dest"]')].map(card => card.getBoundingClientRect())
return [...svg.querySelectorAll<SVGPathElement>('[data-map-route="observation"]')].some(path => {
const length = path.getTotalLength()
const transform = path.getScreenCTM()!
for (let distance = 1; distance < length; distance += 2) {
const p = path.getPointAtLength(distance).matrixTransform(transform)
if (cards.some(rect => p.x > rect.left + 1 && p.x < rect.right - 1 && p.y > rect.top + 1 && p.y < rect.bottom - 1)) return true
}
return false
})
})
expect(intersectsCards).toBe(false)
await closeGroup.press("Enter")
await expect(group).toHaveAttribute("aria-expanded", "false")
await expect(ntp).toHaveCount(0)
await expect.poll(async () => (await map.boundingBox())!.y + (await map.boundingBox())!.height).toBeLessThan(915)
await expect(page.getByRole("button", { name: "Открыть рабочую панель" })).toBeInViewport()
await page.screenshot({path:info.outputPath("карта-сети.png")})
})
test("Связи Cloudflare остаются на гранях экспортёра и подтверждённого выхода при перетаскивании", async ({ page }) => {
const service = { id: "svc:cloudflare", label: "Cloudflare", category: "Cloud", bytes: 10000, bps: 800, share: 1 }
const edge = { toId: service.id, bytes: 5000, bps: 400, bpsFwd: 400, bpsRev: 0 }
await serve(page, [srv(1, "nov-gw01", "jump-host"), srv(2, "ARN", "exit-node")], [], {
services: [service], serviceEdges: [{ ...edge, fromId: "1", observedOnly: true }, { ...edge, fromId: "2" }],
namedBytes: service.bytes, totalBytes: service.bytes,
})
await page.goto("/network-map")
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
const arn = map.getByRole("button", { name: "Устройство ARN" })
const cloudflare = map.getByRole("button", { name: "Сервис Cloudflare" })
const exporter = map.getByRole("button", { name: "Устройство nov-gw01" })
await expect(cloudflare).toBeVisible()
async function attached() {
const connections = await map.evaluate(svg => {
const card = (name: string) => svg.querySelector(`[aria-label="${name}"] [data-map-box]`)!.getBoundingClientRect()
const atSide = (p: DOMPoint, r: DOMRect) =>
Math.min(Math.abs(p.x - r.left), Math.abs(p.x - r.right)) < 1 && Math.abs(p.y - (r.top + r.bottom) / 2) < 1
return [...svg.querySelectorAll<SVGPathElement>("[data-map-route]")].map(path => {
const transform = path.getScreenCTM()!
const start = path.getPointAtLength(0).matrixTransform(transform)
const end = path.getPointAtLength(path.getTotalLength()).matrixTransform(transform)
const source = path.dataset.mapRoute === "observation" ? "Устройство nov-gw01" : "Устройство ARN"
return atSide(start, card(source)) && atSide(end, card("Сервис Cloudflare"))
})
})
expect(connections).toEqual([true, true])
}
await attached()
async function center(node: typeof arn) {
const rect = (await node.boundingBox())!
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
}
const a = await center(arn)
await arn.dragTo(map, { targetPosition: { x: a.x - (await map.boundingBox())!.x + 30, y: a.y - (await map.boundingBox())!.y - 65 } })
expect(Math.abs((await center(arn)).y - a.y)).toBeGreaterThan(20)
await attached()
// Same column: before the fix the IPFIX route was replaced by a disconnected dot.
const jh = await center(exporter)
const bounds = (await map.boundingBox())!
await cloudflare.dragTo(map, {targetPosition: {x: jh.x - bounds.x, y: jh.y - bounds.y + 85}})
expect(Math.abs((await center(cloudflare)).x - (await center(exporter)).x)).toBeLessThan(15)
await attached()
})
test("Карта: сетка JH × Exit и аплинки WAN без наложений подписей", async ({ page }) => {
const wan = (i: number) => ({ id: "w" + i, name: "WAN" + i, iface: "ether" + i, isp: "ISP-" + i, ip: `198.51.100.${i}`, maxDl: 100, maxUl: 50 })
const servers = [
{ ...srv(1, "home-msk", "home-router"), wanUplinks: [wan(1), wan(2)] }, { ...srv(2, "home-spb", "home-router"), wanUplinks: [wan(3), wan(4)] },
srv(3, "mt-msk-core-01", "jump-host"), srv(4, "mt-msk-lab-01", "jump-host"), srv(5, "mt-ams-test-01", "jump-host", "NL"),
srv(6, "mt-fra-edge-01", "exit-node", "DE"), srv(7, "mt-sgp-edge-01", "exit-node", "SG", "offline"), srv(8, "mt-spb-edge-01", "exit-node"), srv(9, "mt-ams-edge-01", "exit-node", "NL", "degraded"),
]
const tunnels = [3, 4, 5].flatMap((jh) => [6, 7, 8, 9].map((en) => gre(`gre-${jh}-${en}`, jh, en, en === 7 ? "down" : "up")))
await serve(page, servers, tunnels, {})
await page.goto("/network-map")
await expect(page.getByRole("button", { name: /^Устройство mt-ams-edge-01/ })).toBeVisible()
await expect.poll(async () => (await overlaps(page)).pills).toBeGreaterThan(2)
expect((await overlaps(page)).hits).toEqual([])
})