Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

fix: prevent diff hang on large/complex objects (#5898)

TomTensor6695fba397a6
diff --git a/lib/reporters/base.js b/lib/reporters/base.js
index 296f5871..4a0bae09 100644
--- a/lib/reporters/base.js
+++ b/lib/reporters/base.js
@@ -275,8 +275,77 @@ var showDiff = (exports.showDiff = function (err) {
);
});
+/**
+ * Estimate the serialized size of a value.
+ * Returns -1 if the value is too complex to estimate safely.
+ *
+ * @private
+ * @param {*} val
+ * @param {number} maxDepth
+ * @param {Set<*>} [seen]
+ * @returns {number}
+ */
+function estimateSize(val, maxDepth, seen) {
+ if (maxDepth <= 0) return -1;
+
+ seen = seen || new Set();
+
+ const type = typeof val;
+ if (type === "string") return val.length;
+ if (type === "number" || type === "boolean") return 8;
+ if (val === null || val === undefined) return 4;
+
+ // Avoid circular references
+ if (type === "object") {
+ if (seen.has(val)) return -1;
+ seen.add(val);
+
+ // Special handling for Buffers - they can be massive
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(val)) {
+ return val.length > 10000 ? -1 : val.length * 2;
+ }
+
+ let size = 2; // {} or []
+ try {
+ const keys = Object.keys(val);
+ if (keys.length > 1000) return -1; // Too many keys
+
+ for (const key of keys) {
+ const childSize = estimateSize(val[key], maxDepth - 1, seen);
+ if (childSize === -1) return -1;
+ size += key.length + childSize + 4; // key + value + formatting
+ if (size > 100000) return -1; // Bail early if getting huge
+ }
+ } catch {
+ return -1;
+ }
+
+ seen.delete(val);
+ return size;
+ }
+
+ return 50; // Default estimate for other types
+}
+
function stringifyDiffObjs(err) {
if (!utils.isString(err.actual) || !utils.isString(err.expected)) {
+ // Estimate size before stringifying to avoid hangs
+ const maxSafeSize = exports.maxDiffSize || 8192;
+ const actualSize = estimateSize(err.actual, 10);
+ const expectedSize = estimateSize(err.expected, 10);
+
+ if (
+ actualSize === -1 ||
+ expectedSize === -1 ||
+ actualSize > maxSafeSize ||
+ expectedSize > maxSafeSize
+ ) {
+ // Values too large/complex - provide safe fallback
+ err.actual = "[object too large to diff]";
+ err.expected = "[object too large to diff]";
+ return;
+ }
+
err.actual = utils.stringify(err.actual);
err.expected = utils.stringify(err.expected);
}
diff --git a/test/integration/fixtures/diff-hang-protection.fixture.js b/test/integration/fixtures/diff-hang-protection.fixture.js
new file mode 100644
index 00000000..314ca3c7
--- /dev/null
+++ b/test/integration/fixtures/diff-hang-protection.fixture.js
@@ -0,0 +1,36 @@
+'use strict';
+
+const { expect } = require('chai');
+
+describe('Diff hang protection', function () {
+ it('should not hang when comparing large buffers', function () {
+ const buf1 = Buffer.alloc(50000, 'a');
+ const buf2 = Buffer.alloc(50000, 'b');
+
+ expect(buf1).to.deep.equal(buf2);
+ });
+
+ it('should not hang when comparing deeply nested objects', function () {
+ let obj1 = { value: 1 };
+ let obj2 = { value: 2 };
+
+ for (let i = 0; i < 100; i++) {
+ obj1 = { nested: obj1, extra: obj1 };
+ obj2 = { nested: obj2, extra: obj2 };
+ }
+
+ expect(obj1).to.deep.equal(obj2);
+ });
+
+ it('should not hang when comparing objects with many keys', function () {
+ const obj1 = {};
+ const obj2 = {};
+
+ for (let i = 0; i < 5000; i++) {
+ obj1['key' + i] = 'value' + i;
+ obj2['key' + i] = 'different' + i;
+ }
+
+ expect(obj1).to.deep.equal(obj2);
+ });
+});
diff --git a/test/unit/reporters/base-diff-protection.spec.js b/test/unit/reporters/base-diff-protection.spec.js
new file mode 100644
index 00000000..6340d162
--- /dev/null
+++ b/test/unit/reporters/base-diff-protection.spec.js
@@ -0,0 +1,130 @@
+"use strict";
+
+var sinon = require("sinon");
+var reporters = require("../../../").reporters;
+var Base = reporters.Base;
+var chaiExpect = require("chai").expect;
+
+describe("Base reporter diff hang protection", function () {
+ var stdout;
+
+ var gather = function (chunk) {
+ stdout.push(chunk);
+ };
+
+ beforeEach(function () {
+ sinon.stub(Base, "useColors").value(false);
+ sinon.stub(process.stdout, "write").callsFake(gather);
+ stdout = [];
+ });
+
+ afterEach(function () {
+ sinon.restore();
+ });
+
+ function list(tests) {
+ try {
+ Base.list(tests);
+ } finally {
+ sinon.restore();
+ }
+ }
+
+ function makeFailedTest(title, actual, expected) {
+ var err = new Error("values differ");
+ err.actual = actual;
+ err.expected = expected;
+ err.showDiff = true;
+ return {
+ isPending: function () {
+ return false;
+ },
+ titlePath: function () {
+ return [title];
+ },
+ err: err,
+ fullTitle: function () {
+ return title;
+ },
+ };
+ }
+
+ describe("large buffers", function () {
+ it("should not hang when diffing large buffers", function () {
+ this.timeout(2000);
+
+ var buf1 = Buffer.alloc(50000, "a");
+ var buf2 = Buffer.alloc(50000, "b");
+ var test = makeFailedTest("large buffer test", buf1, buf2);
+
+ var start = Date.now();
+ list([test]);
+ var elapsed = Date.now() - start;
+
+ chaiExpect(elapsed).to.be.below(1000);
+ // Verify the err was handled (either truncated or replaced with fallback)
+ chaiExpect(test.err.actual).to.be.a("string");
+ });
+ });
+
+ describe("deeply nested objects", function () {
+ it("should not hang when diffing deeply nested objects", function () {
+ this.timeout(2000);
+
+ var obj1 = { value: 1 };
+ var obj2 = { value: 2 };
+
+ for (var i = 0; i < 50; i++) {
+ obj1 = { nested: obj1, extra: obj1 };
+ obj2 = { nested: obj2, extra: obj2 };
+ }
+
+ var test = makeFailedTest("nested object test", obj1, obj2);
+
+ var start = Date.now();
+ list([test]);
+ var elapsed = Date.now() - start;
+
+ chaiExpect(elapsed).to.be.below(1000);
+ chaiExpect(test.err.actual).to.be.a("string");
+ });
+ });
+
+ describe("objects with many keys", function () {
+ it("should not hang when diffing objects with many keys", function () {
+ this.timeout(2000);
+
+ var obj1 = {};
+ var obj2 = {};
+
+ for (var i = 0; i < 2000; i++) {
+ obj1["key" + i] = "value" + i;
+ obj2["key" + i] = "different" + i;
+ }
+
+ var test = makeFailedTest("many keys test", obj1, obj2);
+
+ var start = Date.now();
+ list([test]);
+ var elapsed = Date.now() - start;
+
+ chaiExpect(elapsed).to.be.below(1000);
+ chaiExpect(test.err.actual).to.be.a("string");
+ });
+ });
+
+ describe("normal-sized objects", function () {
+ it("should still produce a valid diff for small objects", function () {
+ var test = makeFailedTest(
+ "small object test",
+ { a: 1, b: 2 },
+ { a: 1, b: 3 },
+ );
+
+ list([test]);
+
+ var output = stdout.join("");
+ chaiExpect(output).to.not.contain("too large to diff");
+ });
+ });
+});