Skip to content

Commit f6f68cb

Browse files
committed
assert: avoid expensive diff for large values
1 parent d080801 commit f6f68cb

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

lib/internal/assert/assertion_error.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ const kReadableOperator = {
4242

4343
const kMaxShortStringLength = 12;
4444
const kMaxLongStringLength = 512;
45+
const kMaxDiffLineCount = 1000;
46+
const kMaxDiffLinesToShow = 50;
4547

4648
const kMethodsWithCustomMessageDiff = new SafeSet()
4749
.add('deepStrictEqual')
@@ -182,6 +184,13 @@ function isSimpleDiff(actual, inspectedActual, expected, inspectedExpected) {
182184
return typeof actual !== 'object' || actual === null || typeof expected !== 'object' || expected === null;
183185
}
184186

187+
function getTruncatedDiffValue(lines) {
188+
if (lines.length > kMaxDiffLinesToShow) {
189+
return `${ArrayPrototypeJoin(ArrayPrototypeSlice(lines, 0, kMaxDiffLinesToShow), '\n')}\n...`;
190+
}
191+
return ArrayPrototypeJoin(lines, '\n');
192+
}
193+
185194
function createErrDiff(actual, expected, operator, customMessage, diffType = 'simple') {
186195
operator = checkOperator(actual, expected, operator);
187196

@@ -213,6 +222,13 @@ function createErrDiff(actual, expected, operator, customMessage, diffType = 'si
213222
message = ArrayPrototypeJoin(inspectedSplitActual, '\n');
214223
}
215224
header = '';
225+
} else if (
226+
diffType !== 'full' &&
227+
inspectedSplitActual.length + inspectedSplitExpected.length > kMaxDiffLineCount
228+
) {
229+
message = `\n${colors.green}+${colors.white} ${getTruncatedDiffValue(inspectedSplitActual)}\n` +
230+
`${colors.red}-${colors.white} ${getTruncatedDiffValue(inspectedSplitExpected)}`;
231+
skipped = true;
216232
} else {
217233
const checkCommaDisparity = actual != null && typeof actual === 'object';
218234
const diff = myersDiff(inspectedSplitActual, inspectedSplitExpected, checkCommaDisparity);

test/parallel/test-assert-deep.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1180,6 +1180,19 @@ test('Strict equal with identical objects that are not identical ' +
11801180
);
11811181
});
11821182

1183+
test('Strict equal skips line diff for very large objects', () => {
1184+
const buffer = Buffer.alloc(1_000);
1185+
1186+
assert.throws(
1187+
() => assert.strictEqual(buffer, [buffer]),
1188+
{
1189+
code: 'ERR_ASSERTION',
1190+
name: 'AssertionError',
1191+
message: /Skipped lines[\s\S]*Buffer\(1000\)/
1192+
}
1193+
);
1194+
});
1195+
11831196
test('Basic valueOf check', () => {
11841197
const a = new String(1);
11851198
a.valueOf = undefined;

0 commit comments

Comments
 (0)