Skip to content

Commit

Permalink
assert: align character indicators properly
Browse files Browse the repository at this point in the history
This makes sure color codes are not taken into account in case
util.inspect's default value was changed.

PR-URL: #31429
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
  • Loading branch information
BridgeAR authored and codebytere committed Mar 30, 2020
1 parent c18cec7 commit f756c80
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/internal/assert/assertion_error.js
Expand Up @@ -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 = '';
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions test/parallel/test-assert.js
Expand Up @@ -1401,3 +1401,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;
});
}

0 comments on commit f756c80

Please sign in to comment.