Skip to content

Commit

Permalink
chore: custom jest Field equality (#7012)
Browse files Browse the repository at this point in the history
Instead of always creating all representations, just provide a custom
jest equality (available since 29.x)
  • Loading branch information
fcarreiro authored Jun 12, 2024
1 parent a8c3c3f commit 1a198b8
Showing 1 changed file with 19 additions and 11 deletions.
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 @@ -405,3 +394,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]);
}

0 comments on commit 1a198b8

Please sign in to comment.