test: improve output of child process utilities

- Display command and options when it fails
- Keep the caller line at the top of the stack trace.

PR-URL: https://github.com/nodejs/node/pull/54622
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
This commit is contained in:
Joyee Cheung 2024-08-31 00:41:04 +02:00 committed by GitHub
parent d49f47ee35
commit 0b120af159
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -60,13 +60,14 @@ function checkOutput(str, check) {
return { passed: true };
}
function expectSyncExit(child, {
function expectSyncExit(caller, spawnArgs, {
status,
signal,
stderr: stderrCheck,
stdout: stdoutCheck,
trim = false,
}) {
const child = spawnSync(...spawnArgs);
const failures = [];
let stderrStr, stdoutStr;
if (status !== undefined && child.status !== status) {
@ -83,7 +84,18 @@ function expectSyncExit(child, {
console.error(`${tag} --- stdout ---`);
console.error(stdoutStr === undefined ? child.stdout.toString() : stdoutStr);
console.error(`${tag} status = ${child.status}, signal = ${child.signal}`);
throw new Error(`${failures.join('\n')}`);
const error = new Error(`${failures.join('\n')}`);
if (spawnArgs[2]) {
error.options = spawnArgs[2];
}
let command = spawnArgs[0];
if (Array.isArray(spawnArgs[1])) {
command += ' ' + spawnArgs[1].join(' ');
}
error.command = command;
Error.captureStackTrace(error, caller);
throw error;
}
// If status and signal are not matching expectations, fail early.
@ -114,12 +126,11 @@ function expectSyncExit(child, {
function spawnSyncAndExit(...args) {
const spawnArgs = args.slice(0, args.length - 1);
const expectations = args[args.length - 1];
const child = spawnSync(...spawnArgs);
return expectSyncExit(child, expectations);
return expectSyncExit(spawnSyncAndExit, spawnArgs, expectations);
}
function spawnSyncAndExitWithoutError(...args) {
return expectSyncExit(spawnSync(...args), {
return expectSyncExit(spawnSyncAndExitWithoutError, [...args], {
status: 0,
signal: null,
});
@ -127,8 +138,7 @@ function spawnSyncAndExitWithoutError(...args) {
function spawnSyncAndAssert(...args) {
const expectations = args.pop();
const child = spawnSync(...args);
return expectSyncExit(child, {
return expectSyncExit(spawnSyncAndAssert, [...args], {
status: 0,
signal: null,
...expectations,