Skip to content

Commit

Permalink
assert: allow getErrMessage to check deeper into the stacktrace
Browse files Browse the repository at this point in the history
  • Loading branch information
RedYetiDev committed Sep 5, 2024
1 parent 2bd6a57 commit aa36521
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
20 changes: 17 additions & 3 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,20 +282,34 @@ function parseCode(code, offset) {
throw null;
}

function getInvokingCall(stack) {
// Try to get the userland function that invoked this assertion
for (let i = 0; i < stack.length; i++) {
const call = stack[i];
const filename = call.getFileName();
if (StringPrototypeStartsWith(filename, 'node:') && BuiltinModule.exists(StringPrototypeSlice(filename, 5))) {
continue;
} else return call;
}
// If that's not possible, just return the function that did.
return stack[0];
}

function getErrMessage(message, fn) {
const tmpLimit = Error.stackTraceLimit;
const errorStackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
// Make sure the limit is set to 1. Otherwise it could fail (<= 0) or it
// does to much work.
if (errorStackTraceLimitIsWritable) Error.stackTraceLimit = 1;
// does to much work. The limit is set to 2, as this allows any wrappers
// around this assertion function to be skipped.
if (errorStackTraceLimitIsWritable) Error.stackTraceLimit = 2;
// We only need the stack trace. To minimize the overhead use an object
// instead of an error.
const err = {};
ErrorCaptureStackTrace(err, fn);
if (errorStackTraceLimitIsWritable) Error.stackTraceLimit = tmpLimit;

overrideStackTrace.set(err, (_, stack) => stack);
const call = err.stack[0];
const call = getInvokingCall(err.stack);

let filename = call.getFileName();
const line = call.getLineNumber() - 1;
Expand Down
4 changes: 4 additions & 0 deletions test/parallel/test-runner-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,7 @@ test('only methods from node:assert are on t.assert', (t) => {
'throws',
]);
});

test('t.assert.ok correctly parses the stacktrace', (t) => {
t.assert.throws(() => t.assert.ok(1 === 2), /t\.assert\.ok\(1 === 2\)/);
});

0 comments on commit aa36521

Please sign in to comment.