Files
eip4-web/e2e/recipe-render-smoke.spec.ts
zhengwr 4b564c6316 test(e2e): executable AI-recipe render smoke gate (M-Gate)
把「手动用浏览器验 AI 生成页渲染成 house-style」codify 成可复用的可执行门,补上
critic 点名「playwright-render 名实不符(从不真渲染)」的缺口——不给后端加浏览器依赖。

- e2e/recipe-render-smoke.spec.ts:给定 templateId,从 served schema 自推期望
  (数据列 label + 所有按钮 label),再断言 amis 真渲染成无错 DOM:amis-host 可见
  且无 schema-error-card / 每列每动作出现 / tbody 无裸 true·false·ISO 串
  (列渲染类型生效)/ 0 console.error·pageerror。
- playwright.recipe-smoke.config.ts:复用已在跑的 5174,不自起 webServer。
- recipe-render-smoke.sh:一键端到端——登录→auto-develop 1 maintenance + 1 tree
  样例→对两页跑断言→DROP 表+删三真相行清理(trap 保证失败也清,sys_ai_* 保留)。

验证:./recipe-render-smoke.sh 端到端全绿(maintenance + tree 两页均 PASSED,
0 console error),库残留复查 0。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 20:28:32 +08:00

170 lines
6.5 KiB
TypeScript
Raw Permalink 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.
/**
* AI recipe 渲染冒烟门(M-Gate 的可执行化)。
*
* 把「手动用浏览器验 AI 生成页是否真渲染成 house-style」codify 成一条可复用断言:
* 给定一个 templateId,从【已生成并 served】的页面 schema 自推期望(列/动作),再断言
* amis 真把它渲染成无错 DOM——补上 critic 点名「playwright-render 名实不符(从不真渲染)」的缺口。
*
* 断言(schema 驱动,recipe 无关):
* ① amis-host 可见 且 无 schema-error-card → 渲染无致命错
* ② body=crud,且 schema 每个数据列 label 出现在表头 → 列真渲染
* ③ schema 里每个 {type:button} 的 label 出现在页面 → 工具栏/节点动作真渲染
* ④ tbody 无裸 true/false、无裸 ISO 时间串 → 列渲染类型(是/否、日期格式)生效
* ⑤ 0 pageerror + 0 console.error → 无运行时报错
*
* 入参(env):RECIPE_SMOKE_TEMPLATE(必填,templateId)。
* 前置:localhost:5174(前端 dev)+ localhost:8093(后端 dev)。页面须已 served。
* 运行:RECIPE_SMOKE_TEMPLATE=<id> npx playwright test --config=playwright.recipe-smoke.config.ts
*/
import { expect, test, type Page, type ConsoleMessage } from '@playwright/test';
import * as http from 'node:http';
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 TEMPLATE_ID = process.env.RECIPE_SMOKE_TEMPLATE ?? '';
const ARTIFACT_DIR = path.join(__dirname, 'artifacts', 'recipe-render-smoke');
let _tokenCache: string | null = null;
function getJson<T>(reqPath: string, body?: string): Promise<T> {
return new Promise((resolve, reject) => {
const req = http.request(
{
hostname: 'localhost',
port: 8093,
path: reqPath,
method: body ? 'POST' : 'GET',
headers: body
? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }
: {},
},
(res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => {
try {
resolve(JSON.parse(data) as T);
} catch (e) {
reject(new Error(`非 JSON 响应 ${reqPath}: ${data.slice(0, 200)}`));
}
});
},
);
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
async function getToken(): Promise<string> {
if (_tokenCache) return _tokenCache;
const parsed = await getJson<{ success: boolean; token: string }>(
'/api/auth/login',
JSON.stringify({ account: 'admin', password: '111111' }),
);
if (!parsed.success) throw new Error('登录失败');
_tokenCache = parsed.token;
return parsed.token;
}
async function seedAuth(page: Page) {
const token = await getToken();
await page.addInitScript(
({ t }: { t: string }) => {
localStorage.setItem('eip4_token', t);
localStorage.setItem(
'eip4_profile',
JSON.stringify({ userId: 'ADMIN', account: 'admin', name: '系统管理员', roles: [] }),
);
},
{ t: token },
);
}
/** 递归收集 schema 中所有 {type:'button'} 节点的 label —— 工具栏 + 节点操作动作。 */
function collectButtonLabels(node: unknown, out: Set<string>): void {
if (Array.isArray(node)) {
node.forEach((n) => collectButtonLabels(n, out));
return;
}
if (node && typeof node === 'object') {
const obj = node as Record<string, unknown>;
if (obj.type === 'button' && typeof obj.label === 'string' && obj.label.trim()) {
out.add(obj.label.trim());
}
Object.values(obj).forEach((v) => collectButtonLabels(v, out));
}
}
test.beforeAll(() => {
fs.mkdirSync(ARTIFACT_DIR, { recursive: true });
if (!TEMPLATE_ID) throw new Error('缺 env RECIPE_SMOKE_TEMPLATE');
});
test(`AI recipe 页 ${TEMPLATE_ID} 渲染成无错 house-style DOM`, async ({ page }) => {
// 0 console.error / pageerror 收集(house-style 页应零报错)。
const consoleErrors: string[] = [];
page.on('console', (m: ConsoleMessage) => {
if (m.type() === 'error') consoleErrors.push(m.text());
});
page.on('pageerror', (e) => consoleErrors.push(`pageerror: ${e.message}`));
// 自推期望:从 served schema 拿数据列 label 与所有按钮 label。
const schema = await getJson<{
body?: { type?: string; columns?: Array<{ name?: string; label?: string; type?: string }> };
}>(`/api/page/schema/${TEMPLATE_ID}`);
expect(schema.body?.type, 'body.type 应为 crud').toBe('crud');
const dataColumnLabels = (schema.body?.columns ?? [])
.filter((c) => c.name && c.label && c.type !== 'operation')
.map((c) => c.label!) as string[];
const buttonLabels = new Set<string>();
collectButtonLabels(schema, buttonLabels);
await seedAuth(page);
await page.goto(`/page/${TEMPLATE_ID}`);
// ① 渲染完成且无致命错卡。
await expect(page.locator('[data-testid="amis-host"]')).toBeVisible({ timeout: 45_000 });
await expect(page.locator('[data-testid="schema-error-card"]')).not.toBeVisible();
await page
.waitForSelector(
'[data-testid="amis-host"] table, [data-testid="amis-host"] .cxd-CRUD',
{ timeout: 20_000 },
)
.catch(() => {/* 空表也算渲染成功,继续 */});
await page.screenshot({
path: path.join(ARTIFACT_DIR, `${TEMPLATE_ID}-full.png`),
fullPage: true,
});
const bodyText = (await page.textContent('body')) ?? '';
// ② 每个数据列 label 出现在页面(表头)。
for (const label of dataColumnLabels) {
expect(bodyText, `列「${label}」应渲染`).toContain(label);
}
// ③ 每个按钮 label 出现在页面(工具栏/节点动作真渲染)。
for (const label of Array.from(buttonLabels)) {
expect(bodyText, `动作「${label}」应渲染`).toContain(label);
}
// ④ 列渲染类型生效:表体无裸 true/false、无裸 ISO 时间串。
const tbodyText = await page
.evaluate(() => document.querySelector('tbody')?.textContent ?? '')
.catch(() => '');
if (tbodyText.trim()) {
expect(tbodyText, '布尔列应渲染为 是/否,而非裸 true').not.toMatch(/\btrue\b/);
expect(tbodyText, '布尔列应渲染为 是/否,而非裸 false').not.toMatch(/\bfalse\b/);
expect(tbodyText, '日期列应格式化,而非裸 ISO 串').not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
}
// ⑤ 0 console.error / pageerror。
expect(consoleErrors, `控制台报错:\n${consoleErrors.join('\n')}`).toHaveLength(0);
});