run-tests.mjs 3.86 KB
#!/usr/bin/env node
/**
 * @file usedcar lane 的测试入口:收集全 lane 的 *.test.mjs,喂给 node --test 并汇总。
 *
 * 为什么要一个脚本而不是 `node --test <254 个路径>`:Windows 的命令行长度上限会被
 * 绝对路径顶穿(约 25KB),且 fixtures 目录里的伪测试文件、需要微信开发者工具的
 * *.live.test.mjs 都要在这一层排除掉。
 *
 * 用法:
 *   node scripts/run-tests.mjs                # 离线全量
 *   node scripts/run-tests.mjs packageEquity  # 只跑路径含 packageEquity 的
 *   node scripts/run-tests.mjs --live         # 追加 live 用例(需开发者工具已启动)
 */
import { spawnSync } from 'node:child_process';
import { readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const SKIP_DIRS = new Set(['node_modules', 'miniprogram_npm', 'dist', 'docs', 'fixtures', '.git']);
const BATCH_SIZE = 100;

function collect(dir, out) {
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
    const absolute = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      if (!SKIP_DIRS.has(entry.name)) collect(absolute, out);
    } else if (entry.name.endsWith('.test.mjs')) {
      out.push(absolute);
    }
  }
  return out;
}

const argv = process.argv.slice(2);
const withLive = argv.includes('--live');
const filters = argv.filter((a) => !a.startsWith('--'));
const liveTag = '.live.test.mjs';

const toPosix = (value) => value.split(path.sep).join('/');

const files = collect(root, [])
  .filter((file) => (withLive ? true : !file.endsWith(liveTag)))
  .filter((file) => filters.every((f) => toPosix(path.relative(root, file)).includes(f)))
  .sort();

if (files.length === 0) {
  console.error('[test] 没有匹配到测试文件');
  process.exit(1);
}

const started = Date.now();
const counts = { pass: 0, fail: 0, cancelled: 0 };
const failures = [];
let crashed = 0;

for (let i = 0; i < files.length; i += BATCH_SIZE) {
  const batch = files.slice(i, i + BATCH_SIZE);
  const result = spawnSync(process.execPath, ['--test', '--test-reporter=tap', ...batch], {
    cwd: root,
    encoding: 'utf8',
    maxBuffer: 64 * 1024 * 1024,
  });
  const output = `${result.stdout ?? ''}${result.stderr ?? ''}`;
  const number = (key) => Number(output.match(new RegExp(`^# ${key} (\\d+)$`, 'm'))?.[1] ?? 0);
  counts.pass += number('pass');
  counts.fail += number('fail');
  counts.cancelled += number('cancelled');

  const lines = output.split(/\r?\n/);
  lines.forEach((line, index) => {
    if (!/^not ok \d+ - /.test(line)) return;
    const detail = lines
      .slice(index + 1, index + 9)
      .filter((l) => /^\s{2,}\S/.test(l))
      .slice(0, 4)
      .map((l) => l.trim())
      .join(' | ');
    failures.push(`${line.replace(/^not ok \d+ - /, '')}\n    ${detail}`);
  });

  // 批次里没有用例计数 = 进程启动即失败(语法错误 / 未捕获退出)。
  if (result.status !== 0 && number('tests') === 0) {
    crashed += 1;
    failures.push(`批次 ${i / BATCH_SIZE + 1} 无法启动:${output.slice(0, 400)}`);
  }

  process.stdout.write(
    `[test] 批次 ${Math.floor(i / BATCH_SIZE) + 1}/${Math.ceil(files.length / BATCH_SIZE)}:` +
      `${batch.length} 个文件,累计 pass ${counts.pass} / fail ${counts.fail}\n`
  );
}

const seconds = ((Date.now() - started) / 1000).toFixed(1);
console.log(
  `[test] ${files.length} 个文件(${withLive ? '含 live' : '离线'}):` +
    `pass ${counts.pass} / fail ${counts.fail} / cancelled ${counts.cancelled},用时 ${seconds}s`
);

if (failures.length) {
  console.error(`\n[test] 失败 ${failures.length} 项:`);
  failures.forEach((f) => console.error(`  - ${f}`));
}
if (crashed) console.error(`[test] ${crashed} 个批次无法启动`);

process.exit(counts.fail || counts.cancelled || crashed ? 1 : 0);