From 4602f90973cf2ec9a5326524e4d61ec6c4994ea3 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Thu, 24 Aug 2017 23:25:22 -0300 Subject: [PATCH] assert: improve AssertionError in case of "Errors" Showing the stack trace in a error message obfuscates the actual message and should not be visible therefore. --- lib/internal/errors.js | 23 ++++++++++++++--------- test/parallel/test-assert.js | 9 +++++++++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/lib/internal/errors.js b/lib/internal/errors.js index d270c3dd44b0e1..26e9cc09ec24e2 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -35,21 +35,26 @@ class AssertionError extends Error { if (typeof options !== 'object' || options === null) { throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object'); } - if (options.message) { - super(options.message); + var { actual, expected, message, operator, stackStartFunction } = options; + if (message) { + super(message); } else { + if (actual && actual.stack && actual instanceof Error) + actual = `${actual.name}: ${actual.message}`; + if (expected && expected.stack && expected instanceof Error) + expected = `${expected.name}: ${expected.message}`; if (util === null) util = require('util'); - super(`${util.inspect(options.actual).slice(0, 128)} ` + - `${options.operator} ${util.inspect(options.expected).slice(0, 128)}`); + super(`${util.inspect(actual).slice(0, 128)} ` + + `${operator} ${util.inspect(expected).slice(0, 128)}`); } - this.generatedMessage = !options.message; + this.generatedMessage = !message; this.name = 'AssertionError [ERR_ASSERTION]'; this.code = 'ERR_ASSERTION'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - Error.captureStackTrace(this, options.stackStartFunction); + this.actual = actual; + this.expected = expected; + this.operator = operator; + Error.captureStackTrace(this, stackStartFunction); } } diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 30e80274890ce6..9569f0c16932b4 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -715,3 +715,12 @@ assert.throws(() => { })); }); } + +common.expectsError( + () => assert.strictEqual(new Error('foo'), new Error('foobar')), + { + code: 'ERR_ASSERTION', + type: assert.AssertionError, + message: /^'Error: foo' === 'Error: foobar'$/ + } +);