From a3ea54f5abd48decb1526c58fafd4cd757dbb02b Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sun, 2 Jun 2019 17:36:24 +0200 Subject: [PATCH] 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 --- lib/internal/assert/assertion_error.js | 28 +++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index 18d9951af0d..ce171710c87 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -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; } }