Skip to content

Commit

Permalink
fix(diff): truncate to avoid crash on diff large objects (#7133)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored Dec 27, 2024
1 parent 8967f09 commit 2a9d67a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
16 changes: 13 additions & 3 deletions packages/utils/src/diff/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const FORMAT_OPTIONS = {
}
const FALLBACK_FORMAT_OPTIONS = {
callToJSON: false,
maxDepth: 10,
maxDepth: 8,
plugins: PLUGINS,
}

Expand Down Expand Up @@ -97,8 +97,18 @@ export function diff(a: any, b: any, options?: DiffOptions): string | undefined
const { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator }
= normalizeDiffOptions(options)
const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options)
const aDisplay = prettyFormat(a, formatOptions)
const bDisplay = prettyFormat(b, formatOptions)
let aDisplay = prettyFormat(a, formatOptions)
let bDisplay = prettyFormat(b, formatOptions)
// even if prettyFormat prints successfully big objects,
// large string can choke later on (concatenation? RPC?),
// so truncate it to a reasonable length here.
// (For example, playwright's ElementHandle can become about 200_000_000 length string)
const MAX_LENGTH = 100_000
function truncate(s: string) {
return s.length <= MAX_LENGTH ? s : (`${s.slice(0, MAX_LENGTH)}...`)
}
aDisplay = truncate(aDisplay)
bDisplay = truncate(bDisplay)
const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)} \n${aDisplay}`
const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)} \n${bDisplay}`
return `${aDiff}\n\n${bDiff}`
Expand Down
10 changes: 8 additions & 2 deletions test/core/test/diff.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,13 +331,19 @@ test('getter only property', () => {
`)
})

function getErrorDiff(actual: unknown, expected: unknown, options?: DiffOptions) {
test('truncate large diff', () => {
const diff = getErrorDiff(Array.from({ length: 500_000 }).fill(0), 1234)
expect(diff.length).lessThan(200_000)
expect(diff.trim()).toMatch(/\.\.\.$/)
})

function getErrorDiff(actual: unknown, expected: unknown, options?: DiffOptions): string {
try {
expect(actual).toEqual(expected)
}
catch (e) {
const error = processError(e, options)
return error.diff
}
expect.unreachable()
return expect.unreachable()
}

0 comments on commit 2a9d67a

Please sign in to comment.