AI_UIAutomation/utils/step-trace.ts

44 lines
1.8 KiB
TypeScript

// 步骤面包屑采集:幂等 patch 全局 console.log/console.error,把每行 tee 进一个进程内环形缓冲。
// 目的:失败用例报告能显示"执行到哪一步"——helper 里本就有的步骤 log(如 "选品类完成"、
// "connection timeout"、"连接失败,点击重试")被顺带捕获,helper 一行不用改。
// 由 test-reporter.ts 顶部 import 触发装载(在任何用例逻辑跑之前),record() 负责按用例边界 reset。
const MAX_LINES = 60; // 环形缓冲上限行数
const MAX_LINE_LEN = 300; // 单行最大字符,防超长 dump 撑爆报告
let buffer: string[] = [];
let patched = false;
function push(args: any[]) {
try {
const line = args
.map(a => (typeof a === 'string' ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })()))
.join(' ');
const trimmed = line.length > MAX_LINE_LEN ? line.slice(0, MAX_LINE_LEN) + '…' : line;
buffer.push(trimmed);
if (buffer.length > MAX_LINES) buffer.splice(0, buffer.length - MAX_LINES);
} catch {
// tee 绝不能影响正常输出/流程
}
}
// 幂等:vitest 多文件加载只 patch 一次
if (!patched) {
patched = true;
const origLog = console.log.bind(console);
const origErr = console.error.bind(console);
console.log = (...args: any[]) => { push(args); origLog(...args); };
console.error = (...args: any[]) => { push(args); origErr(...args); };
}
/** 清空缓冲(在 suite 起步及每条用例 record 后调用,保证每条用例只带自己的步骤路径)。 */
export function resetTrace(): void {
buffer = [];
}
/** 返回最近 tailN 行拼成的字符串;无内容返回空串。 */
export function dumpTrace(tailN = 40): string {
const lines = tailN > 0 ? buffer.slice(-tailN) : buffer.slice();
return lines.join('\n');
}