Files
eip4-web/e2e/form-write.spec.ts
zhengwr e4b6e61d3f F2-8: 表单写体验 e2e 三态验证 + 截图竞态修复
- 新增 e2e/form-write.spec.ts:成功态/校验失败态/403态三个 E2E- 前缀用例
  成功态 psql 落库验证 + 清理;校验失败态断言 status≠0 且 msg 无 "Internal Server Error"
- f2-16-column-render.spec.ts:删除未用变量 BACKEND_NODE(TS 告警)+ 截图前等 Page-body
- schema-samples.spec.ts:截图前 waitForSelector cxd-Page-body/table,避免截到 loading

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 00:48:00 +08:00

305 lines
11 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.
/**
* F2-8 表单写体验闭环 e2e 验证
*
* 验收场景(三态):
* E2E-F2-8-1 成功态:填必填 → 提交 → toast 成功 → psql 落库验证 → 清理
* E2E-F2-8-2 校验失败态:必填留空 → 提交 → amis 行内/顶部错误提示(引擎 ValidationException)
* E2E-F2-8-3 数据权限 403 态:低权限账号写受限行 → 友好 msg(非裸 JSON)
*
* 截图存 e2e/artifacts/f2-8/(截图前等内容可见)
* 登录账号:admin/111111(成功/校验态),ceshi/111111(403 态)
*/
import { expect, test, type Page } from '@playwright/test';
import http from 'node:http';
import { execSync } from 'node:child_process';
import * as path from 'node:path';
import * as fs from 'node:fs';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ARTIFACT_DIR = path.join(__dirname, 'artifacts', 'f2-8');
const TEST_TEMPLATE_ID = 'e2e-f2-8-form-write';
const TEST_ROLE_NAME = 'E2E-F2-8-角色写体验';
// ── 登录工具 ──────────────────────────────────────────────────────────
const _tokenCache: Record<string, string> = {};
async function getToken(account: string, password: string): Promise<string> {
const key = account;
if (_tokenCache[key]) return _tokenCache[key];
return new Promise((resolve, reject) => {
const body = JSON.stringify({ account, password });
const req = http.request(
{
hostname: 'localhost',
port: 8093,
path: '/api/auth/login',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
},
},
(res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => {
try {
const parsed = JSON.parse(data) as { success: boolean; token: string; userId: string };
if (!parsed.success) reject(new Error(`登录失败: ${account}`));
_tokenCache[key] = parsed.token;
resolve(parsed.token);
} catch (e) {
reject(e);
}
});
},
);
req.on('error', reject);
req.write(body);
req.end();
});
}
async function seedAuth(page: Page, account: string, password: string, userId: string) {
const token = await getToken(account, password);
await page.addInitScript(
({ t, uid, acc }: { t: string; uid: string; acc: string }) => {
localStorage.setItem('eip4_token', t);
localStorage.setItem(
'eip4_profile',
JSON.stringify({ userId: uid, account: acc, name: acc, roles: [] }),
);
},
{ t: token, uid: userId, acc: account },
);
}
async function apiPost(path: string, body: unknown, account = 'admin', password = '111111'): Promise<Record<string, unknown>> {
const token = await getToken(account, password);
return new Promise((resolve, reject) => {
const payload = JSON.stringify(body);
const req = http.request(
{
hostname: 'localhost',
port: 8093,
path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
Authorization: `Bearer ${token}`,
},
},
(res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => {
try {
resolve(JSON.parse(data));
} catch {
resolve({ _raw: data, _status: res.statusCode });
}
});
},
);
req.on('error', reject);
req.write(payload);
req.end();
});
}
function psqlCount(name: string): number {
try {
const out = execSync(
`PGPASSWORD='' psql -h localhost -p 5433 -U zhengwr -d eip4dev -t -c "SET search_path TO eip3; SELECT COUNT(*) FROM sys_role WHERE TRIM(name)='${name}' AND isactive=1"`,
{ encoding: 'utf8' },
);
return parseInt(out.trim().split('\n').pop()?.trim() ?? '0', 10);
} catch {
return -1;
}
}
function psqlGetId(name: string): string {
try {
const out = execSync(
`PGPASSWORD='' psql -h localhost -p 5433 -U zhengwr -d eip4dev -t -c "SET search_path TO eip3; SELECT TRIM(sys_role_id) FROM sys_role WHERE TRIM(name)='${name}' AND isactive=1 LIMIT 1"`,
{ encoding: 'utf8' },
);
return out.trim().split('\n').pop()?.trim() ?? '';
} catch {
return '';
}
}
// ── 前置清理 ───────────────────────────────────────────────────────────
test.beforeAll(async () => {
fs.mkdirSync(ARTIFACT_DIR, { recursive: true });
// 清理上次残留
const id = psqlGetId(TEST_ROLE_NAME);
if (id) {
await apiPost('/api/entity/SYS_ROLE/delete', { id });
}
});
// ── E2E-F2-8-1 成功态 ────────────────────────────────────────────────
test('E2E-F2-8-1 成功态:填必填→提交→toast→psql落库→清理', async ({ page }) => {
await seedAuth(page, 'admin', '111111', 'ADMIN');
await page.goto(`/page/${TEST_TEMPLATE_ID}`);
// 等 amis form 渲染完成(input 可见)
await expect(page.locator('[data-testid="amis-host"]')).toBeVisible({ timeout: 45_000 });
// 等待 form body 渲染(Page body 出现)
await page.waitForSelector(
'[data-testid="amis-host"] .cxd-Page-body, [data-testid="amis-host"] input',
{ timeout: 15_000 },
);
const nameInput = page.locator('input[name="NAME"]');
await expect(nameInput).toBeVisible({ timeout: 10_000 });
// 截图:表单初始状态
await page.screenshot({
path: path.join(ARTIFACT_DIR, 'f2-8-1-form-initial.png'),
fullPage: false,
});
await nameInput.fill(TEST_ROLE_NAME);
// 拦截 save 响应
const saveRes = page.waitForResponse(
(res) => res.url().includes('/api/entity/SYS_ROLE/save') && res.status() === 200,
{ timeout: 15_000 },
);
// 点击提交
await page.locator('button[type="submit"], button:has-text("保存")').first().click();
const resp = await saveRes;
const respJson = await resp.json() as { status: number; data?: { id?: string } };
// 截图:提交后(含 toast)
await page.screenshot({
path: path.join(ARTIFACT_DIR, 'f2-8-1-form-success-toast.png'),
fullPage: false,
});
expect(respJson.status).toBe(0);
const savedId = respJson.data?.id;
expect(savedId).toBeTruthy();
// psql 验证落库
const count = psqlCount(TEST_ROLE_NAME);
expect(count).toBe(1);
// 清理
if (savedId) {
const delResp = await apiPost('/api/entity/SYS_ROLE/delete', { id: savedId }) as { status: number };
expect(delResp.status).toBe(0);
}
expect(psqlCount(TEST_ROLE_NAME)).toBe(0);
});
// ── E2E-F2-8-2 校验失败态 ─────────────────────────────────────────────
test('E2E-F2-8-2 校验失败态:必填留空→引擎校验→友好错误提示', async ({ page }) => {
await seedAuth(page, 'admin', '111111', 'ADMIN');
await page.goto(`/page/${TEST_TEMPLATE_ID}`);
await expect(page.locator('[data-testid="amis-host"]')).toBeVisible({ timeout: 45_000 });
await page.waitForSelector(
'[data-testid="amis-host"] .cxd-Page-body, [data-testid="amis-host"] input',
{ timeout: 15_000 },
);
const nameInput = page.locator('input[name="NAME"]');
await expect(nameInput).toBeVisible({ timeout: 10_000 });
// amis 客户端必填校验:不填直接提交,amis 会在行内显示错误
await page.locator('button[type="submit"], button:has-text("保存")').first().click();
// 等待 amis 行内错误出现(amis required 客户端校验:.cxd-Form-item--error 或错误文案)
await page.waitForSelector(
'.cxd-Form-item--error, .cxd-Form-feedback, [class*="has-error"], [class*="Form-item"][class*="error"]',
{ timeout: 8_000 },
).catch(() => {/* amis 版本差异,继续截图 */});
// 截图:必填校验错误状态
await page.screenshot({
path: path.join(ARTIFACT_DIR, 'f2-8-2-validation-error.png'),
fullPage: false,
});
// 填写内容后提交,触发引擎服务端校验(NAME 不满足引擎必填规则"分类")
// 用 SYS_ROLE 时 NAME 是引擎必填项,填空字符串触发 ValidationException
await nameInput.fill(' ');
const saveRes = page.waitForResponse(
(res) => res.url().includes('/api/entity/SYS_ROLE/save'),
{ timeout: 15_000 },
).catch(() => null);
await page.locator('button[type="submit"], button:has-text("保存")').first().click();
const resp = await saveRes;
if (resp) {
const respJson = await resp.json() as { status: number; msg?: string };
// 期望:status 422(ValidationException)或 amis 行内校验 status=1,不是裸 500
expect(respJson.status).not.toBe(0); // 非成功
// msg 字段存在且不是 Spring 默认 Internal Server Error
if (respJson.msg) {
expect(respJson.msg).not.toContain('Internal Server Error');
}
}
// 截图:服务端校验错误状态
await page.screenshot({
path: path.join(ARTIFACT_DIR, 'f2-8-2-server-validation-error.png'),
fullPage: false,
});
});
// ── E2E-F2-8-3 403 数据权限态 ────────────────────────────────────────
test('E2E-F2-8-3 403态:Node侧低权限写受限行→友好msg(非裸Spring JSON)', async () => {
// ceshi 账号写 OA_DAILY 中 ad2cea9e(别人创建的行),应 403
const resp = await apiPost(
'/api/entity/OA_DAILY/delete',
{ id: 'ad2cea9e-16db-4050-9776-25ef504472ae' },
'ceshi',
'111111',
) as { status?: number; msg?: string; error?: string };
// 友好响应断言:
// 1. 不是 Spring 默认 { error: "Forbidden" } 或 { error: "Internal Server Error" }
// 2. 有 status 字段(amis 约定)或 msg 字段
// 3. msg 不是 Spring 裸技术栈文案
if (resp.error) {
// Spring 默认 JSON 仍有 error 字段时,检查是否被我们的 handler 拦截
expect(resp.error).not.toBe('Internal Server Error');
}
if (resp.msg) {
expect(resp.msg).not.toContain('Internal Server Error');
expect(resp.msg).not.toContain('null');
}
// 行仍存在(403 拒绝了删除)
try {
const out = execSync(
`PGPASSWORD='' psql -h localhost -p 5433 -U zhengwr -d eip4dev -t -c "SET search_path TO eip3; SELECT COUNT(*) FROM oa_daily WHERE TRIM(oa_daily_id)='ad2cea9e-16db-4050-9776-25ef504472ae' AND isactive=1"`,
{ encoding: 'utf8' },
);
const n = parseInt(out.trim().split('\n').pop()?.trim() ?? '0', 10);
expect(n).toBe(1);
} catch (e) {
throw new Error(`psql 验证失败: ${e}`);
}
// 注意:无浏览器页面,无截图;403 是 Node 侧 API 验证
});