From f01971915bd3cd63e07ae04b60c44b2273fa71b1 Mon Sep 17 00:00:00 2001 From: Carl-Erik Kopseng Date: Wed, 25 Oct 2023 10:31:12 +0100 Subject: [PATCH] fix(#2484): add assertion log limit Co-authored-by: Spencer Goossens Co-authored-by: Carl-Erik Kopseng --- lib/sinon/assert.js | 32 ++++++++++++++++++++++++++++++-- test/assert-test.js | 12 ++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/lib/sinon/assert.js b/lib/sinon/assert.js index fc7dbdbe3..567135d51 100644 --- a/lib/sinon/assert.js +++ b/lib/sinon/assert.js @@ -15,12 +15,40 @@ const forEach = arrayProto.forEach; const join = arrayProto.join; const splice = arrayProto.splice; -function createAssertObject() { +function applyDefaults(obj, defaults) { + for (const key of Object.keys(defaults)) { + const val = obj[key]; + if (val === null || typeof val === "undefined") { + obj[key] = defaults[key]; + } + } +} + +/** + * @param {object} [opts] options bag + * @param {boolean} [opts.shouldLimitAssertionLogs] default is false + * @param {number} [opts.assertionLogLimit] default is 10K + * @returns {object} object with multiple assertion methods + */ +function createAssertObject(opts) { + const cleanedAssertOptions = opts || {}; + applyDefaults(cleanedAssertOptions, { + shouldLimitAssertionLogs: false, + assertionLogLimit: 1e4, + }); + const assert = { failException: "AssertError", fail: function fail(message) { - const error = new Error(message); + let msg = message; + if (cleanedAssertOptions.shouldLimitAssertionLogs) { + msg = message.substring( + 0, + cleanedAssertOptions.assertionLogLimit, + ); + } + const error = new Error(msg); error.name = this.failException || assert.failException; throw error; diff --git a/test/assert-test.js b/test/assert-test.js index 036dc2231..69b675017 100644 --- a/test/assert-test.js +++ b/test/assert-test.js @@ -65,6 +65,18 @@ describe("assert", function () { sinonAssert.failException = this.exceptionName; }); + it("can be configured to limit the error message length", function () { + const customAssert = sinonAssert.createAssertObject({ + shouldLimitAssertionLogs: true, + assertionLogLimit: 10, + }); + + assert.exception( + () => customAssert.fail("1234567890--THIS SHOULD NOT SHOW--"), + { message: "1234567890" }, + ); + }); + it("throws exception", function () { assert.exception( function () {