Skip to content

Commit 2a9d67a

Browse files
authored
fix(diff): truncate to avoid crash on diff large objects (#7133)
1 parent 8967f09 commit 2a9d67a

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

packages/utils/src/diff/index.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ const FORMAT_OPTIONS = {
5757
}
5858
const FALLBACK_FORMAT_OPTIONS = {
5959
callToJSON: false,
60-
maxDepth: 10,
60+
maxDepth: 8,
6161
plugins: PLUGINS,
6262
}
6363

@@ -97,8 +97,18 @@ export function diff(a: any, b: any, options?: DiffOptions): string | undefined
9797
const { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator }
9898
= normalizeDiffOptions(options)
9999
const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options)
100-
const aDisplay = prettyFormat(a, formatOptions)
101-
const bDisplay = prettyFormat(b, formatOptions)
100+
let aDisplay = prettyFormat(a, formatOptions)
101+
let bDisplay = prettyFormat(b, formatOptions)
102+
// even if prettyFormat prints successfully big objects,
103+
// large string can choke later on (concatenation? RPC?),
104+
// so truncate it to a reasonable length here.
105+
// (For example, playwright's ElementHandle can become about 200_000_000 length string)
106+
const MAX_LENGTH = 100_000
107+
function truncate(s: string) {
108+
return s.length <= MAX_LENGTH ? s : (`${s.slice(0, MAX_LENGTH)}...`)
109+
}
110+
aDisplay = truncate(aDisplay)
111+
bDisplay = truncate(bDisplay)
102112
const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)} \n${aDisplay}`
103113
const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)} \n${bDisplay}`
104114
return `${aDiff}\n\n${bDiff}`

test/core/test/diff.test.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -331,13 +331,19 @@ test('getter only property', () => {
331331
`)
332332
})
333333

334-
function getErrorDiff(actual: unknown, expected: unknown, options?: DiffOptions) {
334+
test('truncate large diff', () => {
335+
const diff = getErrorDiff(Array.from({ length: 500_000 }).fill(0), 1234)
336+
expect(diff.length).lessThan(200_000)
337+
expect(diff.trim()).toMatch(/\.\.\.$/)
338+
})
339+
340+
function getErrorDiff(actual: unknown, expected: unknown, options?: DiffOptions): string {
335341
try {
336342
expect(actual).toEqual(expected)
337343
}
338344
catch (e) {
339345
const error = processError(e, options)
340346
return error.diff
341347
}
342-
expect.unreachable()
348+
return expect.unreachable()
343349
}

0 commit comments

Comments
 (0)