/** * 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= 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(reqPath: string, body?: string): Promise { 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 { 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): void { if (Array.isArray(node)) { node.forEach((n) => collectButtonLabels(n, out)); return; } if (node && typeof node === 'object') { const obj = node as Record; 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(); 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); });