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/M04/ui", ); // Synthetic data only. The API is mocked; no source database or secret is involved. const SERVER_TEXT = "FATAL: driver said something private"; type Draft = { sql_template: string; param_schema: Record[]; output_schema: Record[]; allowed_identifiers: string[]; timeout_ms: number; max_rows: number; }; type Def = { id: string; name: string; description: string | null; datasource_id: string; enabled: boolean; current_version_no: number | null; latest_version_no: number | null; latest_published_version_no: number | null; created_at: string; updated_at: string; current: Draft; }; type Ver = Draft & { id: string; definition_id: string; version_no: number; published_at: string; published_by: string; }; const DS_ONE = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; const DS_TWO = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; const DS_OFF = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; const Q_ONE = "11111111-1111-4111-8111-111111111111"; const Q_TWO = "22222222-2222-4222-8222-222222222222"; const Q_OFF = "33333333-3333-4333-8333-333333333333"; const Q_NEW = "55555555-5555-4555-8555-555555555555"; function datasourceRows() { const base = { description: null, kind: "database", engine: "postgresql", host: "db.example.test", port: 5432, database_name: "process_demo", username: "readonly_demo", secret_configured: true, read_only_intent: 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", }; return [ { ...base, id: DS_ONE, name: "产线工艺库", enabled: true }, { ...base, id: DS_TWO, name: "设备台账库", enabled: true }, { ...base, id: DS_OFF, name: "历史归档库", enabled: false }, ]; } const SQL_ONE = "SELECT lot_no, temperature, phone\nFROM process_readings\nWHERE line_code = :line_code"; function draftOne(): Draft { return { sql_template: SQL_ONE, param_schema: [ { name: "line_code", type: "string", required: true }, { name: "min_temp", type: "number", required: false, default: 0 }, ], output_schema: [ { name: "lot_no", type: "string" }, { name: "temperature", type: "number" }, { name: "phone", type: "string" }, ], allowed_identifiers: ["process_readings"], timeout_ms: 5000, max_rows: 200, }; } function def(overrides: Partial & Pick): Def { return { description: "示例(虚构)", datasource_id: DS_ONE, enabled: true, current_version_no: 1, latest_version_no: 1, latest_published_version_no: 1, created_at: "2026-11-17T01:00:00+00:00", updated_at: "2026-11-18T01:40:00+00:00", current: draftOne(), ...overrides, }; } function seedDefs(): Def[] { return [ def({ id: Q_ONE, name: "产线温度采样", current_version_no: 1, latest_version_no: 1 }), def({ id: Q_TWO, name: "设备停机记录", datasource_id: DS_TWO, current: { ...draftOne(), sql_template: "SELECT 1", param_schema: [], output_schema: [], allowed_identifiers: [], }, }), def({ id: Q_OFF, name: "质检不良统计", enabled: false }), ]; } function seedVersions(): Ver[] { return [ { ...draftOne(), id: "v-1", definition_id: Q_ONE, version_no: 1, published_at: "2026-11-18T01:40:00+00:00", published_by: "admin.demo", }, ]; } function ok(data: unknown): string { return JSON.stringify({ success: true, data, request_id: "pw-q" }); } function fail(code: number, message: string, details: Record = {}): string { return JSON.stringify({ success: false, error: { code, message, details, retryable: false }, request_id: "pw-q", }); } type Outcome = { status: number; body: string; delayMs: number }; type Mock = { defs: Def[]; versions: Ver[]; requests: { method: string; pathname: string; body: unknown }[]; preview: Outcome; }; const SUCCESS_BODY = ok({ id: Q_ONE, version_no: 1, source: "current", status: "success", message: "query succeeded", columns: ["lot_no", "temperature", "phone"], rows: [ { lot_no: "LOT-1001", temperature: 71.2, phone: "***" }, { lot_no: "LOT-1002", temperature: 72, phone: null }, ], row_count: 2, masked_columns: ["phone"], }); function previewBody(data: Record): string { return ok({ id: Q_ONE, version_no: 1, source: "current", message: "m", ...data }); } async function signIn(page: Page, roles: string[]): Promise { 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" }), }); }); } function summary(row: Def): Omit { const { current: _current, ...rest } = row; return rest; } function versionSummary(row: Ver) { return { id: row.id, definition_id: row.definition_id, version_no: row.version_no, published_at: row.published_at, published_by: row.published_by, }; } /** Mocks /queries and the datasource list. Page source files under /src/... never match. */ async function mockApi(page: Page, defs: Def[] = seedDefs(), versions: Ver[] = seedVersions()): Promise { const mock: Mock = { defs, versions, requests: [], preview: { status: 200, delayMs: 0, body: SUCCESS_BODY }, }; const sources = datasourceRows(); const matcher = (url: URL) => /^\/datasources$/.test(url.pathname) || /^\/queries(\/[^/]+(\/(enable|disable|preview|references|versions(\/\d+(\/(preview|activate))?)?))?)?$/.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.postData() ? request.postDataJSON() : null; } 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); if (parts[0] === "datasources") { const page = Number(url.searchParams.get("page") || "1"); const pageSize = Number(url.searchParams.get("page_size") || "20"); return json( 200, ok({ items: sources, total: sources.length, page, page_size: pageSize }), ); } if (parts.length === 1) { if (method === "GET") { const name = (url.searchParams.get("name") || "").trim().toLowerCase(); const datasourceId = url.searchParams.get("datasource_id") || ""; 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") || "updated_at"; const sortOrder = url.searchParams.get("sort_order") || "desc"; let rows = mock.defs.map(summary); if (name) { rows = rows.filter((item) => item.name.toLowerCase().includes(name)); } if (datasourceId) { rows = rows.filter((item) => item.datasource_id === datasourceId); } 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 = [...rows].sort((a, b) => { const av = (a as Record)[sortBy === "datasource_name" ? "datasource_id" : sortBy]; const bv = (b as Record)[sortBy === "datasource_name" ? "datasource_id" : 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 payload = body as Record; if (mock.defs.some((item) => item.name === payload.name)) { return json(409, fail(40000, "Query name already exists", { reason: "duplicate_name" })); } const content = { sql_template: String(payload.sql_template), param_schema: payload.param_schema as Record[], output_schema: payload.output_schema as Record[], allowed_identifiers: payload.allowed_identifiers as string[], timeout_ms: Number(payload.timeout_ms), max_rows: Number(payload.max_rows), }; const created = def({ id: Q_NEW, name: String(payload.name), description: (payload.description as string | null) ?? null, datasource_id: String(payload.datasource_id), current: content, current_version_no: 1, latest_version_no: 1, latest_published_version_no: 1, }); mock.defs.push(created); mock.versions.push({ ...content, id: `v-${Q_NEW}-1`, definition_id: Q_NEW, version_no: 1, published_at: "2026-11-18T02:00:00+00:00", published_by: "admin.demo", }); return json(200, ok({ ...summary(created), current: created.current })); } const found = mock.defs.find((item) => item.id === parts[1]); if (!found) { return json(404, fail(40000, "Query not found", { reason: "not_found" })); } const full = () => ok({ ...summary(found), current: found.current }); const action = parts[2]; if (!action) { if (method === "GET") { return json(200, full()); } const patch = body as Record; if (mock.defs.some((item) => item.name === patch.name && item.id !== found.id)) { return json(409, fail(40000, "Query name already exists", { reason: "duplicate_name" })); } if ( "sql_template" in patch || "param_schema" in patch || "output_schema" in patch || "timeout_ms" in patch || "max_rows" in patch ) { return json(400, fail(40000, "use save version", { reason: "use_save_version" })); } found.name = String(patch.name ?? found.name); found.description = (patch.description as string | null) ?? null; found.datasource_id = String(patch.datasource_id ?? found.datasource_id); return json(200, full()); } if (action === "enable" || action === "disable") { found.enabled = action === "enable"; return json(200, full()); } if (action === "references") { return json(200, ok({ id: found.id, items: [] })); } const own = mock.versions .filter((item) => item.definition_id === found.id) .sort((a, b) => b.version_no - a.version_no); if (action === "versions" && parts.length === 3) { if (method === "POST") { const payload = body as Record; const next = (found.latest_version_no ?? 0) + 1; const content = { sql_template: String(payload.sql_template), param_schema: (payload.param_schema as Record[]) ?? [], output_schema: (payload.output_schema as Record[]) ?? [], allowed_identifiers: (payload.allowed_identifiers as string[]) ?? [], timeout_ms: Number(payload.timeout_ms ?? 10000), max_rows: Number(payload.max_rows ?? 100), }; const version: Ver = { ...content, id: `v-${found.id}-${next}`, definition_id: found.id, version_no: next, published_at: "2026-11-18T02:00:00+00:00", published_by: "admin.demo", }; mock.versions.push(version); found.current = content; found.current_version_no = next; found.latest_version_no = next; found.latest_published_version_no = next; return json(200, ok(version)); } return json(200, ok({ id: found.id, items: own.map(versionSummary) })); } if (action === "versions" && parts.length === 4) { const frozen = own.find((item) => item.version_no === Number(parts[3])); return frozen ? json(200, ok(frozen)) : json(404, fail(40000, "Query version not found", { reason: "not_found" })); } if (action === "versions" && parts[4] === "activate") { const no = Number(parts[3]); const frozen = own.find((item) => item.version_no === no); if (!frozen) { return json(404, fail(40000, "Query version not found", { reason: "not_found" })); } found.current_version_no = no; found.current = { sql_template: frozen.sql_template, param_schema: frozen.param_schema, output_schema: frozen.output_schema, allowed_identifiers: frozen.allowed_identifiers, timeout_ms: frozen.timeout_ms, max_rows: frozen.max_rows, }; return json(200, full()); } if (action === "preview" || parts[4] === "preview") { if (!found.enabled) { return json(409, fail(40000, "Query is disabled", { reason: "disabled" })); } await new Promise((resolve) => setTimeout(resolve, mock.preview.delayMs)); return json(mock.preview.status, mock.preview.body); } return json(404, fail(40000, "Not found", { reason: "not_found" })); }); return mock; } async function pickDatasource(page: Page, name: string): Promise { await page.getByTestId("field-datasource").locator(".el-select__wrapper").click(); await page.getByRole("option", { name }).click(); } async function confirmDialog(page: Page): Promise { await page.locator(".el-message-box__btns .el-button--primary").click(); } async function fillCreateForm(page: Page, name: string): Promise { await page.getByTestId("field-name").locator("input").fill(name); await pickDatasource(page, "设备台账库"); await page.getByTestId("field-sql").locator("textarea").fill("SELECT lot_no FROM {{process_readings}} WHERE line_code = :line_code"); await page.getByTestId("param-add").click(); await page.getByTestId("param-name").fill("line_code"); await page.getByTestId("output-add").click(); await page.getByTestId("output-name").fill("lot_no"); await page.getByTestId("identifier-input").fill("process_readings"); await page.getByTestId("identifier-add").click(); } test.describe("queries console", () => { test("a viewer and an operator see 无法进入查询 and no request is made", async ({ page }) => { await signIn(page, ["watchman-viewer"]); const mock = await mockApi(page); await page.goto("/#/queries"); await expect(page.getByTestId("query-denied")).toContainText("无法进入查询"); await expect(page.getByTestId("breadcrumb")).toContainText("查询"); await expect(page.getByTestId("query-table")).toHaveCount(0); await expect(page.getByTestId("query-create")).toHaveCount(0); await page.screenshot({ path: path.join(evidenceDir, "query-denied-viewer.png"), fullPage: true }); // Deep links are gated too, and the breadcrumb stays at the list level. await page.goto(`/#/queries/${Q_ONE}`); await expect(page.getByTestId("query-denied")).toBeVisible(); await page.goto("/#/queries/new"); await expect(page.getByTestId("query-denied")).toBeVisible(); await expect(page.getByTestId("breadcrumb")).not.toContainText("新建"); await page.goto(`/#/queries/${Q_ONE}/versions/1`); await expect(page.getByTestId("query-denied")).toBeVisible(); await expect(page.getByTestId("breadcrumb")).not.toContainText("版本"); expect(mock.requests).toHaveLength(0); await page.unroute("**/auth/me"); await signIn(page, ["watchman-operator"]); await page.goto("/#/queries"); await page.reload(); await expect(page.getByTestId("query-denied")).toBeVisible(); expect(mock.requests).toHaveLength(0); }); test("empty list shows the empty state with 新建 above it", async ({ page }) => { await signIn(page, ["watchman-admin"]); await mockApi(page, [], []); await page.goto("/#/queries"); await expect(page.getByTestId("query-empty")).toContainText("还没有查询"); await expect(page.getByTestId("query-create")).toBeVisible(); const create = (await page.getByTestId("query-create").boundingBox())!; const empty = (await page.getByTestId("query-empty").boundingBox())!; expect(create.y + create.height).toBeLessThanOrEqual(empty.y); await page.screenshot({ path: path.join(evidenceDir, "query-empty.png"), fullPage: true }); }); test("admin list: breadcrumb, 新建 above the table, columns, disabled row", async ({ page }) => { await signIn(page, ["watchman-admin"]); await mockApi(page); await page.goto("/#/queries"); await expect(page.getByTestId("query-table")).toBeVisible(); await expect(page.getByTestId("nav-queries")).toBeVisible(); const crumb = page.getByTestId("breadcrumb"); await expect(crumb).toContainText("预警平台"); await expect(crumb).toContainText("查询"); await expect(crumb).not.toContainText("新建"); await expect(crumb).not.toContainText("详情"); // No page title repeated under the breadcrumb. await expect(page.getByRole("heading")).toHaveCount(0); await expect(page.getByTestId("side-logo")).toBeVisible(); await expect(page.getByTestId("side-user").getByTestId("shell-welcome")).toBeVisible(); await expect(page.getByTestId("side-user").getByTestId("logout")).toBeVisible(); for (const header of ["名称", "数据源", "状态", "当前版本", "更新时间", "操作"]) { await expect(page.locator(".el-table__header").getByText(header, { exact: true })).toBeVisible(); } const table = page.getByTestId("query-table"); await expect(table).toContainText("产线温度采样"); await expect(table).toContainText("产线工艺库"); await expect(table).toContainText("v1"); await expect(table).toContainText("2026-11-18"); await expect(page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-switch-version")).toBeVisible(); await expect(page.getByTestId("query-pagination")).toBeVisible(); const create = (await page.getByTestId("query-create").boundingBox())!; const box = (await table.boundingBox())!; expect(create.y + create.height).toBeLessThanOrEqual(box.y); expect(create.x + create.width).toBeGreaterThan(box.x + box.width - 40); await expect(page.getByTestId("query-footer")).toHaveCount(0); await expect(page.getByTestId("query-list-toolbar")).toBeVisible(); await expect(page.getByTestId("query-filter-name")).toBeVisible(); await expect(page.getByTestId("query-filter-datasource")).toBeVisible(); await expect(page.getByTestId("query-filter-status")).toBeVisible(); await expect(page.getByTestId("query-filter-search")).toBeVisible(); await expect(page.getByTestId("query-filter-reset")).toBeVisible(); // Draft filters do not apply until 查询 is clicked. await page.getByTestId("query-filter-name").getByRole("textbox").fill("温度"); await expect(table).toContainText("质检不良统计"); await page.getByTestId("query-filter-search").click(); await expect(table).toContainText("产线温度采样"); await expect(table).not.toContainText("质检不良统计"); await page.getByTestId("query-filter-reset").click(); await expect(table).toContainText("质检不良统计"); // Disabled row: visible, 预览 disabled with a title, 打开 still works. const off = page.getByTestId(`query-row-${Q_OFF}`); await expect(off).toBeVisible(); await expect(off.getByTestId("row-preview")).toBeDisabled(); await expect(off.getByTestId("row-preview")).toHaveAttribute("title", "已停用,不能预览"); await expect(off.getByTestId("row-open")).toBeEnabled(); const live = page.getByTestId(`query-row-${Q_ONE}`); await expect(live.getByTestId("row-preview")).toBeEnabled(); await expect(page.locator("body")).not.toContainText("正式版本进行删除"); await expect(page.locator("body")).not.toContainText("原型"); await page.screenshot({ path: path.join(evidenceDir, "query-list.png"), fullPage: true }); }); test("create: footer, validation, then save creates v1 and opens the detail", async ({ page, }) => { await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); await page.goto("/#/queries"); await page.getByTestId("query-create").click(); const crumb = page.getByTestId("breadcrumb"); await expect(crumb).toContainText("新建"); await expect(crumb).not.toContainText("详情"); await expect(page.getByTestId("basic-sub")).toContainText("新建"); await expect(page.getByTestId("versions-create-note")).toBeVisible(); // Create footer: 返回列表, 保存 live; 试跑预览 disabled until saved. No publish. await expect(page.getByTestId("footer-back")).toHaveText("返回列表"); await expect(page.getByTestId("footer-save")).toHaveText("保存"); await expect(page.getByTestId("footer-publish")).toHaveCount(0); await expect(page.getByTestId("footer-preview")).toBeDisabled(); await expect(page.getByTestId("footer-enable")).toHaveCount(0); await expect(page.getByTestId("footer-disable")).toHaveCount(0); await expect(page.getByTestId("preview-need-save")).toBeVisible(); // SQL textarea is monospace. const font = await page .getByTestId("field-sql") .locator("textarea") .evaluate((el) => getComputedStyle(el).fontFamily); expect(font.toLowerCase()).toMatch(/mono|consolas/); // A blank form does not submit. await page.getByTestId("footer-save").click(); for (const field of ["name", "datasource", "sql"]) { await expect(page.getByTestId(`field-${field}`).locator(".el-form-item__error")).toBeVisible(); } expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0); // Undeclared SQL parameter is flagged live; an invalid parameter name and a limit are refused. await page.getByTestId("field-sql").locator("textarea").fill("SELECT 1 WHERE a = :line_code AND b = :since"); await expect(page.getByTestId("chip-undeclared")).toHaveCount(2); await expect(page.getByTestId("chip-undeclared").filter({ hasText: ":since 未声明" })).toBeVisible(); await page.getByTestId("param-add").click(); await page.getByTestId("param-name").fill("1bad"); await page.getByTestId("footer-save").click(); await expect(page.getByTestId("field-params").locator(".el-form-item__error")).toContainText("参数名不合法"); await page.getByTestId("param-name").fill("line_code"); await page.getByTestId("field-timeout").locator("input").fill("300001"); await page.getByTestId("field-timeout").locator("input").press("Tab"); await expect(page.getByTestId("field-timeout").locator(".el-form-item__error")).toContainText("1–300000"); await page.getByTestId("field-max-rows").locator("input").fill("0"); await page.getByTestId("field-max-rows").locator("input").press("Tab"); await expect(page.getByTestId("field-max-rows").locator(".el-form-item__error")).toContainText("1–10000"); await page.screenshot({ path: path.join(evidenceDir, "query-create-validation.png"), fullPage: true }); expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0); // Happy path. await page.reload(); await fillCreateForm(page, "新建演示查询"); await page.getByTestId("field-timeout").locator("input").fill("5000"); await page.getByTestId("field-max-rows").locator("input").fill("50"); await page.screenshot({ path: path.join(evidenceDir, "query-create.png"), fullPage: true }); await page.getByTestId("footer-save").click(); // Saved: the detail page opens with v1 current and no publish button. await expect(page.getByTestId("breadcrumb")).toContainText("详情"); await expect(page.getByTestId("field-name").locator("input")).toHaveValue("新建演示查询"); await expect(page.getByTestId("footer-publish")).toHaveCount(0); await expect(page.getByTestId("footer-disable")).toBeVisible(); await expect(page.getByTestId("footer-preview")).toBeEnabled(); await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1"); const post = mock.requests.find((item) => item.method === "POST" && item.pathname === "/queries"); expect(post).toBeTruthy(); const body = post!.body as Record; expect(Object.keys(body).sort()).toEqual([ "allowed_identifiers", "datasource_id", "description", "max_rows", "name", "output_schema", "param_schema", "sql_template", "timeout_ms", ]); expect(body.name).toBe("新建演示查询"); expect(body.datasource_id).toBe(DS_TWO); expect(body.param_schema).toEqual([{ name: "line_code", type: "string", required: true }]); expect(body.output_schema).toEqual([{ name: "lot_no", type: "string" }]); expect(body.allowed_identifiers).toEqual(["process_readings"]); expect(body.timeout_ms).toBe(5000); expect(body.max_rows).toBe(50); }); test("a disabled datasource cannot be picked", async ({ page }) => { await signIn(page, ["watchman-admin"]); await mockApi(page); await page.goto("/#/queries/new"); await page.getByTestId("field-datasource").locator(".el-select__wrapper").click(); await expect(page.getByRole("option", { name: /历史归档库/ })).toHaveClass(/is-disabled/); await expect(page.getByRole("option", { name: /产线工艺库/ })).not.toHaveClass(/is-disabled/); }); test("duplicate name shows the API reason on the form", async ({ page }) => { await signIn(page, ["watchman-admin"]); await mockApi(page); await page.goto("/#/queries/new"); await fillCreateForm(page, "产线温度采样"); await page.getByTestId("footer-save").click(); await expect(page.getByTestId("query-save-error")).toContainText("名称已存在"); await expect(page.getByTestId("query-save-error")).not.toContainText("Query name already exists"); }); test("detail: footer outside the scroll area, centered, in order; sections present", async ({ page }) => { await page.setViewportSize({ width: 1280, height: 520 }); await signIn(page, ["watchman-admin"]); await mockApi(page); await page.goto("/#/queries"); await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-open").click(); const crumb = page.getByTestId("breadcrumb"); await expect(crumb).toContainText("详情"); await expect(crumb).not.toContainText("新建"); await expect(page.getByRole("heading", { level: 1 })).toHaveCount(0); await expect(page.getByTestId("field-name").locator("input")).toHaveValue("产线温度采样"); await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1"); await expect(page.getByTestId("status-tag")).toHaveText("启用"); await expect(page.getByTestId("param-name").first()).toHaveValue("line_code"); await expect(page.getByTestId("params-table").locator(".el-table__row").nth(1).getByTestId("param-default")).toHaveValue("0"); await expect(page.getByTestId("output-name").nth(1)).toHaveValue("temperature"); await expect(page.getByTestId("identifier-tag")).toHaveText("process_readings"); await expect(page.getByTestId("field-timeout").locator("input")).toHaveValue("5000"); await expect(page.getByTestId("references-empty")).toHaveText("尚无引用"); await expect(page.getByTestId("versions-table")).toContainText("v1"); await expect(page.getByTestId("versions-table")).toContainText("admin.demo"); await expect(page.getByTestId("versions-table")).toContainText("当前生效"); const footer = page.getByTestId("query-footer"); await expect(footer).toBeVisible(); await expect(page.getByTestId("query-scroll").getByTestId("query-footer")).toHaveCount(0); const order = ["footer-back", "footer-save", "footer-disable", "footer-preview"]; const labels = ["返回列表", "保存", "停用", "试跑预览"]; const xs: number[] = []; for (const [index, id] of order.entries()) { await expect(page.getByTestId(id)).toHaveText(labels[index]); xs.push((await page.getByTestId(id).boundingBox())!.x); } expect([...xs].sort((a, b) => a - b)).toEqual(xs); await expect(page.getByTestId("footer-publish")).toHaveCount(0); await expect(page.getByTestId("versions-block").getByRole("button", { name: "发布" })).toHaveCount(0); const footerBox = (await footer.boundingBox())!; const first = (await page.getByTestId("footer-back").boundingBox())!; const last = (await page.getByTestId("footer-preview").boundingBox())!; expect(Math.abs((first.x + last.x + last.width) / 2 - (footerBox.x + footerBox.width / 2))).toBeLessThan(6); expect(await page.getByTestId("query-scroll").evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true); await page.getByTestId("query-scroll").evaluate((el) => el.scrollTo(0, el.scrollHeight)); const after = (await footer.boundingBox())!; expect(after.y).toBeCloseTo(footerBox.y, 0); expect(after.y + after.height).toBeLessThanOrEqual(520); await page.getByTestId("query-scroll").evaluate((el) => el.scrollTo(0, 0)); await page.screenshot({ path: path.join(evidenceDir, "query-detail.png"), fullPage: true }); }); test("unsaved edits disable the preview until saved; metadata save sends PATCH", async ({ page }) => { await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); await page.goto(`/#/queries/${Q_ONE}`); await expect(page.getByTestId("footer-preview")).toBeEnabled(); await expect(page.getByTestId("preview-dirty")).toHaveCount(0); await page.getByTestId("field-name").locator("input").fill("产线温度采样(改)"); await expect(page.getByTestId("preview-dirty")).toContainText("未保存"); await expect(page.getByTestId("footer-preview")).toBeDisabled(); await expect(page.getByTestId("footer-preview")).toHaveAttribute("title", /先保存/); await page.getByTestId("footer-save").click(); await expect(page.getByTestId("preview-dirty")).toHaveCount(0); await expect(page.getByTestId("footer-preview")).toBeEnabled(); const patch = mock.requests.find((item) => item.method === "PATCH"); expect((patch!.body as Record).name).toBe("产线温度采样(改)"); expect(patch!.pathname).toBe(`/queries/${Q_ONE}`); expect(mock.requests.filter((item) => item.pathname.endsWith("/publish"))).toHaveLength(0); }); test("saving content creates a new version; version page is read-only and can activate", async ({ page }) => { await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); await page.goto(`/#/queries/${Q_ONE}`); await page.getByTestId("field-sql").locator("textarea").fill(`${SQL_ONE}\n-- v2`); await page.getByTestId("footer-save").click(); await expect(page.getByTestId("versions-table")).toContainText("v2"); await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v2"); const saveVersion = mock.requests.find( (item) => item.method === "POST" && item.pathname === `/queries/${Q_ONE}/versions`, ); expect(saveVersion).toBeTruthy(); expect((saveVersion!.body as Record).sql_template).toContain("-- v2"); expect(mock.requests.filter((item) => item.pathname.endsWith("/publish"))).toHaveLength(0); // Open v1: read-only page with activate + back to query. await page.getByTestId("version-open-1").click(); const crumb = page.getByTestId("breadcrumb"); await expect(crumb).toContainText("详情"); await expect(crumb).toContainText("版本 v1"); await expect(page.getByTestId("version-number")).toHaveText("v1"); await expect(page.getByTestId("version-readonly-tag")).toHaveText("只读"); await expect(page.getByTestId("version-sql")).toContainText("FROM process_readings"); await expect(page.getByTestId("params-table")).toContainText("line_code"); await expect(page.getByTestId("version-limits")).toContainText("5000"); await expect(page.getByTestId("version-frozen-note")).toContainText("已冻结"); await expect(page.getByTestId("param-name")).toHaveCount(0); await expect(page.getByTestId("field-sql")).toHaveCount(0); await expect(page.getByTestId("footer-save")).toHaveCount(0); await expect(page.getByTestId("footer-publish")).toHaveCount(0); await expect(page.getByTestId("footer-back")).toHaveText("返回列表"); await expect(page.getByTestId("footer-query")).toHaveText("返回查询"); await expect(page.getByTestId("footer-activate")).toHaveText("激活此版本"); await expect(page.getByTestId("footer-preview")).toHaveText("试跑预览"); await expect(page.getByTestId("preview-target")).toContainText("版本 v1"); await page.screenshot({ path: path.join(evidenceDir, "query-version.png"), fullPage: true }); await page.getByTestId("footer-activate").click(); expect( mock.requests.filter((item) => item.pathname === `/queries/${Q_ONE}/versions/1/activate`), ).toHaveLength(1); await page.getByTestId("footer-query").click(); await expect(page.getByTestId("field-name")).toBeVisible(); await expect(page.getByTestId("breadcrumb")).not.toContainText("版本"); await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1"); }); test("a version preview runs that version", async ({ page }) => { await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); await page.goto(`/#/queries/${Q_ONE}/versions/1`); await page.getByTestId("preview-param-line_code").locator("input").fill("L1"); await page.getByTestId("footer-preview").click(); await expect(page.getByTestId("preview-result")).toHaveAttribute("data-status", "success"); const call = mock.requests.find((item) => item.pathname === `/queries/${Q_ONE}/versions/1/preview`)!; expect(call.body).toEqual({ params: { line_code: "L1", min_temp: 0 } }); }); test("preview: running, success with a masked column, parameter values sent by type", async ({ page }) => { await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); mock.preview.delayMs = 600; await page.goto(`/#/queries/${Q_ONE}`); await expect(page.getByTestId("preview-none")).toBeVisible(); await expect(page.getByTestId("preview-target")).toContainText("当前版本"); // Declared defaults pre-fill the inputs; a value that does not fit the type is not sent. await expect(page.getByTestId("preview-param-min_temp").locator("input")).toHaveValue("0"); await page.getByTestId("preview-param-min_temp").locator("input").fill("abc"); await page.getByTestId("footer-preview").click(); await expect(page.getByTestId("preview-param-min_temp")).toContainText("不符"); expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(0); await page.getByTestId("preview-param-min_temp").locator("input").fill("1.5"); await page.getByTestId("preview-param-line_code").locator("input").fill("L1"); await page.getByTestId("footer-preview").click(); await expect(page.getByTestId("preview-running")).toContainText("试跑中"); await expect(page.getByTestId("footer-preview")).toBeDisabled(); const result = page.getByTestId("preview-result"); await expect(result).toHaveAttribute("data-status", "success"); await expect(page.getByTestId("preview-table")).toContainText("LOT-1001"); await expect(page.getByTestId("preview-table")).toContainText("NULL"); await expect(page.getByTestId("masked-phone")).toHaveText("脱敏"); await expect(page.getByTestId("masked-lot_no")).toHaveCount(0); await expect(page.getByTestId("preview-meta")).toContainText("timeout_ms=5000"); await expect(page.getByTestId("preview-meta")).toContainText("产线工艺库"); await expect(page.getByTestId("preview-meta")).toContainText("不创建报警"); const call = mock.requests.find((item) => item.pathname === `/queries/${Q_ONE}/preview`)!; expect(call.body).toEqual({ params: { line_code: "L1", min_temp: 1.5 } }); await page.screenshot({ path: path.join(evidenceDir, "query-preview-success.png"), fullPage: true }); }); test("preview: empty, illegal type and every failure kind stay apart", async ({ page }) => { await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); await page.goto(`/#/queries/${Q_ONE}`); const result = page.getByTestId("preview-result"); mock.preview.body = previewBody({ status: "empty", columns: ["lot_no"], rows: [], row_count: 0, masked_columns: [] }); await page.getByTestId("footer-preview").click(); await expect(result).toHaveAttribute("data-status", "empty"); await expect(result).toContainText("空结果"); await expect(result).toContainText("不是失败"); await expect(page.getByTestId("preview-table")).toHaveCount(0); await page.screenshot({ path: path.join(evidenceDir, "query-preview-empty.png"), fullPage: true }); mock.preview.body = previewBody({ status: "illegal_type", columns: ["temperature"], details: { fields: [{ field: "temperature", expected: "number", actual: "str", row: 1 }] }, }); await page.getByTestId("footer-preview").click(); await expect(result).toHaveAttribute("data-status", "illegal_type"); await expect(result).toContainText("输出类型不匹配"); await expect(page.getByTestId("preview-problems")).toContainText("temperature"); await expect(page.getByTestId("preview-problems")).toContainText("number"); await expect(page.getByTestId("preview-problems")).toContainText("str"); await page.screenshot({ path: path.join(evidenceDir, "query-preview-illegal.png"), fullPage: true }); const kinds: [string, string, boolean][] = [ ["timeout", "执行超时", false], ["unreachable", "连接失败", true], ["auth_failed", "认证失败", true], ["rejected", "拒绝连接", true], ["sql_error", "SQL 执行失败", false], ["limit_exceeded", "超出 max_rows", false], ["validation", "模板或参数无效", false], ]; for (const [kind, title, counted] of kinds) { mock.preview.body = previewBody({ status: "failure", failure_kind: kind, message: SERVER_TEXT, details: kind === "limit_exceeded" ? { max_rows: 200 } : kind === "validation" ? { reason: "missing_param" } : {}, }); await page.getByTestId("footer-preview").click(); await expect(result).toHaveAttribute("data-status", "failure"); await expect(result).toHaveAttribute("data-failure-kind", kind); await expect(result).toContainText(title); await expect(page.getByTestId("preview-failure-note")).toContainText(counted ? "会计入" : "不计入"); await expect(page.locator("body")).not.toContainText(SERVER_TEXT); } await expect(result).toContainText("缺少必填参数"); await page.screenshot({ path: path.join(evidenceDir, "query-preview-failure.png"), fullPage: true }); mock.preview.body = previewBody({ status: "failure", failure_kind: "circuit_open", details: { reason: "circuit_open", circuit_open_until: "2026-11-18T09:30:00+00:00" }, }); await page.getByTestId("footer-preview").click(); await expect(result).toHaveAttribute("data-status", "circuit_open"); await expect(result).toContainText("熔断中"); await expect(result).toContainText("2026-11-18"); mock.preview.body = previewBody({ status: "failure", failure_kind: "disabled", details: { reason: "disabled" } }); await page.getByTestId("footer-preview").click(); await expect(result).toHaveAttribute("data-status", "disabled"); await expect(result).toContainText("数据源已停用"); mock.preview = { status: 403, delayMs: 0, body: fail(42000, SERVER_TEXT, { permission_node: "x" }) }; await page.getByTestId("footer-preview").click(); await expect(page.getByTestId("preview-error")).toContainText("权限不足"); await expect(page.locator("body")).not.toContainText(SERVER_TEXT); }); test("disabled query: the button stays clickable and the 409 is explained", async ({ page }) => { await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); await page.goto(`/#/queries/${Q_OFF}`); await expect(page.getByTestId("query-disabled-note")).toBeVisible(); await expect(page.getByTestId("footer-enable")).toHaveText("启用"); await expect(page.getByTestId("footer-disable")).toHaveCount(0); await expect(page.getByTestId("footer-preview")).toBeEnabled(); await page.getByTestId("footer-preview").click(); const result = page.getByTestId("preview-result"); await expect(result).toHaveAttribute("data-status", "disabled"); await expect(result).toContainText("该查询已停用"); await expect(page.locator("body")).not.toContainText("Query is disabled"); expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(1); await page.screenshot({ path: path.join(evidenceDir, "query-disabled.png"), fullPage: true }); }); test("停用 asks to confirm, 启用 does not; the list follows", async ({ page }) => { await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); await page.goto(`/#/queries/${Q_ONE}`); await page.getByTestId("footer-disable").click(); await page.locator(".el-message-box__btns .el-button:not(.el-button--primary)").click(); expect(mock.requests.filter((item) => item.pathname.endsWith("/disable"))).toHaveLength(0); await page.getByTestId("footer-disable").click(); await confirmDialog(page); await expect(page.getByTestId("footer-enable")).toHaveText("启用"); await expect(page.getByTestId("query-disabled-note")).toBeVisible(); await expect(page.getByTestId("status-tag")).toHaveText("已停用"); await page.getByTestId("footer-back").click(); await expect(page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-preview")).toBeDisabled(); await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-open").click(); await page.getByTestId("footer-enable").click(); await expect(page.getByTestId("footer-disable")).toBeVisible(); await expect(page.getByTestId("query-disabled-note")).toHaveCount(0); expect(mock.requests.filter((item) => item.pathname.endsWith("/enable"))).toHaveLength(1); }); test("list 预览 opens the detail at the trial-run panel without running it", async ({ page }) => { await page.setViewportSize({ width: 1280, height: 520 }); await signIn(page, ["watchman-admin"]); const mock = await mockApi(page); await page.goto("/#/queries"); await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-preview").click(); await expect(page.getByTestId("preview-card")).toBeInViewport(); await expect(page.getByTestId("preview-none")).toBeVisible(); expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(0); }); test("unknown query and version show a not-found message", async ({ page }) => { await signIn(page, ["watchman-admin"]); await mockApi(page); await page.goto("/#/queries/99999999-9999-4999-8999-999999999999"); await expect(page.getByTestId("query-load-error")).toContainText("查询不存在"); await expect(page.getByTestId("footer-back")).toBeVisible(); await expect(page.getByTestId("footer-save")).toHaveCount(0); await page.goto(`/#/queries/${Q_ONE}/versions/9`); await expect(page.getByTestId("query-load-error")).toContainText("版本不存在"); }); });