Files
rw-visualizer/frontend/tests/graph.test.ts
T
2026-12-02 12:43:23 +05:00

126 lines
5.9 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { applyView, toFlow } from '../src/flow'
import { bpHandles, cardHandles } from '../src/handles'
import { highlightFor, rowSelId } from '../src/highlight'
import { autoLayout, heightOf, WIDTH } from '../src/layout'
import type { Graph } from '../src/types'
import raw from './fixtures/graph.json'
const graph = raw as unknown as Graph
const RU = 'node:n-ru'
const FI = 'node:n-2'
describe('handles: карточки рисуют ровно те порты, к которым привязаны рёбра', () => {
const nodes = new Map(graph.nodes.map((n) => [n.id, n]))
const portsOf = (id: string) => {
const n = nodes.get(id)!
const defs = n.type === 'node' ? cardHandles(n.data) : bpHandles(n.type, n.data)
return { source: new Set(defs.filter((h) => h.type === 'source').map((h) => h.id)), target: new Set(defs.filter((h) => h.type === 'target').map((h) => h.id)) }
}
it('у каждого ребра есть исходящий и входящий порт', () => {
for (const e of graph.edges) {
expect(portsOf(e.source).source.has(e.sourceHandle), `${e.id} (source)`).toBe(true)
expect(portsOf(e.target).target.has(e.targetHandle), `${e.id} (target)`).toBe(true)
}
})
})
describe('autoLayout', () => {
const pos = autoLayout(graph)
const nodes = new Map(graph.nodes.map((n) => [n.id, n]))
it('даёт позицию каждому блоку', () => {
for (const n of graph.nodes) expect(pos[n.id], n.id).toBeDefined()
})
it('блоки одной колонки не перекрываются', () => {
const cols = new Map<number, string[]>()
for (const n of graph.nodes) cols.set(pos[n.id].x, [...(cols.get(pos[n.id].x) ?? []), n.id])
for (const ids of cols.values()) {
const sorted = ids.sort((a, b) => pos[a].y - pos[b].y)
for (let i = 1; i < sorted.length; i++) {
const prev = nodes.get(sorted[i - 1])!
expect(pos[sorted[i]].y, `${sorted[i - 1]} / ${sorted[i]}`).toBeGreaterThanOrEqual(pos[sorted[i - 1]].y + heightOf(prev))
}
}
})
it('поток идёт слева направо: источник каждого ребра левее приёмника', () => {
for (const e of graph.edges) {
expect(pos[e.source].x + WIDTH[nodes.get(e.source)!.type], e.id).toBeLessThan(pos[e.target].x)
}
})
it('хост стоит напротив строки, на которую садится его нитка', () => {
const h3 = graph.edges.find((e) => e.source === 'host:h3')!
const hostY = pos['host:h3'].y + heightOf(nodes.get('host:h3')!) / 2
const ruY = pos[RU].y
expect(h3.targetHandle).toBe('rin:inb-bridge:8')
// правило #8 лежит ниже шапки карточки; хост не должен висеть выше карточки
expect(hostY).toBeGreaterThan(ruY)
})
})
describe('highlight', () => {
it('хост: путь через обе ноды, проверенные строки приглушены', () => {
const hl = highlightFor('host:h3', graph)!
expect(hl.hostIds).toEqual(['host:h3'])
expect(hl.nodes.has(RU) && hl.nodes.has(FI)).toBe(true)
const ru = hl.rows.get(RU)!
expect(ru.active.has('inb-bridge:8')).toBe(true)
expect([...ru.pass].sort()).toEqual(['inb-bridge:6', 'inb-bridge:7'])
expect(hl.rows.get(FI)!.active.has('inb:inb-def-ss')).toBe(true)
})
it('строка: подсвечиваются только хосты, которых она касается', () => {
expect(highlightFor(rowSelId(RU, 'inb-bridge:8'), graph)!.hostIds).toEqual(['host:h3'])
expect(highlightFor(rowSelId(RU, 'inb-bridge:13'), graph)!.hostIds.sort()).toEqual(['host:h8', 'host:hn'])
})
it('нода-приёмник: и мост, и прямое подключение', () => {
const ids = highlightFor(FI, graph)!.hostIds
expect(ids).toContain('host:hd')
expect(ids).toContain('host:h3')
expect(ids).toContain('host:h7') // через балансер
expect(ids).not.toContain('host:nonexistent')
})
it('недостижимая строка не подсвечивает хостов', () => {
expect(highlightFor(rowSelId(RU, 'inb-bridge:14'), graph)!.hostIds).toEqual([])
})
it('без выбора подсветки нет', () => {
expect(highlightFor(null, graph)).toBeNull()
})
})
describe('toFlow / applyView', () => {
const flow = toFlow(graph, {}, autoLayout(graph))
it('нода рисуется карточкой, остальное простыми блоками', () => {
expect(flow.nodes.filter((n) => n.type === 'card')).toHaveLength(graph.nodes.filter((n) => n.type === 'node').length)
expect(flow.nodes.find((n) => n.id === 'host:h3')!.type).toBe('bp')
})
it('сохранённая позиция важнее автоматической', () => {
const f = toFlow(graph, { [RU]: { x: 1, y: 2 } }, autoLayout(graph))
expect(f.nodes.find((n) => n.id === RU)!.position).toEqual({ x: 1, y: 2 })
})
it('подсветка: остальное приглушается, карточки получают строки, позиции не меняются', () => {
const hl = highlightFor('host:h3', graph)
const v = applyView(flow.nodes, flow.edges, hl, false)
expect(v.nodes.find((n) => n.id === 'host:h3')!.class).toBe('active')
expect(v.nodes.find((n) => n.id === 'host:h7')!.class).toBe('dim')
expect(v.nodes.find((n) => n.id === RU)!.data.hl.active).toContain('inb-bridge:8')
expect(v.edges.filter((e) => e.animated).length).toBe(hl!.edges.size)
expect(v.nodes.map((n) => n.position)).toEqual(flow.nodes.map((n) => n.position))
})
it('hideShadowed и пустая подсветка пробрасываются в карточки', () => {
const v = applyView(flow.nodes, flow.edges, null, true)
expect(v.nodes.find((n) => n.id === RU)!.data.hideShadowed).toBe(true)
expect(v.nodes.find((n) => n.id === RU)!.data.hl).toBeNull()
})
})