Files
01b8009bd6 test: strip ANSI escape codes from snapshot output (#412)
Strips ANSI escape codes from captured `stdout` and `stderr` before
comparing test output to snapshots.

When `FORCE_COLOR` is set (some terminals and tools set it), Node
colorizes logged errors, so
`main-token-get-owner-set-client-error.test.js` fails locally even
though it passes in CI. With this change, snapshots match regardless of
color settings. CI output is unchanged.

Split out from #411.

Co-authored-by: Aiqiao Yan <55104035+aiqiaoy@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-11-17 21:31:31 -08:00

75 lines
2.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { readdirSync } from "node:fs";
import { execFile } from "node:child_process";
import { promisify, stripVTControlCharacters } from "node:util";
import { snapshot, test } from "node:test";
const execFileAsync = promisify(execFile);
// Serialize strings as-is so multiline output is human-readable in snapshots
snapshot.setDefaultSnapshotSerializers([
(value) => (typeof value === "string" ? value : undefined),
]);
// Get all files in tests directory
const files = readdirSync("tests");
// Files to ignore
const ignore = [
"index.js",
"index.js.snapshot",
"main.js",
"mock-agent.js",
"README.md",
];
const testFiles = files.filter((file) => !ignore.includes(file)).sort();
// Throw an error if there is a file that does not end with test.js in the tests directory
for (const file of testFiles) {
if (!file.endsWith(".test.js")) {
throw new Error(`File ${file} does not end with .test.js`);
}
test(file, async (t) => {
// Override Actions environment variables that change `core`’s behavior
const {
GITHUB_OUTPUT,
GITHUB_STATE,
HTTP_PROXY,
HTTPS_PROXY,
http_proxy,
https_proxy,
NO_PROXY,
no_proxy,
NODE_OPTIONS,
NODE_USE_ENV_PROXY,
...env
} = process.env;
let stderr, stdout;
try {
// Omit stack traces so snapshots don't change with Node.js or dependency updates
({ stderr, stdout } = await execFileAsync(
"node",
["--stack-trace-limit=0", `tests/${file}`],
{ env },
));
} catch (error) {
if (!(error instanceof Error) || !("stderr" in error) || !("stdout" in error)) {
throw error;
}
({ stderr, stdout } = error);
}
const trimmedStderr = stripVTControlCharacters(stderr).replace(/\r?\n$/, "");
const trimmedStdout = stripVTControlCharacters(stdout).replace(/\r?\n$/, "");
await t.test("stderr", (t) => {
if (trimmedStderr) t.assert.snapshot(trimmedStderr);
else t.assert.strictEqual(trimmedStderr, "");
});
await t.test("stdout", (t) => {
if (trimmedStdout) t.assert.snapshot(trimmedStdout);
else t.assert.strictEqual(trimmedStdout, "");
});
});
}