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

Refactor build assert #5856

Merged
merged 2 commits into from
Dec 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 39 additions & 29 deletions packages/hardhat-chai-matchers/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,44 @@ import { AssertionError } from "chai";
// just a generic function type to avoid errors from the ban-types eslint rule
export type Ssfi = (...args: any[]) => any;

type Message = string | (() => string);

function evalMessage(message?: Message): string {
if (message === undefined) {
throw new Error(
"Assertion doesn't have an error message. Please open an issue to report this."
);
}

return typeof message === "function" ? message() : message;
}

function buildNegated(ssfi: Ssfi) {
return function (
condition: boolean,
_messageFalse?: Message,
messageTrue?: Message
) {
if (condition) {
const message = evalMessage(messageTrue);
throw new AssertionError(message, undefined, ssfi);
}
};
}

function buildNormal(ssfi: Ssfi) {
return function (
condition: boolean,
messageFalse?: Message,
_messageTrue?: Message
) {
if (!condition) {
const message = evalMessage(messageFalse);
throw new AssertionError(message, undefined, ssfi);
}
};
}

/**
* This function is used by the matchers to obtain an `assert` function, which
* should be used instead of `this.assert`.
Expand All @@ -20,35 +58,7 @@ export type Ssfi = (...args: any[]) => any;
* existing matchers for a reference of something that works well enough.
*/
export function buildAssert(negated: boolean, ssfi: Ssfi) {
return function (
condition: boolean,
messageFalse?: string | (() => string),
messageTrue?: string | (() => string)
) {
if (!negated && !condition) {
if (messageFalse === undefined) {
throw new Error(
"Assertion doesn't have an error message. Please open an issue to report this."
);
}

const message =
typeof messageFalse === "function" ? messageFalse() : messageFalse;
throw new AssertionError(message, undefined, ssfi);
}

if (negated && condition) {
if (messageTrue === undefined) {
throw new Error(
"Assertion doesn't have an error message. Please open an issue to report this."
);
}

const message =
typeof messageTrue === "function" ? messageTrue() : messageTrue;
throw new AssertionError(message, undefined, ssfi);
}
};
return negated ? buildNegated(ssfi) : buildNormal(ssfi);
}

export type AssertWithSsfi = ReturnType<typeof buildAssert>;
Loading