aboutsummaryrefslogtreecommitdiff
path: root/packages/bun-test/src/runner.ts
blob: f3add738515e86ee155ace507c9b39a80ade6d0b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { spawn } from "bun";
import { readdirSync } from "node:fs";
import { resolve } from "node:path";
import * as action from "@actions/core";

const cwd = resolve("../..");
const isAction = !!process.env["GITHUB_ACTION"];
const errorPattern = /error: ([\S\s]*?)(?=\n.*?at (\/.*):(\d+):(\d+))/mgi;

function* findTests(dir: string, query?: string): Generator<string> {
  for (const entry of readdirSync(resolve(dir), { encoding: "utf-8", withFileTypes: true })) {
    const path = resolve(dir, entry.name);
    if (entry.isDirectory()) {
      yield* findTests(path, query);
    } else if (entry.isFile() && entry.name.includes(".test.")) {
      yield path;
    }
  }
}

async function runTest(path: string): Promise<void> {
  const name = path.replace(cwd, "").slice(1);
  const runner = await spawn({
    cwd,
    cmd: ["bun", "test", path],
    stdout: "pipe",
    stderr: "pipe",
    env: {
      ...process.env,
      FORCE_COLOR: "1",
    }
  });
  const exitCode = await Promise.race([
    new Promise((resolve) => {
      setTimeout(() => {
        runner.kill();
        resolve(124); // Timed Out
      }, 60_000);
    }),
    runner.exited,
  ]);
  if (isAction) {
    const prefix = exitCode === 0
      ? "PASS"
      : `FAIL (exit code ${exitCode})`;
    action.startGroup(`${prefix} - ${name}`);
  }
  for (const stdout of [runner.stdout, runner.stderr]) {
    if (!stdout) {
      continue;
    }
    const reader = stdout.getReader();
    while (true) {
      const { value, done } = await reader.read();
      if (value) {
        console.write(value);
        if (isAction) {
          findErrors(value);
        }
      }
      if (done) {
        break;
      }
    }
  }
  if (isAction) {
    action.endGroup();
  }
}

let failed = false;

function findErrors(data: Uint8Array): void {
  const text = new TextDecoder().decode(data);
  for (const [message, _, path, line, col] of text.matchAll(errorPattern)) {
    failed = true;
    action.error(message, {
      file: path.replace(cwd, "").slice(1),
      startLine: parseInt(line),
      startColumn: parseInt(col),
    });
  }
}

const tests = [];
for (const path of findTests(resolve(cwd, "test/bun.js"))) {
  tests.push(runTest(path).catch(console.error));
}
await Promise.allSettled(tests);
process.exit(failed ? 1 : 0);