import fs from 'node:fs' import path from 'node:path' import { pathToFileURL } from 'node:url' import { CASES_DIR, CASE_TIMEOUT, RESULTS_FILE, RESULTS_DIR } from './config.mjs' import { newContext } from './browser.mjs' import { TestCtx } from './dsl.mjs' /** * 用例装载与执行。 * * cases/ 下一个文件一条用例,文件名即 TC 编号,导出 `meta` 和 `run(t)`。 * 这里只负责:找到它们、按需执行、把过程记成可回放的结果。 */ export async function loadCases() { if (!fs.existsSync(CASES_DIR)) return [] const files = fs.readdirSync(CASES_DIR).filter((f) => f.endsWith('.mjs')).sort() const out = [] for (const f of files) { const full = path.join(CASES_DIR, f) try { // 加 query 让 node 每次重新读盘,改完脚本不用重启 runner const mod = await import(`${pathToFileURL(full).href}?v=${fs.statSync(full).mtimeMs}`) if (!mod.meta || typeof mod.run !== 'function') { out.push({ tc: f.replace(/\.mjs$/, ''), broken: `缺少 meta 或 run 导出` }) continue } out.push({ ...mod.meta, file: f, _run: mod.run }) } catch (e) { out.push({ tc: f.replace(/\.mjs$/, ''), broken: e.message }) } } return out } export function loadResults() { try { return JSON.parse(fs.readFileSync(RESULTS_FILE, 'utf8')) } catch { return { updatedAt: null, cases: {} } } } export function saveResults(results) { fs.mkdirSync(RESULTS_DIR, { recursive: true }) fs.writeFileSync(RESULTS_FILE, JSON.stringify(results, null, 2)) } export function mergeResult(record) { const all = loadResults() all.cases[record.tc] = record all.updatedAt = new Date().toISOString() saveResults(all) return all } function shortId() { return Math.random().toString(36).slice(2, 7) } /** * 跑一条用例。 * 无论成败都返回结果对象(不抛),这样批量执行时一条挂掉不影响后面的。 */ async function runCaseOnce(c, { onLog = () => {}, headless = false, runId = shortId() } = {}) { const t0 = Date.now() const lines = [] const log = (m) => { lines.push(m) onLog(m) } const base = { tc: c.tc, req: c.req ?? null, title: c.title ?? '', priority: c.priority ?? '', type: c.type ?? '', route: c.route ?? '', at: new Date().toISOString() } if (c.broken) { return { ...base, status: 'error', ms: 0, error: `用例脚本加载失败:${c.broken}`, log: [], shots: [] } } let context = null let page = null try { context = await newContext({ headless }) page = await context.newPage() const t = new TestCtx({ page, context, meta: c, runId, log }) log(`▶ ${c.tc} ${c.title || ''}`) // 用 process-level unhandledRejection 兜底:哪怕脚本里出现未捕获的异步异常 // (如 page 在关后还调 screenshot),也只让本条判 fail,不能让整批跑挂。 let unhandled = null const onUnhandled = (e) => { unhandled = e?.reason || e; /* swallow */ } process.on('unhandledRejection', onUnhandled) try { await Promise.race([ c._run(t), new Promise((_, rej) => setTimeout(() => rej(new Error(`用例超时(${CASE_TIMEOUT / 1000}s)`)), CASE_TIMEOUT)) ]) if (unhandled) throw unhandled instanceof Error ? unhandled : new Error(String(unhandled)) } finally { process.off('unhandledRejection', onUnhandled) } log(`✔ 通过(${Date.now() - t0}ms)`) return { ...base, status: 'pass', ms: Date.now() - t0, log: lines, shots: t.shots, steps: t.steps } } catch (e) { const shots = [] // 失败现场留一张图,比读日志快得多 if (page && !page.isClosed()) { try { const t = new TestCtx({ page, context, meta: c, runId, log: () => {} }) shots.push(await t.shot('FAIL')) } catch { /* 截不到就算了 */ } } const status = e.isSkip ? 'skip' : e.isManual ? 'manual' : 'fail' const mark = status === 'pass' ? '✔' : status === 'fail' ? '✘' : '⊘' log(`${mark} ${status === 'fail' ? '失败' : status === 'skip' ? '跳过' : '需人工核对'}:${e.message}`) return { ...base, status, ms: Date.now() - t0, error: e.message, log: lines, shots } } finally { await context?.close().catch(() => {}) } } // 浏览器环境偶发断连(长跑 300+ 条后 Chrome 资源问题)会污染后续用例为 // "browser has been closed" 式 fail。这类错误与业务无关,重试一次基本都能过, // 避免把本应 pass 的用例误报成产品缺陷。真实断言失败不会命中该正则,不会误绿。 const TRANSIENT = /browser has been closed|context or browser|browser is disconnected|Target page.*closed|Browser closed/i export async function runCase(c, opts = {}) { let res = await runCaseOnce(c, opts) if (res.status === 'fail' && TRANSIENT.test(res.error || '')) { await new Promise((r) => setTimeout(r, 1500)) res = await runCaseOnce(c, opts) } return res }