From 2db7593838cc53b8f118d6e256dec2b89adc078c Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 20 Jan 2020 20:44:38 +0100 Subject: [PATCH] assert: align character indicators properly This makes sure color codes are not taken into account in case util.inspect's default value was changed. PR-URL: https://github.com/nodejs/node/pull/31429 Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Anna Henningsen --- lib/internal/assert/assertion_error.js | 12 ++++++++++-- test/parallel/test-assert.js | 13 +++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index a77414834d1e32..691f057ad281e3 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -13,6 +13,9 @@ const { inspect } = require('internal/util/inspect'); const { codes: { ERR_INVALID_ARG_TYPE } } = require('internal/errors'); +const { + removeColors, +} = require('internal/util'); let blue = ''; let green = ''; @@ -93,7 +96,12 @@ function createErrDiff(actual, expected, operator) { // equal, check further special handling. if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { - const inputLength = actualLines[0].length + expectedLines[0].length; + // Check for the visible length using the `removeColors()` function, if + // appropriate. + const c = inspect.defaultOptions.colors; + const actualRaw = c ? removeColors(actualLines[0]) : actualLines[0]; + const expectedRaw = c ? removeColors(expectedLines[0]) : expectedLines[0]; + const inputLength = actualRaw.length + expectedRaw.length; // If the character length of "actual" and "expected" together is less than // kMaxShortLength and if neither is an object and at least one of them is // not `zero`, use the strict equal comparison to visualize the output. @@ -110,7 +118,7 @@ function createErrDiff(actual, expected, operator) { // not a tty, use a default value of 80 characters. const maxLength = process.stderr.isTTY ? process.stderr.columns : 80; if (inputLength < maxLength) { - while (actualLines[0][i] === expectedLines[0][i]) { + while (actualRaw[i] === expectedRaw[i]) { i++; } // Ignore the first characters. diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index d3f4435d17c266..115d818b0be568 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -1461,3 +1461,16 @@ assert.throws( ); assert.doesNotMatch('I will pass', /different$/); } + +{ + const tempColor = inspect.defaultOptions.colors; + assert.throws(() => { + inspect.defaultOptions.colors = true; + // Guarantee the position indicator is placed correctly. + assert.strictEqual(111554n, 11111115); + }, (err) => { + assert.strictEqual(inspect(err).split('\n')[5], ' ^'); + inspect.defaultOptions.colors = tempColor; + return true; + }); +}