From 8f8a0e348387fdcc3905d24b25c3fbc51e790b69 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Wed, 16 May 2018 18:10:08 +0200 Subject: [PATCH] assert: fix wrong message indentation If code is read from a file and that code is indented, it would be misaligned. This makes sure it has a natural indentation that is relative to the starting point of the assertion. PR-URL: https://github.com/nodejs/node/pull/20791 Reviewed-By: James M Snell Reviewed-By: Trivikram Kamat Reviewed-By: Khaidi Chu Reviewed-By: Matteo Collina --- lib/assert.js | 13 +++++++++ test/parallel/test-assert.js | 53 ++++++++++++++++++++++++++++++++---- 2 files changed, 60 insertions(+), 6 deletions(-) diff --git a/lib/assert.js b/lib/assert.js index 17b0059cba50e7..da92c02f640e46 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -192,6 +192,19 @@ function getErrMessage(call) { if (EOL === '\r\n') { message = message.replace(/\r\n/g, '\n'); } + // Always normalize indentation, otherwise the message could look weird. + if (message.indexOf('\n') !== -1) { + const tmp = message.split('\n'); + message = tmp[0]; + for (var i = 1; i < tmp.length; i++) { + let pos = 0; + while (pos < column && + (tmp[i][pos] === ' ' || tmp[i][pos] === '\t')) { + pos++; + } + message += `\n ${tmp[i].slice(pos)}`; + } + } message = 'The expression evaluated to a falsy value:' + `\n\n assert${ok}(${message})\n`; } diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index d81ef32cd82210..eb084e9b01cb2b 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -694,14 +694,55 @@ common.expectsError( { code: 'ERR_ASSERTION', type: assert.AssertionError, - message: 'The expression evaluated to a falsy value:\n\n ' + - "assert((() => 'string')()\n" + - ' // eslint-disable-next-line\n' + - ' ===\n' + - ' 123 instanceof\n' + - ' Buffer)\n' + message: 'The expression evaluated to a falsy value:\n\n' + + ' assert((() => \'string\')()\n' + + ' // eslint-disable-next-line\n' + + ' ===\n' + + ' 123 instanceof\n' + + ' Buffer)\n' + } +); + +common.expectsError( + () => { + a( + (() => 'string')() + // eslint-disable-next-line + === + 123 instanceof + Buffer + ); + }, + { + code: 'ERR_ASSERTION', + type: assert.AssertionError, + message: 'The expression evaluated to a falsy value:\n\n' + + ' assert((() => \'string\')()\n' + + ' // eslint-disable-next-line\n' + + ' ===\n' + + ' 123 instanceof\n' + + ' Buffer)\n' + } +); + +/* eslint-disable indent */ +common.expectsError(() => { +a(( + () => 'string')() === +123 instanceof +Buffer +); +}, { + code: 'ERR_ASSERTION', + type: assert.AssertionError, + message: 'The expression evaluated to a falsy value:\n\n' + + ' assert((\n' + + ' () => \'string\')() ===\n' + + ' 123 instanceof\n' + + ' Buffer)\n' } ); +/* eslint-enable indent */ common.expectsError( () => assert(null, undefined),