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 <[email protected]>
Reviewed-By: Rich Trott <[email protected]>
Reviewed-By: Anna Henningsen <[email protected]>
  • Loading branch information
BridgeAR authored and codebytere committed Feb 17, 2020
1 parent 89dcf73 commit 2db7593
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
}

0 comments on commit 2db7593

Please sign in to comment.