Files
MikrotikManager/tests/e2e/firewall-tables.spec.ts
T

113 lines
6.7 KiB
TypeScript

import { test, expect, type Page } from "@playwright/test"
import type { FirewallRule } from "../../lib/data"
async function setup(page: Page, failMove = false) {
let rules: FirewallRule[] = Array.from({ length: 12 }, (_, i) => ({
id: `rule-${i + 1}`, rosId: `*${i + 1}`, serverId: "1", serverName: "Тестовый роутер",
family: "ip", table: "filter", chain: "forward", action: "accept", proto: "tcp",
src: `192.0.2.${i + 1}`, dst: "", port: "443", iface: "", comment: `Правило ${i + 1}`,
enabled: true, hits: i + 1,
}))
const moves: Record<string, unknown>[] = []
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
if (path === "/api/firewall/rules/move") {
const body = route.request().postDataJSON()
moves.push(body)
if (failMove) return route.fulfill({ status: 500, json: { message: "Ошибка перемещения" } })
const active = rules.find(r => r.rosId === body.rosId)!
rules = rules.filter(r => r !== active)
const destination = rules.findIndex(r => r.rosId === body.destinationRosId)
rules.splice(destination < 0 ? rules.length : destination, 0, active)
return route.fulfill({ json: { ok: true } })
}
return route.fulfill({ json: path === "/api/firewall/all" ? { rules, addressLists: [] }
: path === "/api/auth/config" ? { required: false }
: path === "/api/servers" ? [{ id: 1, name: "Тестовый роутер", host: "192.0.2.100", type: "exit-node", site: "TEST", country: "RU", asn: "", enabled: true, status: "online", latency: 1 }] : {} })
})
await page.goto("/firewall?server=1")
await expect(page.locator("tr[data-row-id]")).toHaveCount(12)
return moves
}
async function moveFirstDown(page: Page) {
const handle = page.locator('tr[data-row-id="rule-1"]').getByRole("button", { name: "Перетащите для изменения порядка строк", exact: true })
await handle.focus()
await page.keyboard.press("Space")
await expect(handle).toHaveAttribute("aria-pressed", "true")
await page.keyboard.press("ArrowDown")
await expect(page.locator('[role="status"]')).toContainText("over droppable area rule-2")
await page.keyboard.press("Space")
}
test("Firewall: клавиатурное перемещение подтверждается API и сохраняет все строки", async ({ page }) => {
const moves = await setup(page)
await moveFirstDown(page)
await expect.poll(() => moves.length).toBe(1)
expect(moves[0]).toMatchObject({ serverId: "1", family: "ip", table: "filter", rosId: "*1", destinationRosId: "*3" })
await expect(page.locator("tr[data-row-id]").first()).toHaveAttribute("data-row-id", "rule-2")
await expect(page.locator("tr[data-row-id]").nth(1)).toHaveAttribute("data-row-id", "rule-1")
await expect(page.locator("tr[data-row-id]")).toHaveCount(12)
})
test("Firewall: ошибка перемещения возвращает исходный порядок", async ({ page }) => {
const moves = await setup(page, true)
await moveFirstDown(page)
await expect.poll(() => moves.length).toBe(1)
await expect(page.locator("tr[data-row-id]").first()).toHaveAttribute("data-row-id", "rule-1")
await expect(page.locator("tr[data-row-id]")).toHaveCount(12)
})
test("Firewall: Escape отменяет перенос без API-запроса", async ({ page }) => {
const moves = await setup(page)
await page.locator('tr[data-row-id="rule-1"]').getByRole("button", { name: "Перетащите для изменения порядка строк", exact: true }).focus()
await page.keyboard.press("Space")
await expect(page.locator('tr[data-row-id="rule-1"]').getByRole("button", { name: "Перетащите для изменения порядка строк", exact: true })).toHaveAttribute("aria-pressed", "true")
await page.keyboard.press("ArrowDown")
await expect(page.locator('[role="status"]')).toContainText("over droppable area rule-2")
await page.keyboard.press("Escape")
await expect(page.locator("tr[data-row-id]").first()).toHaveAttribute("data-row-id", "rule-1")
expect(moves).toHaveLength(0)
})
test("Firewall: перенос мышью отправляет тот же запрос", async ({ page }) => {
const moves = await setup(page)
const handle = page.locator('tr[data-row-id="rule-1"]').getByRole("button", { name: "Перетащите для изменения порядка строк", exact: true })
await handle.scrollIntoViewIfNeeded()
const start = await handle.boundingBox()
const target = await page.locator('tr[data-row-id="rule-2"]').boundingBox()
if (!start || !target) throw new Error("Строки недоступны для переноса")
const x = start.x + start.width / 2
await page.mouse.move(x, start.y + start.height / 2)
await page.mouse.down()
await page.mouse.move(x, target.y + target.height / 2, { steps: 10 })
await expect(page.locator('[role="status"]')).toContainText("over droppable area rule-2")
await page.mouse.up()
await expect.poll(() => moves.length).toBe(1)
expect(moves[0]).toMatchObject({ rosId: "*1", destinationRosId: "*3" })
await expect(page.locator("tr[data-row-id]").first()).toHaveAttribute("data-row-id", "rule-2")
})
test("Сценарий Firewall: 12 правил, перемещение и удаление в черновике", async ({ page }) => {
await setup(page)
await page.getByRole("button", { name: "Симулятор", exact: true }).click()
await page.getByRole("button", { name: "Новый сценарий", exact: true }).click()
const dialog = page.getByRole("dialog")
for (let i = 0; i < 12; i++) {
await dialog.getByRole("button", { name: "Добавить правило", exact: true }).click()
await dialog.getByRole("button", { name: "Добавить", exact: true }).click()
}
const rows = dialog.locator("tr[data-row-id]")
await expect(rows).toHaveCount(12)
const firstId = await rows.first().getAttribute("data-row-id")
await expect(dialog.getByRole("button", { name: "Поднять правило 1", exact: true })).toBeDisabled()
await expect(dialog.getByRole("button", { name: "Опустить правило 12", exact: true })).toBeDisabled()
await dialog.getByRole("button", { name: "Опустить правило 1", exact: true }).click()
await expect(rows.nth(1)).toHaveAttribute("data-row-id", firstId!)
await dialog.getByRole("button", { name: "Удалить правило 2", exact: true }).click()
await expect(rows).toHaveCount(11)
await expect(dialog.locator(`tr[data-row-id="${firstId}"]`)).toHaveCount(0)
await dialog.getByRole("button", { name: "Отмена", exact: true }).click()
})