assert: limit string inspection when logging assertion errors

This makes sure long strings as `actual` or `expected` values on an
`AssertionError` won't be logged completely. This is important as
the actual value is somewhat redundant in combination with the error
message which already logs the difference between the input values.

PR-URL: https://github.com/nodejs/node/pull/28058
Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
Ruben Bridgewater 2019-06-02 17:36:24 +02:00 committed by Rich Trott
parent f7ffa52312
commit a3ea54f5ab

View File

@ -429,11 +429,37 @@ class AssertionError extends Error {
}
[inspect.custom](recurseTimes, ctx) {
// Long strings should not be fully inspected.
const tmpActual = this.actual;
const tmpExpected = this.expected;
for (const name of ['actual', 'expected']) {
if (typeof this[name] === 'string') {
const lines = this[name].split('\n');
if (lines.length > 10) {
lines.length = 10;
this[name] = `${lines.join('\n')}\n...`;
} else if (this[name].length > 512) {
this[name] = `${this[name].slice(512)}...`;
}
}
}
// This limits the `actual` and `expected` property default inspection to
// the minimum depth. Otherwise those values would be too verbose compared
// to the actual error message which contains a combined view of these two
// input values.
return inspect(this, { ...ctx, customInspect: false, depth: 0 });
const result = inspect(this, {
...ctx,
customInspect: false,
depth: 0
});
// Reset the properties after inspection.
this.actual = tmpActual;
this.expected = tmpExpected;
return result;
}
}