Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

assert: refactor to avoid unsafe array iteration #37344

Merged
merged 1 commit into from Feb 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 16 additions & 10 deletions lib/internal/assert/assertion_error.js
Expand Up @@ -313,6 +313,17 @@ function createErrDiff(actual, expected, operator) {
return `${msg}${skipped ? skippedMsg : ''}\n${res}${other}${end}${indicator}`;
}

function addEllipsis(string) {
const lines = StringPrototypeSplit(string, '\n', 11);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aduh95 Thanks for fixing the bug. Why did we add 11 here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We only want to keep the first 10 lines, we can give up splitting the string at the 11th line.

if (lines.length > 10) {
lines.length = 10;
return `${ArrayPrototypeJoin(lines, '\n')}\n...`;
} else if (string.length > 512) {
return `${StringPrototypeSlice(string, 512)}...`;
}
return string;
}

class AssertionError extends Error {
constructor(options) {
validateObject(options, 'options');
Expand Down Expand Up @@ -467,16 +478,11 @@ class AssertionError extends Error {
const tmpActual = this.actual;
const tmpExpected = this.expected;

for (const name of ['actual', 'expected']) {
if (typeof this[name] === 'string') {
const lines = StringPrototypeSplit(this[name], '\n');
if (lines.length > 10) {
lines.length = 10;
this[name] = `${ArrayPrototypeJoin(lines, '\n')}\n...`;
} else if (this[name].length > 512) {
this[name] = `${StringPrototypeSlice(this[name], 512)}...`;
}
}
if (typeof this.actual === 'string') {
this.actual = addEllipsis(this.actual);
}
if (typeof this.expected === 'string') {
this.expected = addEllipsis(this.expected);
}

// This limits the `actual` and `expected` property default inspection to
Expand Down