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

chore: custom jest Field equality #7012

Merged
merged 1 commit into from
Jun 12, 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
30 changes: 19 additions & 11 deletions yarn-project/foundation/src/fields/fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@ type DerivedField<T extends BaseField> = {
* Conversions from Buffer to BigInt and vice-versa are not cheap.
* We allow construction with either form and lazily convert to other as needed.
* We only check we are within the field modulus when initializing with bigint.
* If NODE_ENV === 'test', we will always initialize both types to check the modulus.
* This is also necessary in test environment as a lot of tests just use deep equality to check equality.
* WARNING: This could lead to a bugs in production that don't reveal in tests, but it's low risk.
*/
abstract class BaseField {
static SIZE_IN_BYTES = 32;
Expand Down Expand Up @@ -67,14 +64,6 @@ abstract class BaseField {
} else {
throw new Error(`Type '${typeof value}' with value '${value}' passed to BaseField ctor.`);
}

// Loads of our tests are just doing deep equality rather than calling e.g. toBigInt() first.
// This ensures the deep equality passes regardless of the internal representation.
// It also ensures the value range is checked even when initializing as a buffer.
if (process.env.NODE_ENV === 'test') {
this.toBuffer();
this.toBigInt();
}
}

protected abstract modulus(): bigint;
Expand Down Expand Up @@ -397,3 +386,22 @@ export const GrumpkinScalar = Fq;
export function reduceFn<TInput, TField extends BaseField>(fn: (input: TInput) => Buffer, field: DerivedField<TField>) {
return (input: TInput) => fromBufferReduce(fn(input), field);
}

/** If we are in test mode, we register a special equality for fields. */
if (process.env.NODE_ENV === 'test') {
const areFieldsEqual = (a: unknown, b: unknown): boolean | undefined => {
const isAField = a instanceof BaseField;
const isBField = b instanceof BaseField;

if (isAField && isBField) {
return a.equals(b);
} else if (isAField === isBField) {
return undefined;
} else {
return false;
}
};

// `addEqualityTesters` doesn't seem to be in the types yet.
(expect as any).addEqualityTesters([areFieldsEqual]);
}
Loading