Files
watchman/web/apps/console/e2e/datasources.spec.ts
T
unknownandCursor be63e2fe5d feat(web): 列表自适应布局并将分页固定页脚
数据源与查询列表整页不滚、仅表体内滚;名称筛选去掉「模糊」占位后缀。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 18:48:50 +08:00

861 lines
41 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 { expect, test, type Page, type Route } from "@playwright/test";
import path from "node:path";
import { fileURLToPath } from "node:url";
const evidenceDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../../../docs/evidence/M03/ui",
);
// Synthetic data only. Hosts use the reserved .example.test suffix.
// The password below stands in for a saved secret: the mocked API never returns it.
const SAVED_SECRET = "pw-never-shown-9f3a";
const DRIVER_TEXT = "FATAL: driver said something private";
type Row = {
id: string;
name: string;
description: string | null;
kind: string;
engine: string;
host: string;
port: number;
database_name: string;
username: string;
secret_configured: boolean;
read_only_intent: boolean;
enabled: boolean;
circuit_state: "closed" | "open";
circuit_opened_at: string | null;
circuit_open_until: string | null;
circuit_failure_window_seconds: number;
circuit_failure_threshold: number;
circuit_open_cooldown_seconds: number;
last_test_category: string | null;
last_test_at: string | null;
last_test_message: string | null;
created_at: string;
updated_at: string;
};
function row(overrides: Partial<Row> & Pick<Row, "id" | "name">): Row {
return {
description: "示例(虚构)",
kind: "database",
engine: "postgresql",
host: "db.example.test",
port: 5432,
database_name: "process_demo",
username: "readonly_demo",
secret_configured: true,
read_only_intent: true,
enabled: true,
circuit_state: "closed",
circuit_opened_at: null,
circuit_open_until: null,
circuit_failure_window_seconds: 300,
circuit_failure_threshold: 3,
circuit_open_cooldown_seconds: 600,
last_test_category: null,
last_test_at: null,
last_test_message: null,
created_at: "2026-11-17T01:00:00+00:00",
updated_at: "2026-11-17T01:00:00+00:00",
...overrides,
};
}
const ID_ONE = "11111111-1111-4111-8111-111111111111";
const ID_OFF = "44444444-4444-4444-8444-444444444444";
const ID_OPEN = "66666666-6666-4666-8666-666666666666";
function seedRows(): Row[] {
return [
row({
id: ID_ONE,
name: "产线工艺库",
last_test_category: "success",
last_test_at: "2026-11-17T01:12:00+00:00",
}),
row({
id: "22222222-2222-4222-8222-222222222222",
name: "设备台账库",
engine: "mysql",
host: "mysql.example.test",
port: 3306,
database_name: "asset_demo",
last_test_category: "auth_failed",
last_test_at: "2026-11-16T09:40:00+00:00",
}),
row({
id: "33333333-3333-4333-8333-333333333333",
name: "质检结果库",
engine: "sqlserver",
host: "mssql.example.test",
port: 1433,
database_name: "quality_demo",
}),
row({
id: ID_OFF,
name: "历史归档库",
host: "archive.example.test",
database_name: "archive_demo",
enabled: false,
last_test_category: "success",
last_test_at: "2026-11-10T06:03:00+00:00",
}),
row({
id: ID_OPEN,
name: "熔断演示库",
host: "flaky.example.test",
database_name: "flaky_demo",
circuit_state: "open",
circuit_opened_at: "2026-11-18T09:20:00+00:00",
circuit_open_until: "2026-11-18T09:30:00+00:00",
circuit_failure_window_seconds: 120,
circuit_failure_threshold: 5,
circuit_open_cooldown_seconds: 900,
last_test_category: "unreachable",
last_test_at: "2026-11-18T09:20:00+00:00",
}),
];
}
function ok(data: unknown): string {
return JSON.stringify({ success: true, data, request_id: "pw-ds" });
}
function fail(code: number, message: string, details: Record<string, unknown> = {}): string {
return JSON.stringify({
success: false,
error: { code, message, details, retryable: false },
request_id: "pw-ds",
});
}
type Mock = {
rows: Row[];
requests: { method: string; pathname: string; body: unknown }[];
testOutcome: { status: number; body: string; delayMs: number };
draftOutcome: { status: number; body: string; delayMs: number };
};
async function signIn(page: Page, roles: string[]): Promise<void> {
await page.route("**/auth/me", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: ok({ subject: "user-1", display_name: "Worker", roles }),
});
});
await page.route("**/health", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: ok({ status: "ok", app: "watchman", version: "0.1.0" }),
});
});
}
/** Mock /datasources exactly; source files under /src/datasources are never matched. */
async function mockDatasources(page: Page, rows: Row[] = seedRows()): Promise<Mock> {
const mock: Mock = {
rows,
requests: [],
testOutcome: { status: 200, delayMs: 0, body: "" },
draftOutcome: { status: 200, delayMs: 0, body: ok({ category: "success", message: "fixed" }) },
};
mock.testOutcome.body = ok({
id: ID_ONE,
category: "success",
message: "fixed",
last_test_at: "2026-11-18T02:00:00+00:00",
});
const matcher = (url: URL) =>
/^\/datasources(\/(test-draft|[0-9a-f-]{36}(\/(test|disable|enable|references))?))?$/.test(url.pathname);
await page.route(matcher, async (route: Route) => {
const request = route.request();
const url = new URL(request.url());
const method = request.method();
let body: unknown = null;
if (method === "POST" || method === "PATCH") {
body = request.postDataJSON();
}
mock.requests.push({ method, pathname: url.pathname, body });
const json = (status: number, text: string) =>
route.fulfill({ status, contentType: "application/json", body: text });
const parts = url.pathname.split("/").filter(Boolean);
const id = parts[1];
const found = mock.rows.find((item) => item.id === id);
if (id === "test-draft") {
const draft = body as Record<string, unknown>;
if (!draft.password && !draft.datasource_id) {
return json(400, fail(40000, "Password is required", { fields: ["password"] }));
}
await new Promise((resolve) => setTimeout(resolve, mock.draftOutcome.delayMs));
return json(mock.draftOutcome.status, mock.draftOutcome.body);
}
if (parts.length === 1) {
if (method === "GET") {
const name = (url.searchParams.get("name") || "").trim().toLowerCase();
const engine = url.searchParams.get("engine") || "";
const enabledParam = url.searchParams.get("enabled");
const page = Number(url.searchParams.get("page") || "1");
const pageSize = Number(url.searchParams.get("page_size") || "20");
const sortBy = url.searchParams.get("sort_by") || "created_at";
const sortOrder = url.searchParams.get("sort_order") || "asc";
let rows = [...mock.rows];
if (name) {
rows = rows.filter((item) => item.name.toLowerCase().includes(name));
}
if (engine) {
rows = rows.filter((item) => item.engine === engine);
}
if (enabledParam === "true") {
rows = rows.filter((item) => item.enabled);
}
if (enabledParam === "false") {
rows = rows.filter((item) => !item.enabled);
}
const dir = sortOrder === "asc" ? 1 : -1;
rows.sort((a, b) => {
const av = (a as Record<string, unknown>)[sortBy];
const bv = (b as Record<string, unknown>)[sortBy];
if (av === bv) return 0;
if (av == null) return 1;
if (bv == null) return -1;
return av < bv ? -dir : dir;
});
const total = rows.length;
const start = Math.max(0, (page - 1) * pageSize);
const items = rows.slice(start, start + pageSize);
return json(200, ok({ items, total, page, page_size: pageSize }));
}
const created = row({ id: "55555555-5555-4555-8555-555555555555", name: "x" });
Object.assign(created, body, { secret_configured: true });
delete (created as Partial<Record<string, unknown>>).password;
mock.rows.push(created);
return json(200, ok(created));
}
if (!found) {
return json(404, fail(40400, "Datasource not found"));
}
const action = parts[2];
if (!action) {
if (method === "GET") {
return json(200, ok(found));
}
const patch = { ...(body as Record<string, unknown>) };
delete patch.password;
Object.assign(found, patch);
return json(200, ok(found));
}
if (action === "references") {
return json(200, ok({ id: found.id, items: [] }));
}
if (action === "disable") {
found.enabled = false;
return json(200, ok(found));
}
if (action === "enable") {
found.enabled = true;
return json(200, ok(found));
}
if (!found.enabled) {
return json(409, fail(40900, "Datasource is disabled", { reason: "disabled" }));
}
if (found.circuit_state === "open") {
return json(
409,
fail(40900, "Circuit open", { reason: "circuit_open", circuit_open_until: found.circuit_open_until }),
);
}
await new Promise((resolve) => setTimeout(resolve, mock.testOutcome.delayMs));
return json(mock.testOutcome.status, mock.testOutcome.body);
});
return mock;
}
async function expectNoSecretAnywhere(page: Page): Promise<void> {
await expect(page.locator("body")).not.toContainText(SAVED_SECRET);
const html = await page.content();
expect(html).not.toContain(SAVED_SECRET);
const stored = await page.evaluate(() =>
JSON.stringify({ local: { ...window.localStorage }, session: { ...window.sessionStorage } }),
);
expect(stored).not.toContain(SAVED_SECRET);
}
test.describe("datasources console", () => {
test("admin list: breadcrumb, create button above the table, columns, disabled row", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockDatasources(page);
await page.goto("/#/datasources");
await expect(page.getByTestId("datasource-table")).toBeVisible();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("预警平台");
await expect(crumb).toContainText("数据源");
await expect(crumb).not.toContainText("新建");
await expect(crumb).not.toContainText("详情");
await expect(page.getByTestId("nav-datasources")).toBeVisible();
await expect(page.getByTestId("side-logo")).toBeVisible();
await expect(page.getByTestId("side-user").getByTestId("shell-welcome")).toBeVisible();
for (const header of ["名称", "引擎", "主机", "端口", "库名", "用户名", "状态", "最近测试", "操作"]) {
await expect(page.locator(".el-table__header").getByText(header, { exact: true })).toBeVisible();
}
await expect(page.getByTestId("datasource-table")).toContainText("产线工艺库");
await expect(page.getByTestId("datasource-table")).toContainText("SQL Server");
await expect(page.getByTestId("datasource-table")).toContainText("2026-11-17");
await expect(page.getByTestId("datasource-table")).toContainText("尚未测试");
await expect(page.getByTestId("datasource-pagination")).toBeVisible();
await expect(page.getByTestId("datasource-filter-search")).toBeVisible();
await expect(page.getByTestId("datasource-filter-reset")).toBeVisible();
// 新建 sits above the table, right aligned; pagination is a page footer below the table.
const create = await page.getByTestId("datasource-create").boundingBox();
const table = await page.getByTestId("datasource-table").boundingBox();
const pager = await page.getByTestId("datasource-pagination").boundingBox();
const viewport = page.viewportSize();
expect(create && table && pager && viewport).toBeTruthy();
expect(create!.y + create!.height).toBeLessThanOrEqual(table!.y);
expect(create!.x + create!.width).toBeGreaterThan(table!.x + table!.width - 40);
expect(pager!.y).toBeGreaterThanOrEqual(table!.y + table!.height - 2);
// The list page itself does not scroll; only the table body does.
const listScrolls = await page
.getByTestId("datasource-list")
.evaluate((el) => el.scrollHeight > el.clientHeight + 1);
expect(listScrolls).toBe(false);
// Detail-style action footer is not used on the list.
await expect(page.getByTestId("datasource-footer")).toHaveCount(0);
// Disabled row: visible, 测试 disabled, no 停用, no "停用后不能测试" copy.
const off = page.getByTestId(`datasource-row-${ID_OFF}`);
await expect(off).toBeVisible();
await expect(off.getByTestId("row-test")).toBeDisabled();
await expect(off.getByTestId("row-test-why")).toHaveCount(0);
await expect(off).not.toContainText("停用后不能测试");
await expect(off.getByTestId("row-disable")).toHaveCount(0);
const live = page.getByTestId(`datasource-row-${ID_ONE}`);
await expect(live.getByTestId("row-edit")).toBeVisible();
await expect(live.getByTestId("row-test")).toBeEnabled();
await expect(live.getByTestId("row-disable")).toBeVisible();
await expect(page.locator("body")).not.toContainText("只读意图");
await expect(page.locator("body")).not.toContainText("正式版本进行删除");
await page.screenshot({ path: path.join(evidenceDir, "datasource-list.png"), fullPage: true });
});
test("empty list shows the empty state with 新建 above it", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockDatasources(page, []);
await page.goto("/#/datasources");
await expect(page.getByTestId("datasource-empty")).toContainText("还没有数据源");
await expect(page.getByTestId("datasource-create")).toBeVisible();
await page.screenshot({ path: path.join(evidenceDir, "datasource-empty.png"), fullPage: true });
});
test("detail: masked password, footer outside the scroll area, blank save omits password", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 520 });
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await page.getByTestId(`datasource-row-${ID_ONE}`).getByTestId("row-edit").click();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("详情");
await expect(crumb).not.toContainText("新建");
await expect(page.getByTestId("field-name").locator("input")).toHaveValue("产线工艺库");
// Password: el-input type=password with show-password, fixed mask, never the saved secret.
const password = page.getByTestId("field-password").locator("input");
await expect(password).toHaveAttribute("type", "password");
await expect(page.getByTestId("field-password").locator(".el-input__password")).toBeVisible();
await expect(password).toHaveValue("••••••••");
await expectNoSecretAnywhere(page);
// Footer: visible, centered, outside the scrolling body, and it does not move on scroll.
const footer = page.getByTestId("datasource-footer");
await expect(footer).toBeVisible();
await expect(page.getByTestId("datasource-scroll").getByTestId("datasource-footer")).toHaveCount(0);
for (const id of ["footer-save", "footer-test", "footer-disable", "footer-back"]) {
await expect(page.getByTestId(id)).toBeVisible();
}
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
await expect(page.getByTestId("footer-enable")).toHaveCount(0);
await expect(page.getByTestId("footer-save")).toHaveText("保存");
await expect(page.getByTestId("footer-test")).toHaveText("测试连接");
await expect(page.getByTestId("footer-disable")).toHaveText("停用");
await expect(page.getByTestId("footer-back")).toHaveText("返回列表");
const footerBox = (await footer.boundingBox())!;
const first = (await page.getByTestId("footer-save").boundingBox())!;
const last = (await page.getByTestId("footer-back").boundingBox())!;
const buttonsCenter = (first.x + last.x + last.width) / 2;
expect(Math.abs(buttonsCenter - (footerBox.x + footerBox.width / 2))).toBeLessThan(6);
const bodyScrolls = await page
.getByTestId("datasource-scroll")
.evaluate((el) => el.scrollHeight > el.clientHeight);
expect(bodyScrolls).toBe(true);
await page.getByTestId("datasource-scroll").evaluate((el) => el.scrollTo(0, el.scrollHeight));
const afterScroll = (await footer.boundingBox())!;
expect(afterScroll.y).toBeCloseTo(footerBox.y, 0);
expect(afterScroll.y + afterScroll.height).toBeLessThanOrEqual(520);
await page.getByTestId("datasource-scroll").evaluate((el) => el.scrollTo(0, 0));
// References are empty.
await expect(page.getByTestId("references-empty")).toHaveText("尚无引用");
await page.screenshot({ path: path.join(evidenceDir, "datasource-detail.png"), fullPage: true });
// Focus clears the mask. Leaving it blank restores it. A blank save omits the password.
await password.focus();
await expect(password).toHaveValue("");
await page.getByTestId("field-name").locator("input").focus();
await expect(password).toHaveValue("••••••••");
await page.getByTestId("field-host").locator("input").fill("db2.example.test");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toBeVisible();
const patch = mock.requests.find((item) => item.method === "PATCH");
expect(patch).toBeTruthy();
const body = patch!.body as Record<string, unknown>;
expect("password" in body).toBe(false);
expect(body.host).toBe("db2.example.test");
expect(body.circuit_failure_window_seconds).toBe(300);
expect(body.circuit_failure_threshold).toBe(3);
expect(body.circuit_open_cooldown_seconds).toBe(600);
expect(JSON.stringify(mock.requests)).not.toContain("••••");
await expectNoSecretAnywhere(page);
});
test("detail: a typed password is sent, and test shows testing then the category only", async ({
page,
}) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
mock.testOutcome = {
status: 400,
delayMs: 700,
body: fail(40000, DRIVER_TEXT, { category: "auth_failed" }),
};
// List「测试」opens the detail with ?test=1 and probes the saved connection (no detail button).
await page.goto("/#/datasources");
await page.getByTestId(`datasource-row-${ID_ONE}`).getByTestId("row-test").click();
await expect(page.getByTestId("test-running")).toContainText("测试中");
const result = page.getByTestId("test-result");
await expect(result).toBeVisible();
await expect(result).toHaveAttribute("data-category", "auth_failed");
await expect(result).toHaveAttribute("data-source", "saved");
await expect(page.getByTestId("test-source-note")).toContainText("最近测试");
await expect(result).toContainText("认证失败");
await expect(page.locator("body")).not.toContainText(DRIVER_TEXT);
await expectNoSecretAnywhere(page);
await page.screenshot({ path: path.join(evidenceDir, "datasource-test-auth.png"), fullPage: true });
mock.testOutcome = { status: 200, delayMs: 0, body: ok({ id: ID_ONE, category: "success", message: "m", last_test_at: null }) };
await page.goto(`/#/datasources/${ID_ONE}?test=1`);
await page.reload();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", "success");
for (const category of ["timeout", "unreachable", "rejected"]) {
mock.testOutcome = {
status: 400,
delayMs: 0,
body: fail(40000, DRIVER_TEXT, { category }),
};
await page.goto(`/#/datasources/${ID_ONE}?test=1`);
await page.reload();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", category);
}
await expect(page.locator("body")).not.toContainText(DRIVER_TEXT);
await page.getByTestId("field-password").locator("input").focus();
await page.getByTestId("field-password").locator("input").fill("typed-replacement-pw");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toBeVisible();
const patch = mock.requests.find((item) => item.method === "PATCH");
expect((patch!.body as Record<string, unknown>).password).toBe("typed-replacement-pw");
});
test("disabled detail: no saved-test button, 启用 replaces 停用, draft test stays", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto(`/#/datasources/${ID_OFF}`);
await expect(page.getByTestId("datasource-disabled-note")).toBeVisible();
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
await expect(page.getByTestId("footer-test")).toBeEnabled();
await expect(page.getByTestId("footer-disable")).toHaveCount(0);
await expect(page.getByTestId("footer-enable")).toHaveText("启用");
await page.screenshot({ path: path.join(evidenceDir, "datasource-disabled.png"), fullPage: true });
// Enable needs no prior test; the page stays on detail.
await page.getByTestId("footer-enable").click();
await expect(page.getByTestId("footer-disable")).toBeVisible();
await expect(page.getByTestId("footer-enable")).toHaveCount(0);
await expect(page.getByTestId("datasource-disabled-note")).toHaveCount(0);
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
const calls = mock.requests.filter((item) => item.method === "POST");
expect(calls.map((item) => item.pathname)).toEqual([`/datasources/${ID_OFF}/enable`]);
});
test("list: enable a disabled row without testing first", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
const off = page.getByTestId(`datasource-row-${ID_OFF}`);
await expect(off.getByTestId("row-enable")).toHaveText("启用");
await expect(off.getByTestId("row-test")).toBeDisabled();
await expect(page.getByTestId(`datasource-row-${ID_ONE}`).getByTestId("row-enable")).toHaveCount(0);
await off.getByTestId("row-enable").click();
await expect(off.getByTestId("row-disable")).toBeVisible();
await expect(off.getByTestId("row-enable")).toHaveCount(0);
await expect(off.getByTestId("row-test")).toBeEnabled();
expect(mock.requests.filter((item) => item.method === "POST").map((item) => item.pathname)).toEqual([
`/datasources/${ID_OFF}/enable`,
]);
await page.screenshot({ path: path.join(evidenceDir, "datasource-list-enabled.png"), fullPage: true });
});
test("circuit open: list and detail block the saved test and show the until time", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
const open = page.getByTestId(`datasource-row-${ID_OPEN}`);
await expect(page.getByTestId("datasource-table")).toContainText("熔断中");
await expect(open.getByTestId("row-test")).toBeDisabled();
await expect(open.getByTestId("row-test")).toHaveAttribute("title", /2026-11-18/);
await expect(open.getByTestId("row-enable")).toHaveCount(0);
await page.screenshot({ path: path.join(evidenceDir, "datasource-list-circuit.png"), fullPage: true });
await open.getByTestId("row-edit").click();
await expect(page.getByTestId("circuit-open-alert")).toContainText("2026-11-18");
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
await expect(page.getByTestId("footer-test")).toBeEnabled();
await expect(page.getByTestId("field-circuit-window").locator("input")).toHaveValue("120");
await expect(page.getByTestId("field-circuit-threshold").locator("input")).toHaveValue("5");
await expect(page.getByTestId("field-circuit-cooldown").locator("input")).toHaveValue("900");
await page.screenshot({ path: path.join(evidenceDir, "datasource-circuit-open.png"), fullPage: true });
// The list's test link does not run a saved probe while the circuit is open.
await page.goto(`/#/datasources/${ID_OPEN}?test=1`);
await page.reload();
await expect(page.getByTestId("circuit-open-alert")).toBeVisible();
expect(mock.requests.filter((item) => item.pathname.endsWith("/test"))).toHaveLength(0);
// Circuit parameters are saved with the rest of the form.
await page.getByTestId("field-circuit-window").locator("input").fill("60");
await page.getByTestId("field-circuit-threshold").locator("input").fill("4");
await page.getByTestId("field-circuit-cooldown").locator("input").fill("1200");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toBeVisible();
const patch = mock.requests.find((item) => item.method === "PATCH");
const body = patch!.body as Record<string, unknown>;
expect(body.circuit_failure_window_seconds).toBe(60);
expect(body.circuit_failure_threshold).toBe(4);
expect(body.circuit_open_cooldown_seconds).toBe(1200);
});
test("circuit open: list ?test=1 against an open circuit does not call /test", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
const target = mock.rows.find((item) => item.id === ID_ONE)!;
target.circuit_state = "open";
target.circuit_open_until = "2026-11-18T09:45:00+00:00";
await page.goto(`/#/datasources/${ID_ONE}?test=1`);
await page.reload();
await expect(page.getByTestId("circuit-open-alert")).toBeVisible();
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
expect(mock.requests.filter((item) => item.pathname.endsWith("/test"))).toHaveLength(0);
});
test("circuit parameters are validated on the detail page", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto(`/#/datasources/${ID_ONE}`);
const window = page.getByTestId("field-circuit-window").locator("input");
const threshold = page.getByTestId("field-circuit-threshold").locator("input");
const cooldown = page.getByTestId("field-circuit-cooldown").locator("input");
await window.fill("0");
await window.press("Tab");
await threshold.fill("101");
await threshold.press("Tab");
await cooldown.fill("86401");
await cooldown.press("Tab");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("field-circuit-window").locator(".el-form-item__error")).toContainText("1–86400");
await expect(page.getByTestId("field-circuit-threshold").locator(".el-form-item__error")).toContainText("1–100");
await expect(page.getByTestId("field-circuit-cooldown").locator(".el-form-item__error")).toContainText("1–86400");
expect(mock.requests.filter((item) => item.method === "PATCH")).toHaveLength(0);
await window.fill("86400");
await window.press("Tab");
await threshold.fill("100");
await threshold.press("Tab");
await cooldown.fill("1");
await cooldown.press("Tab");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toBeVisible();
const body = mock.requests.find((item) => item.method === "PATCH")!.body as Record<string, unknown>;
expect([body.circuit_failure_window_seconds, body.circuit_failure_threshold, body.circuit_open_cooldown_seconds]).toEqual([
86400, 100, 1,
]);
});
test("create form validation: required fields, port range, host has no format rule", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources/new");
await expect(page.getByTestId("datasource-circuit")).toHaveCount(0);
await page.getByTestId("footer-save").click();
for (const field of ["name", "host", "database", "username", "password"]) {
await expect(page.getByTestId(`field-${field}`).locator(".el-form-item__error")).toContainText("必填");
}
expect(mock.requests).toHaveLength(0);
// A spaces-only host is still empty.
await page.getByTestId("field-host").locator("input").fill(" ");
await page.getByTestId("field-host").locator("input").press("Tab");
await expect(page.getByTestId("field-host").locator(".el-form-item__error")).toContainText("必填");
// Port: empty and out of range are both refused.
const port = page.getByTestId("field-port").locator("input");
await port.fill("");
await port.press("Tab");
await expect(page.getByTestId("field-port").locator(".el-form-item__error")).toContainText("必填");
await port.fill("70000");
await port.press("Tab");
await expect(page.getByTestId("field-port").locator(".el-form-item__error")).toContainText("1–65535");
await port.fill("0");
await port.press("Tab");
await expect(page.getByTestId("field-port").locator(".el-form-item__error")).toContainText("1–65535");
await page.screenshot({ path: path.join(evidenceDir, "datasource-validation.png"), fullPage: true });
// Host takes any non-blank text: no hostname regex.
await page.getByTestId("field-name").locator("input").fill("宽松主机库");
await page.getByTestId("field-host").locator("input").fill("not a hostname_at all");
await port.fill("65535");
await port.press("Tab");
await page.getByTestId("field-database").locator("input").fill("d");
await page.getByTestId("field-username").locator("input").fill("u");
await page.getByTestId("field-password").locator("input").fill("typed-pw");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toContainText("宽松主机库");
const post = mock.requests.find((item) => item.method === "POST")!.body as Record<string, unknown>;
expect(post.host).toBe("not a hostname_at all");
expect(post.port).toBe(65535);
expect(JSON.stringify(post)).not.toContain("circuit");
});
test("create: draft test works before saving and never saves or leaks the password", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources/new");
await expect(page.getByTestId("footer-test")).toHaveText("测试连接");
await expect(page.getByTestId("test-none")).toContainText("保存前");
// Missing fields and a missing password stop the test before any request.
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("field-host").locator(".el-form-item__error")).toContainText("必填");
await expect(page.getByTestId("field-password").locator(".el-form-item__error")).toContainText("必填");
expect(mock.requests).toHaveLength(0);
await page.getByTestId("field-host").locator("input").fill("draft.example.test");
await page.getByTestId("field-database").locator("input").fill("draft_demo");
await page.getByTestId("field-username").locator("input").fill("readonly_demo");
await page.getByTestId("footer-test").click();
expect(mock.requests).toHaveLength(0);
await page.getByTestId("field-password").locator("input").fill(SAVED_SECRET);
mock.draftOutcome = {
status: 400,
delayMs: 500,
body: fail(40000, DRIVER_TEXT, { category: "auth_failed" }),
};
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("test-running")).toContainText("测试中");
const result = page.getByTestId("test-result");
await expect(result).toHaveAttribute("data-category", "auth_failed");
await expect(result).toHaveAttribute("data-source", "draft");
await expect(page.getByTestId("test-source-note")).toContainText("草稿测试");
await expect(page.getByTestId("test-source-note")).toContainText("不会保存");
const draft = mock.requests.filter((item) => item.pathname === "/datasources/test-draft");
expect(draft).toHaveLength(1);
expect(draft[0].body).toEqual({
engine: "postgresql",
host: "draft.example.test",
port: 5432,
database_name: "draft_demo",
username: "readonly_demo",
password: SAVED_SECRET,
});
// Nothing was saved: no create call and no saved-record test.
expect(mock.requests.filter((item) => item.pathname !== "/datasources/test-draft")).toHaveLength(0);
expect(mock.rows.some((item) => item.name === "x")).toBe(false);
await expect(page.locator("body")).not.toContainText(DRIVER_TEXT);
await expectNoSecretAnywhere(page);
mock.draftOutcome = { status: 200, delayMs: 0, body: ok({ category: "success", message: "m" }) };
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", "success");
await page.screenshot({ path: path.join(evidenceDir, "datasource-draft-test.png"), fullPage: true });
});
test("edit: draft test with a blank password uses the stored secret via datasource_id", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto(`/#/datasources/${ID_ONE}`);
await page.getByTestId("field-host").locator("input").fill("changed.example.test");
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-source", "draft");
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", "success");
const draft = mock.requests.filter((item) => item.pathname === "/datasources/test-draft");
expect(draft).toHaveLength(1);
const body = draft[0].body as Record<string, unknown>;
expect(body.datasource_id).toBe(ID_ONE);
expect(body.host).toBe("changed.example.test");
expect("password" in body).toBe(false);
expect(JSON.stringify(body)).not.toContain("••••");
// The draft did not touch the saved record or call the saved test.
expect(mock.requests.filter((item) => item.pathname.endsWith(`${ID_ONE}/test`))).toHaveLength(0);
expect(mock.requests.filter((item) => item.method !== "GET" && item.pathname !== "/datasources/test-draft")).toHaveLength(0);
expect(mock.rows.find((item) => item.id === ID_ONE)!.host).toBe("db.example.test");
await expectNoSecretAnywhere(page);
// A typed password goes along with the id.
await page.getByTestId("field-password").locator("input").focus();
await page.getByTestId("field-password").locator("input").fill("typed-replacement-pw");
await page.getByTestId("footer-test").click();
await expect.poll(() => mock.requests.filter((item) => item.pathname === "/datasources/test-draft").length).toBe(2);
const second = mock.requests.filter((item) => item.pathname === "/datasources/test-draft")[1].body as Record<string, unknown>;
expect(second.password).toBe("typed-replacement-pw");
expect(second.datasource_id).toBe(ID_ONE);
});
test("a draft test is also available on a disabled datasource", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto(`/#/datasources/${ID_OFF}`);
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-source", "draft");
expect(mock.requests.filter((item) => item.pathname === "/datasources/test-draft")).toHaveLength(1);
});
test("list test action opens the detail and runs the test once", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await page.getByTestId(`datasource-row-${ID_ONE}`).getByTestId("row-test").click();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", "success");
expect(mock.requests.filter((item) => item.pathname.endsWith("/test")).length).toBe(1);
});
test("create: breadcrumb, empty password, three engines, footer, payload", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await page.getByTestId("datasource-create").click();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("新建");
await expect(crumb).not.toContainText("详情");
const password = page.getByTestId("field-password").locator("input");
await expect(password).toHaveValue("");
await expect(password).toHaveAttribute("type", "password");
await expect(page.locator("body")).not.toContainText("只读意图");
await expect(page.locator("body")).not.toContainText("正式版本进行删除");
// Footer: 保存, 测试连接 (draft) and 返回列表; no saved-record actions yet.
await expect(page.getByTestId("footer-save")).toBeVisible();
await expect(page.getByTestId("footer-test")).toBeVisible();
await expect(page.getByTestId("footer-back")).toBeVisible();
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
await expect(page.getByTestId("footer-enable")).toHaveCount(0);
await expect(page.getByTestId("footer-disable")).toHaveCount(0);
// Engines: exactly the three supported ones.
await page.getByTestId("field-engine").click();
const options = page.locator(".el-select-dropdown__item");
await expect(options).toHaveText(["PostgreSQL", "MySQL", "SQL Server"]);
await options.filter({ hasText: "MySQL" }).click();
await expect(page.getByTestId("field-port").locator("input")).toHaveValue("3306");
await page.screenshot({ path: path.join(evidenceDir, "datasource-create.png"), fullPage: true });
// A blank form does not submit, and a missing password blocks create.
await page.getByTestId("footer-save").click();
await expect(page.locator(".el-form-item__error").first()).toBeVisible();
expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0);
await page.getByTestId("field-name").locator("input").fill("新建演示库");
await page.getByTestId("field-host").locator("input").fill("new.example.test");
await page.getByTestId("field-database").locator("input").fill("new_demo");
await page.getByTestId("field-username").locator("input").fill("readonly_demo");
await page.getByTestId("footer-save").click();
expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0);
await password.fill(SAVED_SECRET);
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toContainText("新建演示库");
const post = mock.requests.find((item) => item.method === "POST");
const body = post!.body as Record<string, unknown>;
expect(body.password).toBe(SAVED_SECRET);
expect(body.engine).toBe("mysql");
expect("read_only_intent" in body).toBe(false);
await expectNoSecretAnywhere(page);
});
test("duplicate name shows the API reason on the form", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockDatasources(page);
await page.route(/\/datasources$/, async (route) => {
if (route.request().method() === "POST") {
await route.fulfill({
status: 409,
contentType: "application/json",
body: fail(40900, "Conflict", { reason: "duplicate_name" }),
});
return;
}
await route.fallback();
});
await page.goto("/#/datasources/new");
await page.getByTestId("field-name").locator("input").fill("产线工艺库");
await page.getByTestId("field-host").locator("input").fill("x.example.test");
await page.getByTestId("field-database").locator("input").fill("d");
await page.getByTestId("field-username").locator("input").fill("u");
await page.getByTestId("field-password").locator("input").fill("typed-pw");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-save-error")).toContainText("名称已存在");
});
test("a viewer sees 无法进入数据源 and no datasource request is made", async ({ page }) => {
await signIn(page, ["watchman-viewer"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await expect(page.getByTestId("datasource-denied")).toContainText("无法进入数据源");
await expect(page.getByTestId("breadcrumb")).toContainText("数据源");
await expect(page.getByTestId("datasource-table")).toHaveCount(0);
await expect(page.getByTestId("datasource-create")).toHaveCount(0);
await page.screenshot({ path: path.join(evidenceDir, "datasource-denied-viewer.png"), fullPage: true });
// Deep links are gated too.
await page.goto(`/#/datasources/${ID_ONE}`);
await expect(page.getByTestId("datasource-denied")).toBeVisible();
await page.goto("/#/datasources/new");
await expect(page.getByTestId("datasource-denied")).toBeVisible();
await expect(page.getByTestId("breadcrumb")).not.toContainText("新建");
expect(mock.requests).toHaveLength(0);
});
test("an operator is denied as well", async ({ page }) => {
await signIn(page, ["watchman-operator"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await expect(page.getByTestId("datasource-denied")).toBeVisible();
expect(mock.requests).toHaveLength(0);
});
});