assert: add partial support for evaluated code in simple assert

This makes sure using `assert.ok()` in `new Function()` statements
visualizes the actual call site in the error message.

PR-URL: https://github.com/nodejs/node/pull/27781
Reviewed-By: Rich Trott <rtrott@gmail.com>
pull/28032/merge
Ruben Bridgewater 2019-05-20 12:56:21 +02:00 committed by Rich Trott
parent 4a3af65a88
commit 1a0fd60277
2 changed files with 41 additions and 21 deletions

View File

@ -269,42 +269,55 @@ function getErrMessage(message, fn) {
Error.prepareStackTrace = tmpPrepare;
const filename = call.getFileName();
if (!filename) {
return message;
}
const line = call.getLineNumber() - 1;
let column = call.getColumnNumber() - 1;
let identifier;
let code;
const identifier = `${filename}${line}${column}`;
if (filename) {
identifier = `${filename}${line}${column}`;
// Skip Node.js modules!
if (filename.endsWith('.js') &&
NativeModule.exists(filename.slice(0, -3))) {
errorCache.set(identifier, undefined);
return;
}
} else {
const fn = call.getFunction();
if (!fn) {
return message;
}
code = String(fn);
identifier = `${code}${line}${column}`;
}
if (errorCache.has(identifier)) {
return errorCache.get(identifier);
}
// Skip Node.js modules!
if (filename.endsWith('.js') && NativeModule.exists(filename.slice(0, -3))) {
errorCache.set(identifier, undefined);
return;
}
let fd;
try {
// Set the stack trace limit to zero. This makes sure unexpected token
// errors are handled faster.
Error.stackTraceLimit = 0;
if (decoder === undefined) {
const { StringDecoder } = require('string_decoder');
decoder = new StringDecoder('utf8');
if (filename) {
if (decoder === undefined) {
const { StringDecoder } = require('string_decoder');
decoder = new StringDecoder('utf8');
}
fd = openSync(filename, 'r', 0o666);
// Reset column and message.
[column, message] = getCode(fd, line, column);
// Flush unfinished multi byte characters.
decoder.end();
} else {
for (let i = 0; i < line; i++) {
code = code.slice(code.indexOf('\n') + 1);
}
[column, message] = parseCode(code, column);
}
fd = openSync(filename, 'r', 0o666);
// Reset column and message.
[column, message] = getCode(fd, line, column);
// Flush unfinished multi byte characters.
decoder.end();
// Always normalize indentation, otherwise the message could look weird.
if (message.includes('\n')) {
if (EOL === '\r\n') {

View File

@ -859,6 +859,13 @@ common.expectsError(
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n assert(1 === 2)\n'
}
);
assert.throws(
() => eval('console.log("FOO");\nassert.ok(1 === 2);'),
{
code: 'ERR_ASSERTION',
message: 'false == true'
}
);