test-runner.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // kilocode_change - new file
  2. //
  3. // Custom test runner that executes each test file in its own isolated process.
  4. // Prevents cross-contamination between test files by ensuring separate PIDs,
  5. // temp directories, in-memory databases, and environment state.
  6. import os from "os"
  7. import path from "path"
  8. import fs from "fs/promises"
  9. const root = path.resolve(import.meta.dir, "..")
  10. const argv = process.argv.slice(2)
  11. // ---------------------------------------------------------------------------
  12. // Help
  13. // ---------------------------------------------------------------------------
  14. if (argv.includes("--help") || argv.includes("-h")) {
  15. console.log(
  16. [
  17. "",
  18. "Usage: bun run script/test-runner.ts [options] [patterns...]",
  19. "",
  20. "Runs test files in isolated parallel processes to prevent cross-contamination.",
  21. "",
  22. "Options:",
  23. " --ci Enable JUnit XML output to .artifacts/unit/junit.xml",
  24. " --concurrency <N> Max parallel processes (default: CPU count)",
  25. " --timeout <ms> Per-test timeout passed to bun test (default: 30000)",
  26. " --file-timeout <ms> Per-file process timeout (default: 300000)",
  27. " --bail Stop on first failure",
  28. " --verbose Show full output for every file",
  29. " -h, --help Show this help",
  30. "",
  31. "Positional:",
  32. " [patterns...] Filter test files by substring match",
  33. "",
  34. ].join("\n"),
  35. )
  36. process.exit(0)
  37. }
  38. // ---------------------------------------------------------------------------
  39. // CLI parsing
  40. // ---------------------------------------------------------------------------
  41. function opt(name: string, fallback: number) {
  42. const i = argv.indexOf(`--${name}`)
  43. return i >= 0 && i + 1 < argv.length ? Number(argv[i + 1]) || fallback : fallback
  44. }
  45. const ci = argv.includes("--ci")
  46. const bail = argv.includes("--bail")
  47. const verbose = argv.includes("--verbose")
  48. const concurrency = opt("concurrency", os.cpus().length)
  49. const timeout = opt("timeout", 30000)
  50. const deadline = opt("file-timeout", 300000)
  51. const valued = new Set(["--concurrency", "--timeout", "--file-timeout"])
  52. const patterns = argv.filter((arg, i) => {
  53. if (arg.startsWith("-")) return false
  54. if (i > 0 && valued.has(argv[i - 1])) return false
  55. return true
  56. })
  57. // ---------------------------------------------------------------------------
  58. // Colors
  59. // ---------------------------------------------------------------------------
  60. const tty = !!process.stdout.isTTY
  61. const green = (s: string) => (tty ? `\x1b[32m${s}\x1b[0m` : s)
  62. const red = (s: string) => (tty ? `\x1b[31m${s}\x1b[0m` : s)
  63. const dim = (s: string) => (tty ? `\x1b[2m${s}\x1b[0m` : s)
  64. const bold = (s: string) => (tty ? `\x1b[1m${s}\x1b[0m` : s)
  65. // ---------------------------------------------------------------------------
  66. // File discovery
  67. // ---------------------------------------------------------------------------
  68. const glob = new Bun.Glob("**/*.test.{ts,tsx}")
  69. const all = (await Array.fromAsync(glob.scan({ cwd: path.join(root, "test") }))).sort()
  70. const files =
  71. patterns.length > 0 ? all.filter((f) => patterns.some((p) => f.includes(p) || path.join("test", f).includes(p))) : all
  72. if (files.length === 0) {
  73. console.log("No test files found")
  74. process.exit(0)
  75. }
  76. // ---------------------------------------------------------------------------
  77. // Types
  78. // ---------------------------------------------------------------------------
  79. type Result = {
  80. file: string
  81. passed: boolean
  82. code: number
  83. stdout: string
  84. stderr: string
  85. duration: number
  86. timedout: boolean
  87. }
  88. // ---------------------------------------------------------------------------
  89. // Setup
  90. // ---------------------------------------------------------------------------
  91. const xmldir = ci ? path.join(os.tmpdir(), `opencode-junit-${process.pid}`) : ""
  92. if (ci) await fs.mkdir(xmldir, { recursive: true })
  93. const counter = { done: 0 }
  94. const pad = String(files.length).length
  95. // ---------------------------------------------------------------------------
  96. // Run a single test file
  97. // ---------------------------------------------------------------------------
  98. async function run(file: string): Promise<Result> {
  99. const target = path.join("test", file)
  100. const cmd = ["bun", "test", target, "--timeout", String(timeout)]
  101. if (ci) {
  102. const name = file.replace(/[/\\]/g, "_") + ".xml"
  103. cmd.push("--reporter=junit", `--reporter-outfile=${path.join(xmldir, name)}`)
  104. }
  105. const start = performance.now()
  106. const killed = { value: false }
  107. const proc = Bun.spawn(cmd, {
  108. cwd: root,
  109. stdout: "pipe",
  110. stderr: "pipe",
  111. })
  112. const timer = setTimeout(() => {
  113. killed.value = true
  114. proc.kill()
  115. }, deadline)
  116. const [stdout, stderr, code] = await Promise.all([
  117. new Response(proc.stdout).text(),
  118. new Response(proc.stderr).text(),
  119. proc.exited,
  120. ])
  121. clearTimeout(timer)
  122. return {
  123. file,
  124. passed: code === 0,
  125. code,
  126. stdout,
  127. stderr,
  128. duration: performance.now() - start,
  129. timedout: killed.value,
  130. }
  131. }
  132. // ---------------------------------------------------------------------------
  133. // Report a single result
  134. // ---------------------------------------------------------------------------
  135. function report(result: Result) {
  136. counter.done++
  137. const idx = String(counter.done).padStart(pad)
  138. const secs = (result.duration / 1000).toFixed(1)
  139. if (result.timedout) {
  140. console.log(
  141. `[${idx}/${files.length}] ${red("TIME")} ${result.file} ${dim(`(${secs}s - exceeded ${deadline / 1000}s)`)}`,
  142. )
  143. return
  144. }
  145. if (!result.passed) {
  146. console.log(`[${idx}/${files.length}] ${red("FAIL")} ${result.file} ${dim(`(${secs}s)`)}`)
  147. if (verbose && result.stderr.trim()) console.log(result.stderr)
  148. if (verbose && result.stdout.trim()) console.log(result.stdout)
  149. return
  150. }
  151. console.log(`[${idx}/${files.length}] ${green("PASS")} ${result.file} ${dim(`(${secs}s)`)}`)
  152. if (verbose && result.stdout.trim()) console.log(dim(result.stdout))
  153. }
  154. // ---------------------------------------------------------------------------
  155. // Parallel execution
  156. // ---------------------------------------------------------------------------
  157. console.log(`\nRunning ${bold(String(files.length))} test files with concurrency ${bold(String(concurrency))}\n`)
  158. const start = performance.now()
  159. const results: Result[] = []
  160. const queue = [...files]
  161. const stopped = { value: false }
  162. const workers = Array.from({ length: Math.min(concurrency, files.length) }, async () => {
  163. while (queue.length > 0 && !stopped.value) {
  164. const file = queue.shift()!
  165. const result = await run(file)
  166. results.push(result)
  167. report(result)
  168. if (bail && !result.passed) stopped.value = true
  169. }
  170. })
  171. await Promise.all(workers)
  172. const elapsed = (performance.now() - start) / 1000
  173. // ---------------------------------------------------------------------------
  174. // Failure details
  175. // ---------------------------------------------------------------------------
  176. const failures = results.filter((r) => !r.passed).sort((a, b) => a.file.localeCompare(b.file))
  177. if (failures.length > 0 && !verbose) {
  178. console.log(`\n${bold(red("--- FAILURES ---"))}\n`)
  179. for (const f of failures) {
  180. const tag = f.timedout ? " (TIMED OUT)" : ""
  181. console.log(`${bold(red(f.file))}${tag}:`)
  182. const output = (f.stderr || f.stdout).trim()
  183. if (output)
  184. console.log(
  185. output
  186. .split("\n")
  187. .map((l) => " " + l)
  188. .join("\n"),
  189. )
  190. console.log()
  191. }
  192. }
  193. // ---------------------------------------------------------------------------
  194. // Summary
  195. // ---------------------------------------------------------------------------
  196. const passed = results.filter((r) => r.passed).length
  197. console.log(
  198. `\n${bold(String(results.length))} files | ` +
  199. `${green(passed + " passed")} | ` +
  200. `${failures.length > 0 ? red(failures.length + " failed") : failures.length + " failed"} | ` +
  201. `${elapsed.toFixed(1)}s\n`,
  202. )
  203. // ---------------------------------------------------------------------------
  204. // JUnit XML merge (CI mode)
  205. // ---------------------------------------------------------------------------
  206. if (ci) {
  207. await merge()
  208. await fs.rm(xmldir, { recursive: true, force: true }).catch((err) => {
  209. console.error("cleanup failed:", err)
  210. })
  211. }
  212. process.exit(failures.length > 0 ? 1 : 0)
  213. // ---------------------------------------------------------------------------
  214. // Helpers
  215. // ---------------------------------------------------------------------------
  216. async function merge() {
  217. const dir = path.join(root, ".artifacts", "unit")
  218. await fs.mkdir(dir, { recursive: true })
  219. const suites: string[] = []
  220. const counts = { tests: 0, failures: 0, errors: 0 }
  221. for (const file of files) {
  222. const name = file.replace(/[/\\]/g, "_") + ".xml"
  223. const fpath = path.join(xmldir, name)
  224. const found = await Bun.file(fpath).exists()
  225. if (found) {
  226. const content = await Bun.file(fpath).text()
  227. const extracted = extract(content)
  228. if (extracted) {
  229. suites.push(extracted)
  230. counts.tests += attr(extracted, "tests")
  231. counts.failures += attr(extracted, "failures")
  232. counts.errors += attr(extracted, "errors")
  233. continue
  234. }
  235. }
  236. // No valid XML produced - generate synthetic entry for failed files
  237. const result = results.find((r) => r.file === file)
  238. if (!result || result.passed) continue
  239. const secs = (result.duration / 1000).toFixed(3)
  240. const msg = result.timedout
  241. ? `Test file timed out after ${deadline / 1000}s`
  242. : `Test process exited with code ${result.code}`
  243. const detail = esc((result.stderr || result.stdout || msg).slice(0, 10000))
  244. suites.push(
  245. ` <testsuite name="${esc(file)}" tests="1" failures="1" errors="0" time="${secs}">\n` +
  246. ` <testcase name="${esc(file)}" classname="${esc(file)}" time="${secs}">\n` +
  247. ` <failure message="${esc(msg)}">${detail}</failure>\n` +
  248. ` </testcase>\n` +
  249. ` </testsuite>`,
  250. )
  251. counts.tests++
  252. counts.failures++
  253. }
  254. const body = [
  255. '<?xml version="1.0" encoding="UTF-8"?>',
  256. `<testsuites tests="${counts.tests}" failures="${counts.failures}" errors="${counts.errors}" time="${elapsed.toFixed(3)}">`,
  257. ...suites,
  258. "</testsuites>",
  259. "",
  260. ].join("\n")
  261. await Bun.write(path.join(dir, "junit.xml"), body)
  262. }
  263. function extract(content: string, from = 0): string {
  264. const open = "<testsuite"
  265. const close = "</testsuite>"
  266. const s = content.indexOf(open, from)
  267. if (s === -1) return ""
  268. const e = content.indexOf(close, s)
  269. if (e === -1) return ""
  270. const suite = content.slice(s, e + close.length)
  271. const rest = extract(content, e + close.length)
  272. return rest ? suite + "\n" + rest : suite
  273. }
  274. function attr(content: string, name: string): number {
  275. const match = content.match(new RegExp(`${name}="(\\d+)"`))
  276. return match ? Number(match[1]) : 0
  277. }
  278. function esc(s: string): string {
  279. return s
  280. .replace(/&/g, "&amp;")
  281. .replace(/</g, "&lt;")
  282. .replace(/>/g, "&gt;")
  283. .replace(/"/g, "&quot;")
  284. .replace(/'/g, "&apos;")
  285. }