Skip to content

Commit

Permalink
fix(sinonjs#2484): add assertion log limit
Browse files Browse the repository at this point in the history
Co-authored-by: Spencer Goossens <sgoossens18@gmail.com>
Co-authored-by: Carl-Erik Kopseng <carlerik@gmail.com>
  • Loading branch information
fatso83 and sgoossens committed Oct 25, 2023
1 parent dbde881 commit 0331e66
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
32 changes: 30 additions & 2 deletions lib/sinon/assert.js
Expand Up @@ -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;
Expand Down
12 changes: 12 additions & 0 deletions test/assert-test.js
Expand Up @@ -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 () {
Expand Down

0 comments on commit 0331e66

Please sign in to comment.