vignette/apps/web/e2e/public-admin-visual.spec.ts
2026-07-15 21:31:30 +09:00

223 lines
9.3 KiB
TypeScript

import { promises as fs } from "node:fs";
import path from "node:path";
import { expect, test } from "@playwright/test";
const publicApiBase = process.env.E2E_PUBLIC_API_BASE ?? "https://api-vignette.chanpaca.net";
const SHOT_DIR = path.join(process.cwd(), "node_modules", ".tmp", "public-admin-visual");
interface AuthMeResponse {
email?: string;
role?: string;
admin_access?: boolean;
super_admin?: boolean;
}
async function browserFetchJson<T>(
page: import("@playwright/test").Page,
pathName: string,
) {
return page.evaluate(
async ({ apiBase, apiPath }) => {
const response = await fetch(`${apiBase}${apiPath}`, {
credentials: "include",
headers: { accept: "application/json" },
});
const text = await response.text();
let json: unknown = null;
try {
json = text ? JSON.parse(text) : null;
} catch {
json = null;
}
return { status: response.status, ok: response.ok, text, json };
},
{ apiBase: publicApiBase, apiPath: pathName },
) as Promise<{ status: number; ok: boolean; text: string; json: T | null }>;
}
test.describe("public admin visual @public-auth", () => {
test("renders the public admin home with visible operational content", async ({
page,
}, testInfo) => {
if (!process.env.E2E_PUBLIC_STORAGE_STATE) {
throw new Error(
"Set E2E_PUBLIC_STORAGE_STATE to a storageState file captured after Google admin login.",
);
}
await fs.mkdir(SHOT_DIR, { recursive: true });
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto("/admin", { waitUntil: "domcontentloaded" });
await page.waitForLoadState("networkidle", { timeout: 15_000 }).catch(() => undefined);
const me = await browserFetchJson<AuthMeResponse>(page, "/auth/me");
expect(me.status, me.text).toBe(200);
expect(
me.json?.role === "admin" || me.json?.admin_access === true || me.json?.super_admin === true,
JSON.stringify(me.json),
).toBeTruthy();
await expect(page).toHaveURL(/\/admin(?:$|[?#])/);
await expect(page.locator(".ad-root")).toBeVisible({ timeout: 15_000 });
await expect(page.locator(".vg-shell")).toBeVisible();
await expect(page.locator(".vg-nav").getByRole("link", { name: "운영 홈" })).toBeVisible();
await expect(page.getByRole("heading", { name: "현재 서비스 상태" })).toBeVisible();
await expect(page.getByRole("heading", { name: "AI 비용" })).toBeVisible();
await expect(page.getByRole("heading", { name: "가용성" })).toBeVisible();
await expect(page.getByRole("heading", { name: "운영 티켓" })).toBeVisible();
await expect(page.locator(".ad-kpi b")).toHaveCount(4);
await expect(page.locator("#vignette-boot-diagnostic")).toHaveCount(0);
const visualReport = await page.evaluate(() => {
const adminRoot = document.querySelector<HTMLElement>(".ad-root");
const main = document.querySelector<HTMLElement>("main");
const heading = Array.from(document.querySelectorAll<HTMLElement>("h1,h2,h3")).find(
(node) => node.textContent?.includes("현재 서비스 상태"),
);
const visibleNodes = Array.from(
document.querySelectorAll<HTMLElement>(
".ad-root,.ad-head,.ad-kpi,.ad-panel,.ad-service,.vg-shell,.vg-nav,h1,h2,h3,p,a,button",
),
).filter((node) => {
const rect = node.getBoundingClientRect();
const style = getComputedStyle(node);
return (
rect.width > 4 &&
rect.height > 4 &&
style.display !== "none" &&
style.visibility !== "hidden" &&
style.opacity !== "0"
);
});
const rootRect = adminRoot?.getBoundingClientRect();
const mainRect = main?.getBoundingClientRect();
const headingRect = heading?.getBoundingClientRect();
return {
url: location.href,
bodyTextLength: document.body.innerText.trim().length,
visibleNodeCount: visibleNodes.length,
adminRootRect: rootRect
? { x: rootRect.x, y: rootRect.y, width: rootRect.width, height: rootRect.height }
: null,
mainRect: mainRect
? { x: mainRect.x, y: mainRect.y, width: mainRect.width, height: mainRect.height }
: null,
headingRect: headingRect
? { x: headingRect.x, y: headingRect.y, width: headingRect.width, height: headingRect.height }
: null,
horizontalOverflow:
document.documentElement.scrollWidth - document.documentElement.clientWidth,
};
});
expect(visualReport.bodyTextLength, JSON.stringify(visualReport)).toBeGreaterThan(400);
expect(visualReport.visibleNodeCount, JSON.stringify(visualReport)).toBeGreaterThan(20);
expect(visualReport.adminRootRect?.width, JSON.stringify(visualReport)).toBeGreaterThan(900);
expect(visualReport.adminRootRect?.height, JSON.stringify(visualReport)).toBeGreaterThan(500);
expect(visualReport.mainRect?.width, JSON.stringify(visualReport)).toBeGreaterThan(800);
expect(visualReport.headingRect?.y, JSON.stringify(visualReport)).toBeGreaterThanOrEqual(0);
expect(visualReport.headingRect?.y, JSON.stringify(visualReport)).toBeLessThan(900);
expect(visualReport.horizontalOverflow, JSON.stringify(visualReport)).toBeLessThanOrEqual(1);
const shotPath = path.join(SHOT_DIR, `admin-home-${testInfo.project.name}.png`);
await page.screenshot({ path: shotPath, fullPage: true });
const shot = await fs.stat(shotPath);
expect(shot.size, `admin visual screenshot was too small: ${shotPath}`).toBeGreaterThan(
80_000,
);
});
test("renders every public admin section without a silent blank pane", async ({ page }) => {
if (!process.env.E2E_PUBLIC_STORAGE_STATE) {
throw new Error(
"Set E2E_PUBLIC_STORAGE_STATE to a storageState file captured after Google admin login.",
);
}
const pageErrors: string[] = [];
const consoleErrors: string[] = [];
page.on("pageerror", (error) => pageErrors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
const sections = [
{ path: "/admin", heading: "현재 서비스 상태" },
{ path: "/admin/users", heading: "가입 승인과 권한 관리" },
{ path: "/admin/access", heading: "역할, 그룹, 접근 범위" },
{ path: "/admin/tickets", heading: "사용자 문제 큐" },
] as const;
for (const section of sections) {
await page.goto(section.path, { waitUntil: "domcontentloaded" });
await expect(page.locator(".ad-root")).toBeVisible({ timeout: 15_000 });
await expect(page.getByRole("heading", { name: section.heading })).toBeVisible();
await expect(page.locator(".ad-diagnostic")).toHaveCount(0);
const report = await page.evaluate(() => {
const root = document.querySelector<HTMLElement>(".ad-root");
const rect = root?.getBoundingClientRect();
const visibleNodes = root
? Array.from(root.querySelectorAll<HTMLElement>("h1,h2,p,button,input,select,article,section"))
.filter((node) => {
const nodeRect = node.getBoundingClientRect();
const style = getComputedStyle(node);
return (
nodeRect.width > 1 &&
nodeRect.height > 1 &&
style.display !== "none" &&
style.visibility !== "hidden" &&
style.opacity !== "0"
);
}).length
: 0;
return {
textLength: root?.innerText.trim().length ?? 0,
visibleNodes,
width: rect?.width ?? 0,
height: rect?.height ?? 0,
scrollY: window.scrollY,
};
});
expect(report.textLength, JSON.stringify({ section, report })).toBeGreaterThan(120);
expect(report.visibleNodes, JSON.stringify({ section, report })).toBeGreaterThan(5);
expect(report.width, JSON.stringify({ section, report })).toBeGreaterThan(300);
expect(report.height, JSON.stringify({ section, report })).toBeGreaterThan(120);
expect(report.scrollY, JSON.stringify({ section, report })).toBe(0);
}
expect(pageErrors, JSON.stringify(pageErrors)).toEqual([]);
expect(consoleErrors, JSON.stringify(consoleErrors)).toEqual([]);
});
test("returns a restored admin tab to visible content after pageshow", async ({ page }) => {
if (!process.env.E2E_PUBLIC_STORAGE_STATE) {
throw new Error(
"Set E2E_PUBLIC_STORAGE_STATE to a storageState file captured after Google admin login.",
);
}
await page.goto("/admin", { waitUntil: "domcontentloaded" });
await expect(page.getByRole("heading", { name: "현재 서비스 상태" })).toBeVisible();
await expect(page.locator(".ad-root")).toBeVisible();
const beforeRestore = await page.evaluate(() => {
document.documentElement.style.minHeight = "2200px";
document.body.style.minHeight = "2200px";
window.scrollTo(0, 900);
return window.scrollY;
});
expect(beforeRestore).toBeGreaterThan(0);
await page.evaluate(() => {
window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }));
});
await expect
.poll(() => page.evaluate(() => window.scrollY), { timeout: 5_000 })
.toBe(0);
await expect(page.getByRole("heading", { name: "현재 서비스 상태" })).toBeInViewport();
});
});