it("should reject any expression not containing an even number of signs (2)", () => {
  fc.assert(
    fc.property(
      fc
        .array(fc.constantFrom("(", "[", "{", ")", "]", "}"), { minLength: 1 })
        .filter((parentheses) => parentheses.length % 2 === 1)
        .map((parentheses) => parentheses.join("")),
      (invalidExpression) => {
        expect(validParentheses(invalidExpression)).toBe(false);
      }
    )
  );
})

Summary: An expression with an odd number of parentheses should be rejected as invalid by `validParentheses`.


unknown

it("should move the tower to the requested pillar", () => {
  fc.assert(
    fc.property(
      fc.constantFrom(0, 1, 2),
      fc.constantFrom(0, 1, 2),
      fc.integer({ min: 0, max: 10 }),
      (startPosition, endPosition, towerHeight) => {
        // Arrange
        const stacks = buildInitialStacks(startPosition, towerHeight);
        const expectedStacks = buildInitialStacks(endPosition, towerHeight);
        const move = (from: number, to: number) => {
          const head = stacks[from].pop()!; // not checked by this test
          stacks[to].push(head);
        };

        // Act
        hanoiTower(towerHeight, startPosition, endPosition, move);

        // Assert
        expect(stacks).toEqual(expectedStacks);
      }
    )
  );
})

Summary: The tower should be moved from a starting pillar to an ending pillar, resulting in stacks that match the expected configuration for the end position and given tower height.


it("should not pass twice by the same state", () => {
  fc.assert(
    fc.property(
      fc.constantFrom(0, 1, 2),
      fc.constantFrom(0, 1, 2),
      fc.integer({ min: 0, max: 10 }),
      (startPosition, endPosition, towerHeight) => {
        // Arrange
        const stacks = buildInitialStacks(startPosition, towerHeight);
        function stateToString(state: [number[], number[], number[]]): string {
          return `${state[0].join(".")}/${state[1].join(".")}/${state[2].join(
            "."
          )}`;
        }
        const seenStates = new Set<string>([stateToString(stacks)]);

        // Act / Assert
        const move = (from: number, to: number) => {
          const head = stacks[from].pop()!; // not checked by this test
          stacks[to].push(head);
          const newStateString = stateToString(stacks);
          expect(seenStates.has(newStateString)).toBe(false);
          seenStates.add(newStateString);
        };
        hanoiTower(towerHeight, startPosition, endPosition, move);
      }
    )
  );
})

Summary: A state in the Tower of Hanoi puzzle, represented by stacks, should not be revisited during moves.


it("should never request any changes when moving a string to itself", () => {
  fc.assert(
    fc.property(fc.fullUnicodeString(), (value) => {
      // Arrange / Act
      const numChanges = minimalNumberOfChangesToBeOther(value, value);

      // Assert
      expect(numChanges).toBe(0);
    })
  );
})

Summary: The number of changes needed to transform a string into itself should be zero.


it("should have exactly the same number of occurrences as source for each item", () => {
  fc.assert(
    fc.property(fc.array(fc.integer()), (data) => {
      const sortedData = sorted(data);
      expect(countEach(sortedData)).toEqual(countEach(data));
    })
  );
})

Summary: The number of occurrences for each item should remain the same in sorted and unsorted arrays.


assertAsyncProperty: (predicate: (...args: Ts) => Promise<boolean | void>) =>
            fc.assert(fc.asyncProperty(...arbitraries, predicate), params)

Summary: The property ensures that a predicate function, taking arbitrary arguments and returning a Promise, evaluates to true or void.


it("should check state leaf and ballot transformers (full credits voting)", async () => {
    const max = BigInt(2 ** 50);

    await fc.assert(
      fc.asyncProperty(
        fc.bigInt({ min: 1n, max }),
        fc.bigInt({ min: 1n, max }),
        fc.bigInt({ min: 1n, max }),
        fc.bigInt({ min: 1n, max }),
        fc.bigInt({ min: 1n, max: max - maxSignups }),
        fc.bigInt({ min: 1n, max: max - maxVoteOptions }),
        check,
      ),
    );

    async function check(
      votes: bigint,
      nonce: bigint,
      stateTreeIndex: bigint,
      voteOptionIndex: bigint,
      maxSignupsDifference: bigint,
      maxVoteOptionsDifference: bigint,
    ) {
      const { privateKey, publicKey } = new Keypair();
      const userCommand = new VoteCommand(stateTreeIndex, publicKey, voteOptionIndex, votes, nonce, 0n);
      const commandSignature = userCommand.sign(privateKey);

      const circuitInputs = {
        totalSignups: stateTreeIndex + maxSignupsDifference,
        voteOptions: voteOptionIndex + maxVoteOptionsDifference,
        stateLeafPublicKey: publicKey.asCircuitInputs() as unknown as [bigint, bigint],
        stateLeafVoiceCreditBalance: votes,
        ballotNonce: nonce - 1n,
        ballotCurrentVotesForOption: 0n,
        commandStateIndex: userCommand.stateIndex,
        commandPublicKey: userCommand.newPublicKey.asCircuitInputs() as unknown as [bigint, bigint],
        commandVoteOptionIndex: userCommand.voteOptionIndex,
        commandNewVoteWeight: userCommand.newVoteWeight,
        commandNonce: userCommand.nonce,
        commandPollId: userCommand.pollId,
        commandSalt: userCommand.salt,
        commandSignaturePoint: commandSignature.R8 as [bigint, bigint],
        commandSignatureScalar: commandSignature.S as bigint,
        packedCommand: userCommand.asCircuitInputs(),
      };

      const witness = await circuit.calculateWitness(circuitInputs);
      await circuit.expectConstraintPass(witness);

      const newStateLeafPublicKey0 = await getSignal(circuit, witness, "newStateLeafPublicKey[0]");
      const newStateLeafPublicKey1 = await getSignal(circuit, witness, "newStateLeafPublicKey[1]");
      const newBallotNonce = await getSignal(circuit, witness, "newBallotNonce");
      const isValid = await getSignal(circuit, witness, "isValid");
      const isStateLeafIndexValid = await getSignal(circuit, witness, "isStateLeafIndexValid");
      const isVoteOptionIndexValid = await getSignal(circuit, witness, "isVoteOptionIndexValid");

      return (
        isValid.toString() === "1" &&
        isStateLeafIndexValid.toString() === "1" &&
        isVoteOptionIndexValid.toString() === "1" &&
        newBallotNonce.toString() === userCommand.nonce.toString() &&
        newStateLeafPublicKey0.toString() === userCommand.newPublicKey.raw[0].toString() &&
        newStateLeafPublicKey1.toString() === userCommand.newPublicKey.raw[1].toString()
      );
    }
  })

Summary: The property ensures that state leaf and ballot transformations for full credits voting are valid by verifying the constraints and outputs of a circuit against expected values using a variety of randomly generated big integers.


it("correctly hashes 2 random values in order", async () => {
      const n = 2;

      circuit = await circomkitInstance.WitnessTester("poseidonHasher", {
        file: "./utils/PoseidonHasher",
        template: "PoseidonHasher",
        params: [n],
      });

      await fc.assert(
        fc.asyncProperty(
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: n, maxLength: n }),
          async (preImages: bigint[]) => {
            const witness = await circuit.calculateWitness({
              inputs: preImages,
            });
            await circuit.expectConstraintPass(witness);
            const output = await getSignal(circuit, witness, "out");
            const outputJS = hash2(preImages);

            return output === outputJS;
          },
        ),
      );
    })

Summary: The function hashes two random big integer values using the PoseidonHasher circuit and verifies that the circuit's output matches the JavaScript hash function `hash2`.


it("correctly hashes 3 random values", async () => {
      const n = 3;

      circuit = await circomkitInstance.WitnessTester("poseidonHasher", {
        file: "./utils/PoseidonHasher",
        template: "PoseidonHasher",
        params: [n],
      });

      await fc.assert(
        fc.asyncProperty(
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: n, maxLength: n }),
          async (preImages: bigint[]) => {
            const witness = await circuit.calculateWitness({
              inputs: preImages,
            });
            await circuit.expectConstraintPass(witness);
            const output = await getSignal(circuit, witness, "out");
            const outputJS = hash3(preImages);

            return output === outputJS;
          },
        ),
      );
    })

Summary: Hashes of three random bigint inputs using `poseidonHasher` should match the output of `hash3`.


it("correctly hashes 4 random values", async () => {
      const n = 4;

      circuit = await circomkitInstance.WitnessTester("poseidonHasher", {
        file: "./utils/PoseidonHasher",
        template: "PoseidonHasher",
        params: [n],
      });

      await fc.assert(
        fc.asyncProperty(
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: n, maxLength: n }),
          async (preImages: bigint[]) => {
            const witness = await circuit.calculateWitness({
              inputs: preImages,
            });
            await circuit.expectConstraintPass(witness);
            const output = await getSignal(circuit, witness, "out");
            const outputJS = hash4(preImages);

            return output === outputJS;
          },
        ),
      );
    })

Summary: `PoseidonHasher` correctly hashes 4 random big integer values, ensuring the output matches the result of the `hash4` function for the same input.


it("correctly hashes 5 random values", async () => {
      const n = 5;

      circuit = await circomkitInstance.WitnessTester("poseidonHasher", {
        file: "./utils/PoseidonHasher",
        template: "PoseidonHasher",
        params: [n],
      });

      await fc.assert(
        fc.asyncProperty(
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: n, maxLength: n }),
          async (preImages: bigint[]) => {
            const witness = await circuit.calculateWitness({
              inputs: preImages,
            });
            await circuit.expectConstraintPass(witness);
            const output = await getSignal(circuit, witness, "out");
            const outputJS = hash5(preImages);

            return output === outputJS;
          },
        ),
      );
    })

Summary: The `PoseidonHasher` correctly hashes an array of 5 random bigint values, ensuring that the circuit output matches the JavaScript `hash5` function output.


it("should check message validator properly", async () => {
    const max = BigInt(2 ** 50);

    await fc.assert(
      fc.asyncProperty(
        fc.bigInt({ min: 1n, max }),
        fc.bigInt({ min: 1n, max }),
        fc.bigInt({ min: 0n, max }),
        fc.bigInt({ min: 0n, max }),
        fc.bigInt({ min: 1n, max: max - maxSignups }),
        fc.bigInt({ min: 1n, max: max - maxVoteOptions }),
        check,
      ),
    );

    async function check(
      votes: bigint,
      nonce: bigint,
      stateTreeIndex: bigint,
      voteOptionIndex: bigint,
      maxSignupsDifference: bigint,
      maxVoteOptionsDifference: bigint,
    ) {
      const { privateKey, publicKey } = new Keypair();
      const command = new VoteCommand(stateTreeIndex, publicKey, voteOptionIndex, votes, nonce, 0n);

      const signature = command.sign(privateKey);

      const inputs = {
        originalNonce: nonce - 1n,
        commandNonce: nonce,
        currentVotesForOption: 0n,
        voteWeight: votes,
        currentVoiceCreditBalance: votes,
        signaturePoint: signature.R8 as unknown as bigint,
        signatureScalar: signature.S as bigint,
        publicKey: publicKey.asCircuitInputs() as unknown as [bigint, bigint],
        command: command.asCircuitInputs(),
        stateTreeIndex,
        totalSignups: stateTreeIndex + maxSignupsDifference,
        voteOptionIndex,
        voteOptions: voteOptionIndex + maxVoteOptionsDifference,
      };

      const witness = await circuit.calculateWitness(inputs);
      await circuit.expectConstraintPass(witness);
      const isValid = await getSignal(circuit, witness, "isValid");
      const isStateLeafIndexValid = await getSignal(circuit, witness, "isStateLeafIndexValid");
      const isVoteOptionIndexValid = await getSignal(circuit, witness, "isVoteOptionIndexValid");

      return (
        isValid.toString() === "1" &&
        isStateLeafIndexValid.toString() === "1" &&
        isVoteOptionIndexValid.toString() === "1"
      );
    }
  })

Summary: The `MessageValidatorFull` test checks that a message validator accurately verifies validity, state leaf index validity, and vote option index validity for various input configurations.


it("should correctly hash a message [fuzz]", async () => {
    const random50bitBigInt = (salt: bigint): bigint =>
      // eslint-disable-next-line no-bitwise
      ((BigInt(1) << BigInt(50)) - BigInt(1)) & salt;

    await fc.assert(
      fc.asyncProperty(
        fc.bigInt({ min: 0n }),
        fc.bigInt({ min: 0n }),
        fc.bigInt({ min: 0n }),
        fc.bigInt({ min: 0n }),
        fc.bigInt({ min: 0n }),
        fc.bigInt({ min: 0n }),
        async (
          stateIndex: bigint,
          voteOptionIndex: bigint,
          newVoteWeight: bigint,
          nonce: bigint,
          pollId: bigint,
          salt: bigint,
        ) => {
          const { publicKey, privateKey } = new Keypair();

          const command: VoteCommand = new VoteCommand(
            random50bitBigInt(stateIndex),
            publicKey,
            random50bitBigInt(voteOptionIndex),
            random50bitBigInt(newVoteWeight),
            random50bitBigInt(nonce),
            random50bitBigInt(pollId),
            salt,
          );

          const ecdhSharedKey = Keypair.generateEcdhSharedKey(privateKey, publicKey);
          const signature = command.sign(privateKey);
          const message = command.encrypt(signature, ecdhSharedKey);
          const messageHash = message.hash(publicKey);
          const circuitInputs = {
            in: message.asCircuitInputs(),
            encryptionPublicKey: publicKey.asCircuitInputs() as unknown as [bigint, bigint],
          };
          const witness = await circuit.calculateWitness(circuitInputs);
          await circuit.expectConstraintPass(witness);
          const output = await getSignal(circuit, witness, "hash");

          return output === messageHash;
        },
      ),
    );
  })

Summary: The property verifies that a message, when hashed using the `MessageHasher`, produces the expected hash after going through encryption and witness calculation processes, ensuring consistency between the computed and expected hashes.


it("should check the correct value [fuzz]", async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.nat(),
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: leavesPerNode, maxLength: leavesPerNode }),
          async (index: number, elements: bigint[]) => {
            fc.pre(elements.length > index);

            const witness = await circuitQuinarySelector.calculateWitness({ index: BigInt(index), in: elements });
            await circuitQuinarySelector.expectConstraintPass(witness);
            const out = await getSignal(circuitQuinarySelector, witness, "out");

            return out.toString() === elements[index].toString();
          },
        ),
      );
    })

Summary: `circuitQuinarySelector` outputs the value at a specified index from an array of fixed length.


it("should loop the value if number is greater that r [fuzz]", async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.nat(),
          fc.array(fc.bigInt({ min: r }), { minLength: leavesPerNode, maxLength: leavesPerNode }),
          async (index: number, elements: bigint[]) => {
            fc.pre(elements.length > index);

            const witness = await circuitQuinarySelector.calculateWitness({ index: BigInt(index), in: elements });
            await circuitQuinarySelector.expectConstraintPass(witness);
            const out = await getSignal(circuitQuinarySelector, witness, "out");

            return out.toString() === (elements[index] % r).toString();
          },
        ),
      );
    })

Summary: The value should loop when indexed from elements with a length greater than the index, resulting in `out` equaling `elements[index] % r`.


it("should throw error if index is out of bounds [fuzz]", async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.nat(),
          fc.array(fc.bigInt({ min: 0n }), { minLength: 1 }),
          async (index: number, elements: bigint[]) => {
            fc.pre(index >= elements.length);

            const circuit = await circomkitInstance.WitnessTester("QuinarySelector", {
              file: "./utils/trees/QuinarySelector",
              template: "QuinarySelector",
              params: [elements.length],
            });

            return circuit
              .calculateWitness({ index: BigInt(index), in: elements })
              .then(() => false)
              .catch((error: Error) => error.message.includes("Assert Failed"));
          },
        ),
      );
    })

Summary: Checks that an error is thrown when attempting to calculate a witness with an out-of-bounds index in a quinary tree circuit.


it("should check generation of path indices [fuzz]", async () => {
      const maxLevel = 100n;

      await fc.assert(
        fc.asyncProperty(
          fc.bigInt({ min: 1n, max: maxLevel }),
          fc.bigInt({ min: 1n, max: r - 1n }),
          async (levels: bigint, input: bigint) => {
            fc.pre(BigInt(leavesPerNode) ** levels > input);

            const tree = new IncrementalQuinTree(Number(levels), 0n, 5, hash5);

            const circuit = await circomkitInstance.WitnessTester("QuinaryGeneratePathIndices", {
              file: "./utils/trees/QuinaryGeneratePathIndices",
              template: "QuinaryGeneratePathIndices",
              params: [levels],
            });

            const witness = await circuit.calculateWitness({
              in: input,
            });
            await circuit.expectConstraintPass(witness);

            const values: bigint[] = [];

            for (let i = 0; i < levels; i += 1) {
              // eslint-disable-next-line no-await-in-loop
              const value = await getSignal(circuit, witness, `out[${i}]`);
              tree.insert(value);
              values.push(value);
            }

            const { pathIndices } = tree.generateProof(Number(input));

            const isEqual = pathIndices.every((item, index) => item.toString() === values[index].toString());

            return values.length === pathIndices.length && isEqual;
          },
        ),
      );
    })

Summary: Generation of path indices should accurately match expected values in an incremental quinary tree across multiple levels.


it("should check the correct leaf [fuzz]", async () => {
      // TODO: seems js implementation doesn't work with levels more than 22
      const maxLevel = 22;

      await fc.assert(
        fc.asyncProperty(
          fc.integer({ min: 1, max: maxLevel }),
          fc.nat({ max: leavesPerNode - 1 }),
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: leavesPerNode, maxLength: leavesPerNode }),
          async (levels: number, index: number, leaves: bigint[]) => {
            const circuit = await circomkitInstance.WitnessTester("QuinaryLeafExists", {
              file: "./utils/trees/QuinaryLeafExists",
              template: "QuinaryLeafExists",
              params: [levels],
            });

            const tree = new IncrementalQuinTree(levels, 0n, leavesPerNode, hash5);
            leaves.forEach((value) => {
              tree.insert(value);
            });

            const proof = tree.generateProof(index);

            const witness = await circuit.calculateWitness({
              root: tree.root,
              leaf: leaves[index],
              path_elements: proof.pathElements,
              path_indices: proof.pathIndices,
            });

            return circuit
              .expectConstraintPass(witness)
              .then(() => true)
              .catch(() => false);
          },
        ),
      );
    })

Summary: The property verifies that for a quinary tree with up to 22 levels, the circuit correctly confirms the existence of a specified leaf within the tree.


it("should correctly sum a list of values [fuzz]", async () => {
    await fc.assert(
      fc.asyncProperty(fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: 1 }), async (nums: bigint[]) => {
        const sum = nums.reduce((a, b) => a + b, 0n);
        fc.pre(sum <= r - 1n);

        const testCircuit = await circomkitInstance.WitnessTester("calculateTotal", {
          file: "./utils/CalculateTotal",
          template: "CalculateTotal",
          params: [nums.length],
        });

        const witness = await testCircuit.calculateWitness({ nums });
        await testCircuit.expectConstraintPass(witness);
        const total = await getSignal(testCircuit, witness, "sum");

        return total === sum;
      }),
      { numRuns: 10_000 },
    );
  })

Summary: The property verifies that the sum of a list of bigint values matches the total calculated by the `calculateTotal` circuit, ensuring the sum does not exceed `r - 1`.


it("should correctly compute a public key [fuzz]", async () => {
    await fc.assert(
      fc.asyncProperty(fc.bigInt(), async (salt: bigint) => {
        const { publicKey, privateKey } = new Keypair(new PrivateKey(salt));

        const witness = await circuit.calculateWitness({ privateKey: BigInt(privateKey.asCircuitInputs()) });
        await circuit.expectConstraintPass(witness);

        const derivedPublicKeyX = await getSignal(circuit, witness, "publicKey[0]");
        const derivedPublicKeyY = await getSignal(circuit, witness, "publicKey[1]");

        return (
          derivedPublicKeyX === publicKey.raw[0] &&
          derivedPublicKeyY === publicKey.raw[1] &&
          inCurve([derivedPublicKeyX, derivedPublicKeyY])
        );
      }),
      { numRuns: 10_000 },
    );
  })

Summary: The function computes a public key from a given private key and verifies that the derived public key matches the expected values and lies on the curve.


it("should be equal to the sum of fibo(n-1) and fibo(n-2)", () => {
  fc.assert(
    fc.property(fc.integer({ min: 2, max: MaxN }), (n) => {
      expect(fibonacci(n)).toBe(fibonacci(n - 1) + fibonacci(n - 2));
    })
  );
})

Summary: The function `fibonacci` should satisfy the property that its result equals the sum of `fibonacci(n-1)` and `fibonacci(n-2)` for integers `n` greater than or equal to 2.


test("should encrypt and decrypt properly", () => {
    fc.assert(
      fc.property(fc.string(), (text: string) => {
        const service = new CryptoService();

        const keypair = generateKeyPairSync("rsa", {
          modulusLength: 2048,
        });

        const encryptedText = service.encrypt(keypair.publicKey.export({ type: "pkcs1", format: "pem" }), text);

        const decryptedText = service.decrypt(
          keypair.privateKey.export({ type: "pkcs1", format: "pem" }),
          encryptedText,
        );

        return decryptedText === text;
      }),
    );
  })

Summary: Encryption and decryption processes should accurately preserve the original string.


test('compare test framework to real framework', () => {
  // Generate a tree of TestConditions using fast-check
  fc.assert(
    fc.property(fc.integer({min: 1, max: 20}), numConditions => {
      const conditions: TestCondition[] = fc
        .sample(fc.boolean(), numConditions)
        .map(
          value =>
            ({
              type: 'simple',
              right: {value},
            }) as const,
        );

      const pivots = conditions.map(
        () => fc.sample(fc.integer({min: 0, max: 100}), 1)[0] > 50,
      );

      const expected = conditions.reduce((acc, value, i) => {
        if (acc === undefined) {
          return value;
        }
        return pivots[i] ? simpleAnd(acc, value) : simpleOr(acc, value);
      });

      const actualConditions = conditions.map(convertTestCondition);
      const actual = simplifyCondition(
        actualConditions.reduce((acc, value, i) => {
          if (acc === undefined) {
            return value;
          }
          return pivots[i] ? and(value, acc) : or(value, acc);
        }),
      );

      expect(evaluate(actual as TestCondition)).toBe(evaluate(expected));

      // check that the real framework produced a flattened condition
      // console.log(toStr(actual));
      const check = (c: Condition): boolean =>
        c.type === 'simple' ||
        c.type === 'correlatedSubquery' ||
        c.conditions.every(child => child.type !== c.type && check(child));
      expect(check(actual)).toBe(true);
    }),
  );

  function convertTestCondition(c: TestCondition): Condition {
    assert(c.type === 'simple');
    return {
      type: 'simple',
      right: {
        type: 'literal',
        value: c.right.value,
      },
      op: '=',
      left: {
        type: 'column',
        name: 'n/a',
      },
    };
  }
})

Summary: The framework should correctly evaluate a tree of simplified `TestCondition` objects to ensure equivalence in evaluation results between the test condition and actual condition structures, while producing a flattened condition without repeating condition types in its children.


test('normalizeUndefined', () => {
  fc.assert(
    fc.property(fc.constantFrom(null, undefined), v => {
      expect(normalizeUndefined(v)).toBe(null);
    }),
  );
  fc.assert(
    fc.property(fc.oneof(fc.boolean(), fc.double(), fc.string()), b => {
      expect(normalizeUndefined(b)).toBe(b);
    }),
  );
})

Summary: `normalizeUndefined` converts `null` and `undefined` to `null`, leaving other types unchanged.


test('compareValues', () => {
  // null and undefined are equal to each other
  fc.assert(
    fc.property(
      fc.constantFrom(null, undefined),
      fc.constantFrom(null, undefined),
      (v1, v2) => {
        expect(compareValues(v1, v2)).toBe(0);
      },
    ),
  );

  // null and undefined are less than any other value
  fc.assert(
    fc.property(
      fc.constantFrom(null, undefined),
      fc.oneof(fc.boolean(), fc.double(), fc.fullUnicodeString()),
      (v1, v2) => {
        expect(compareValues(v1, v2)).lessThan(0);
        expect(compareValues(v2, v1)).greaterThan(0);
      },
    ),
  );

  // boolean
  fc.assert(
    fc.property(fc.boolean(), fc.boolean(), (b1, b2) => {
      expect(compareValues(b1, b2)).toBe(b1 === b2 ? 0 : b1 ? 1 : -1);
    }),
  );
  fc.assert(
    fc.property(
      fc.boolean(),
      fc.oneof(fc.double(), fc.fullUnicodeString()),
      (b, v) => {
        expect(() => compareValues(b, v)).toThrow('expected boolean');
      },
    ),
  );

  // number
  fc.assert(
    fc.property(fc.double(), fc.double(), (n1, n2) => {
      expect(compareValues(n1, n2)).toBe(n1 - n2);
    }),
  );
  fc.assert(
    fc.property(
      fc.double(),
      fc.oneof(fc.boolean(), fc.fullUnicodeString()),
      (n, v) => {
        expect(() => compareValues(n, v)).toThrow('expected number');
      },
    ),
  );

  // string
  fc.assert(
    fc.property(fc.fullUnicodeString(), fc.fullUnicodeString(), (s1, s2) => {
      expect(compareValues(s1, s2)).toBe(compareUTF8(s1, s2));
    }),
  );
  fc.assert(
    fc.property(
      fc.fullUnicodeString(),
      fc.oneof(fc.boolean(), fc.double()),
      (s, v) => {
        expect(() => compareValues(s, v)).toThrow('expected string');
      },
    ),
  );
})

Summary: `compareValues` is validated across different data types: `null` and `undefined` are treated as equal and less than other types, booleans are compared logically, numbers use arithmetic comparison, and strings are compared using UTF-8 logic. Mismatched types raise an exception.


Summary: `compareValues` ensures that null and undefined are treated as equal to each other and less than any other value, that booleans are compared correctly and throw on invalid comparisons, that numbers are subtracted for comparison and throw on invalid comparisons, and that strings use `compareUTF8` and throw on invalid comparisons.


Summary: `compareValues` function should return `0` for null and undefined pairs, indicate they are less than other types, correctly compare booleans and numbers, throw errors when comparing different types, and match `compareUTF8` results for strings.


Summary: The `compareValues` function should return 0 when comparing `null` or `undefined`, treat these as less than any other types, correctly compare booleans and numbers against their respective types, ensure strings are compared using `compareUTF8`, and throw errors when types are mismatched.


Summary: `compareValues` evaluates equality between `null` and `undefined`, ranks them below other types, and throws errors when comparing mismatched types, while correctly comparing booleans, numbers, and strings.


Summary: `compareValues` function should correctly handle comparisons, equating `null` and `undefined`, treating them as less than other values, comparing boolean values realistically, throwing errors for mismatched types, and comparing numbers and strings according to expected logic.


test('valuesEquals', () => {
  fc.assert(
    fc.property(
      fc.oneof(fc.boolean(), fc.double(), fc.fullUnicodeString()),
      fc.oneof(fc.boolean(), fc.double(), fc.fullUnicodeString()),
      (v1, v2) => {
        expect(valuesEqual(v1, v2)).toBe(v1 === v2);
      },
    ),
  );

  fc.assert(
    fc.property(
      fc.constantFrom(null, undefined),
      fc.oneof(
        fc.constantFrom(null, undefined),
        fc.boolean(),
        fc.double(),
        fc.fullUnicodeString(),
      ),
      (v1, v2) => {
        expect(valuesEqual(v1, v2)).false;
        expect(valuesEqual(v2, v1)).false;
      },
    ),
  );
})

Summary: The `valuesEqual` function should correctly determine equality based on strict equivalence for various data types, and return false when comparing null or undefined with any other values.


Summary: The `valuesEqual` function should return true if two values are strictly equal, and false if either value is null or undefined.


test('basics', () => {
  // nulls and undefined are false in all conditions except IS NULL and IS NOT NULL
  fc.assert(
    fc.property(
      fc.oneof(fc.constant(null), fc.constant(undefined)),
      fc.oneof(
        fc.constant('='),
        fc.constant('!='),
        fc.constant('<'),
        fc.constant('<='),
        fc.constant('>'),
        fc.constant('>='),
        fc.constant('LIKE'),
        fc.constant('NOT LIKE'),
        fc.constant('ILIKE'),
        fc.constant('NOT ILIKE'),
      ),
      // hexastring to avoid sending escape chars to like
      fc.oneof(fc.hexaString(), fc.double(), fc.boolean(), fc.constant(null)),
      (a, operator, b) => {
        const condition: SimpleCondition = {
          type: 'simple',
          left: {
            type: 'column',
            name: 'foo',
          },
          op: operator as SimpleOperator,
          right: {
            type: 'literal',
            value: b,
          },
        };
        const predicate = createPredicate(condition);
        expect(predicate({foo: a})).toBe(false);
      },
    ),
  );

  let condition: SimpleCondition = {
    type: 'simple',
    left: {
      type: 'column',
      name: 'foo',
    },
    op: 'IS',
    right: {
      type: 'literal',
      value: null,
    },
  };
  let predicate = createPredicate(condition);
  expect(predicate({foo: null})).toBe(true);
  expect(predicate({foo: 1})).toBe(false);
  expect(predicate({foo: 'null'})).toBe(false);
  expect(predicate({foo: true})).toBe(false);
  expect(predicate({foo: false})).toBe(false);

  condition = {
    type: 'simple',
    left: {
      type: 'column',
      name: 'foo',
    },
    op: 'IS NOT',
    right: {
      type: 'literal',
      value: null,
    },
  };
  predicate = createPredicate(condition);
  expect(predicate({foo: null})).toBe(false);
  expect(predicate({foo: 1})).toBe(true);
  expect(predicate({foo: 'null'})).toBe(true);
  expect(predicate({foo: true})).toBe(true);
  expect(predicate({foo: false})).toBe(true);

  // basic operators
  fc.assert(
    fc.property(
      fc.oneof(fc.boolean(), fc.double(), fc.string()),
      fc.oneof(
        fc.constant('='),
        fc.constant('!='),
        fc.constant('<'),
        fc.constant('<='),
        fc.constant('>'),
        fc.constant('>='),
      ),
      fc.oneof(fc.boolean(), fc.double(), fc.string()),
      (a, op, b) => {
        const condition: SimpleCondition = {
          type: 'simple',
          left: {
            type: 'column',
            name: 'foo',
          },
          op: op as SimpleOperator,
          right: {
            type: 'literal',
            value: b,
          },
        };
        const predicate = createPredicate(condition);
        const jsOp = {'=': '===', '!=': '!=='}[op] ?? op;
        expect(predicate({foo: a})).toBe(eval(`a ${jsOp} b`));
      },
    ),
  );
})

Summary: Null and undefined values yield false with all operators except IS NULL and IS NOT NULL, for which they return true and false respectively. For basic comparison operators, the predicate created should replicate the JavaScript evaluation of the same operation.


test('no clashes - single pk', () => {
  fc.assert(
    fc.property(
      fc.oneof(
        fc.tuple(fc.string(), fc.string()),
        fc.tuple(fc.double(), fc.double()),
        fc.tuple(fc.boolean(), fc.boolean()),
      ),
      ([a, b]) => {
        const keyA = toPrimaryKeyStringImpl('issue', ['id'], {id: a});
        const keyB = toPrimaryKeyStringImpl('issue', ['id'], {id: b});
        if (a === b) {
          expect(keyA).toBe(keyB);
        } else {
          expect(keyA).not.toBe(keyB);
        }
      },
    ),
  );
})

Summary: `toPrimaryKeyStringImpl` generates unique primary key strings for different values and identical strings for equal values.


test('no clashes - multiple pk', () => {
  const primaryKey = ['id', 'name'] as const;
  fc.assert(
    fc.property(
      fc.tuple(
        fc.oneof(fc.string(), fc.double(), fc.boolean()),
        fc.oneof(fc.string(), fc.double(), fc.boolean()),
        fc.oneof(fc.string(), fc.double(), fc.boolean()),
        fc.oneof(fc.string(), fc.double(), fc.boolean()),
      ),
      ([a1, a2, b1, b2]) => {
        const keyA = toPrimaryKeyStringImpl('issue', primaryKey, {
          id: a1,
          name: a2,
        });
        const keyB = toPrimaryKeyStringImpl('issue', primaryKey, {
          id: b1,
          name: b2,
        });
        if (a1 === b1 && a2 === b2) {
          expect(keyA).toBe(keyB);
        } else {
          expect(keyA).not.toBe(keyB);
        }
      },
    ),
  );
})

Summary: When creating primary keys from combinations of different types, identical input values should produce identical keys, while different values should produce distinct keys.


test('encode/decodeSecProtocols round-trip', () => {
  fc.assert(
    fc.property(
      fc.record({
        initConnectionMessage: fc.tuple(
          fc.constant<'initConnection'>('initConnection'),
          fc.record(
            {
              desiredQueriesPatch: fc.array(
                fc.oneof(
                  fc.record(
                    {
                      op: fc.constant<'put'>('put'),
                      hash: fc.string(),
                      data: fc.fullUnicodeString(),
                      ast: fc.constant({
                        table: 'table',
                      }),
                      ttl: fc.option(
                        fc.double({
                          noDefaultInfinity: true,
                          noNaN: true,
                          min: 0,
                        }),
                        {nil: undefined},
                      ),
                    },
                    {requiredKeys: ['op', 'hash', 'ast']},
                  ),
                  fc.record({
                    op: fc.constant<'del'>('del'),
                    hash: fc.string(),
                  }),
                ),
              ),
              deleted: fc.record(
                {
                  clientIDs: fc.array(fc.string()),
                  clientGroupIDs: fc.array(fc.string()),
                },
                {requiredKeys: []},
              ),
            },
            {requiredKeys: ['desiredQueriesPatch']},
          ),
        ),
        authToken: fc.option(
          fc.stringOf(
            fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789-_.'),
          ),
          {nil: undefined},
        ),
      }),
      ({initConnectionMessage, authToken}) => {
        const encoded = encodeSecProtocols(initConnectionMessage, authToken);
        const {
          initConnectionMessage: decodedInitConnectionMessage,
          authToken: decodedAuthToken,
        } = decodeSecProtocols(encoded);
        expect(decodedInitConnectionMessage).toEqual(initConnectionMessage);
        expect(decodedAuthToken).toEqual(authToken);
      },
    ),
  );
})

Summary: The property should ensure that `encodeSecProtocols` and `decodeSecProtocols` are inverse operations, such that decoding the encoded result of given inputs yields the original inputs.


test('random using fast check', () => {
  fc.assert(
    fc.property(
      fc.bigInt({min: 0n}),
      fc.integer({min: 2, max: 36}),
      (n, radix) => {
        const s = n.toString(radix);
        const actual = parseBigInt(s, radix);
        expect(actual).toBe(n);
      },
    ),
  );
})

Summary: `parseBigInt` accurately parses strings representing non-negative big integers in various radices back to their original big integer values.


test('random with fast-check', () => {
  fc.assert(
    fc.property(fc.float(), fc.float(), (a, b) => {
      const as = encodeFloat64AsString(a);
      const bs = encodeFloat64AsString(b);

      const a2 = decodeFloat64AsString(as);
      const b2 = decodeFloat64AsString(bs);

      expect(a2).toBe(a);
      expect(b2).toBe(b);

      if (Object.is(a, b)) {
        expect(as).toBe(bs);
      } else {
        expect(as).not.toBe(bs);
        if (!Number.isNaN(a) && !Number.isNaN(b)) {
          expect(as < bs).toBe(a < b);
        }
      }
    }),
  );
})

Summary: Encoding and decoding of `float` values to and from strings should preserve the original values, and the string comparison should reflect the numeric comparison, except for `NaN` values.


test('creating an arbitrary context field should return the created context field', async () => {
    await fc.assert(
        fc
            .asyncProperty(contextFieldDto(), async (input) => {
                const { createdAt, ...storedData } =
                    await stores.contextFieldStore.create(input);

                Object.entries(input).forEach(([key, value]) => {
                    expect(storedData[key]).toStrictEqual(value);
                });
            })
            .afterEach(cleanup),
    );
})

Summary: Creating an arbitrary context field should result in stored data that matches the input values exactly, except for the creation timestamp.


test('updating a context field should update the specified fields and leave everything else untouched', async () => {
    await fc.assert(
        fc
            .asyncProperty(
                contextFieldDto(),
                contextFieldDto(),
                async (original, { name, ...updateData }) => {
                    await stores.contextFieldStore.create(original);

                    const { createdAt, ...updatedData } =
                        await stores.contextFieldStore.update({
                            name: original.name,
                            ...updateData,
                        });

                    const allKeys = [
                        'sortOrder',
                        'stickiness',
                        'description',
                        'legalValues',
                    ];
                    const updateKeys = Object.keys(updateData);

                    const unchangedKeys = allKeys.filter(
                        (k) => !updateKeys.includes(k),
                    );

                    Object.entries(updateData).forEach(([key, value]) => {
                        expect(updatedData[key]).toStrictEqual(value);
                    });

                    for (const key in unchangedKeys) {
                        expect(updatedData[key]).toStrictEqual(original[key]);
                    }
                },
            )
            .afterEach(cleanup),
    );
})

Summary: Updating a context field should change the specified fields while leaving all other fields unchanged.


it('should reject configurations specifying non existing keys as required', () =>
    fc.assert(
      fc.property(fc.uniqueArray(keyArb, { minLength: 1 }), keyArb, (keys, requiredKey) => {
        // Arrange
        fc.pre(!keys.includes(requiredKey));
        const recordModel: Record<string | symbol, Arbitrary<any>> = {};
        for (const k of keys) {
          const { instance } = fakeArbitrary();
          recordModel[k] = instance;
        }

        // Act / Assert
        expect(() =>
          record(recordModel, {
            requiredKeys: [requiredKey],
          }),
        ).toThrowError();
      }),
    ))

Summary: An error is thrown when attempting to require a key not present in the record model.


it('should reject any inputs containing at least one strictly negative entry', () =>
    fc.assert(
      fc.property(fc.array(fc.nat()), fc.array(fc.nat()), fc.integer({ max: -1 }), (beforeNeg, afterNeg, neg) => {
        // Arrange
        const entries = [...beforeNeg, neg, ...afterNeg].map((num) => ({ num, build: vi.fn() }));

        // Act / Assert
        expect(() => mapToConstant(...entries)).toThrowError();
      }),
    ))

Summary: `mapToConstant` should throw an error if any input contains a strictly negative entry.


it('should reject any inputs summing to zero', () =>
    fc.assert(
      fc.property(fc.nat({ max: 1000 }), (length) => {
        // Arrange
        const entries = [...Array(length)].map(() => ({ num: 0, build: vi.fn() }));

        // Act / Assert
        expect(() => mapToConstant(...entries)).toThrowError();
      }),
    ))

Summary: `mapToConstant` throws an error for inputs with elements summing to zero.


test("should return all of a feature's strategies", async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    fc.context(),
                    async (data, context, ctx) => {
                        const log = (x: unknown) => ctx.log(JSON.stringify(x));
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...data,
                                context,
                            },
                        );

                        const serviceFeaturesDict: {
                            [key: string]: PlaygroundFeatureSchema;
                        } = serviceFeatures.reduce(
                            (acc, feature) => ({
                                ...acc,
                                [feature.name]: feature,
                            }),
                            {},
                        );

                        // for each feature, find the corresponding evaluated feature
                        // and make sure that the evaluated
                        // return genFeat.length === servFeat.length && zip(gen, serv).
                        data.features.forEach((feature) => {
                            const mappedFeature: PlaygroundFeatureSchema =
                                serviceFeaturesDict[feature.name];

                            // log(feature);
                            log(mappedFeature);

                            const featureStrategies = feature.strategies ?? [];

                            expect(
                                mappedFeature.strategies.data.length,
                            ).toEqual(featureStrategies.length);

                            // we can't guarantee that the order we inserted
                            // strategies into the database is the same as it
                            // was returned by the service , so we'll need to
                            // scan through the list of strats.

                            // extract the `result` property, because it
                            // doesn't exist in the input

                            const removeResult = <T>({
                                result,
                                ...rest
                            }: T & {
                                result: unknown;
                            }) => rest;

                            const cleanedReceivedStrategies =
                                mappedFeature.strategies.data.map(
                                    (strategy) => {
                                        const {
                                            segments: mappedSegments,
                                            ...mappedStrategy
                                        } = removeResult(strategy);

                                        return {
                                            ...mappedStrategy,
                                            constraints:
                                                mappedStrategy.constraints?.map(
                                                    removeResult,
                                                ),
                                        };
                                    },
                                );

                            feature.strategies?.forEach(
                                ({ segments, ...strategy }) => {
                                    expect(cleanedReceivedStrategies).toEqual(
                                        expect.arrayContaining([
                                            {
                                                ...strategy,
                                                title: undefined,
                                                disabled: false,
                                                constraints:
                                                    strategy.constraints ?? [],
                                                parameters:
                                                    strategy.parameters ?? {},
                                            },
                                        ]),
                                    );
                                },
                            );
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: The test verifies that for each feature, the strategies returned by evaluating service features match the expected strategies in count and content, while accommodating unordered results by checking for array containment.


it('should accept any inputs not summing to zero and with positive or null values', () =>
    fc.assert(
      fc.property(fc.array(fc.nat(), { minLength: 1 }), (nums) => {
        // Arrange
        fc.pre(nums.some((n) => n > 0));
        const entries = nums.map((num) => ({ num, build: vi.fn() }));

        // Act / Assert
        expect(() => mapToConstant(...entries)).not.toThrowError();
      }),
    ))

Summary: `mapToConstant` accepts inputs with values that are positive or zero, ensuring the sum is not zero, without throwing an error.


test('should return feature strategies with all their segments', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async (
                        { segments, features: generatedFeatures },
                        context,
                    ) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features: generatedFeatures,
                                context,
                                segments,
                            },
                        );

                        const serviceFeaturesDict: {
                            [key: string]: PlaygroundFeatureSchema;
                        } = serviceFeatures.reduce(
                            (acc, feature) => ({
                                ...acc,
                                [feature.name]: feature,
                            }),
                            {},
                        );

                        // ensure that segments are mapped on to features
                        // correctly. We do not need to check whether the
                        // evaluation is correct; that is taken care of by other
                        // tests.

                        // For each feature strategy, find its list of segments and
                        // compare it to the input.
                        //
                        // We can assert three things:
                        //
                        // 1. The segments lists have the same length
                        //
                        // 2. All segment ids listed in an input id list are
                        // also in the original segments list
                        //
                        // 3. If a feature is considered enabled, _all_ segments
                        // must be true. If a feature is _disabled_, _at least_
                        // one segment is not true.
                        generatedFeatures.forEach((unmappedFeature) => {
                            const strategies = serviceFeaturesDict[
                                unmappedFeature.name
                            ].strategies.data.reduce(
                                (acc, strategy) => ({
                                    ...acc,
                                    [strategy.id]: strategy,
                                }),
                                {},
                            );

                            unmappedFeature.strategies?.forEach(
                                (unmappedStrategy) => {
                                    const mappedStrategySegments: PlaygroundSegmentSchema[] =
                                        strategies[unmappedStrategy.id!]
                                            .segments;

                                    const unmappedSegments =
                                        unmappedStrategy.segments ?? [];

                                    // 1. The segments lists have the same length
                                    // 2. All segment ids listed in the input exist:
                                    expect(
                                        [
                                            ...mappedStrategySegments?.map(
                                                (segment) => segment.id,
                                            ),
                                        ].sort(),
                                    ).toEqual([...unmappedSegments].sort());

                                    switch (
                                        strategies[unmappedStrategy.id!].result
                                    ) {
                                        case true:
                                            // If a strategy is considered true, _all_ segments
                                            // must be true.
                                            expect(
                                                mappedStrategySegments.every(
                                                    (segment) =>
                                                        segment.result === true,
                                                ),
                                            ).toBeTruthy();
                                            break;
                                        case false:
                                        // empty -- all segments can be true and
                                        // the toggle still not enabled. We
                                        // can't check for anything here.
                                        case 'not found':
                                        // empty -- we can't evaluate this
                                    }
                                },
                            );
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: The test ensures that feature strategies are returned with correctly mapped segments, verifies that the segment lists have matching lengths and IDs, and checks that all segments are true if a strategy is enabled.


test("should evaluate a strategy to be unknown if it doesn't recognize the strategy and all constraints pass", async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }).map(
                        ({ features, ...rest }) => ({
                            ...rest,
                            features: features.map((feature) => ({
                                ...feature,
                                // remove any constraints and use a name that doesn't exist
                                strategies: feature.strategies?.map(
                                    (strategy) => ({
                                        ...strategy,
                                        name: 'bogus-strategy',
                                        constraints: [],
                                        segments: [],
                                    }),
                                ),
                            })),
                        }),
                    ),
                    generateContext(),
                    fc.context(),
                    async (featsAndSegments, context, ctx) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...featsAndSegments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) =>
                            feature.strategies.data.forEach((strategy) => {
                                expect(strategy.result.evaluationStatus).toBe(
                                    playgroundStrategyEvaluation.evaluationIncomplete,
                                );
                                expect(strategy.result.enabled).toBe(
                                    playgroundStrategyEvaluation.unknownResult,
                                );
                            }),
                        );

                        ctx.log(JSON.stringify(serviceFeatures));
                        serviceFeatures.forEach((feature) => {
                            // if there are strategies and they're all
                            // incomplete and unknown, then the feature can't be
                            // evaluated fully
                            if (feature.strategies.data.length) {
                                expect(feature.isEnabled).toBe(false);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: Evaluates whether a strategy is labeled as unknown and incomplete if the strategy name is unrecognized and all constraints pass, ensuring features with such strategies are not fully enabled.


test("should evaluate a strategy as false if it doesn't recognize the strategy and constraint checks fail", async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    fc
                        .tuple(
                            fc.uuid(),
                            clientFeaturesAndSegments({ minLength: 1 }),
                        )
                        .map(([uuid, { features, ...rest }]) => ({
                            ...rest,
                            features: features.map((feature) => ({
                                ...feature,
                                // use a constraint that will never be true
                                strategies: feature.strategies?.map(
                                    (strategy) => ({
                                        ...strategy,
                                        name: 'bogusStrategy',
                                        constraints: [
                                            {
                                                contextName: 'appName',
                                                operator: 'IN' as const,
                                                values: [uuid],
                                            },
                                        ],
                                    }),
                                ),
                            })),
                        })),
                    generateContext(),
                    fc.context(),
                    async (featsAndSegments, context, ctx) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...featsAndSegments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) =>
                            feature.strategies.data.forEach((strategy) => {
                                expect(strategy.result.evaluationStatus).toBe(
                                    playgroundStrategyEvaluation.evaluationIncomplete,
                                );
                                expect(strategy.result.enabled).toBe(false);
                            }),
                        );

                        ctx.log(JSON.stringify(serviceFeatures));

                        serviceFeatures.forEach((feature) => {
                            if (feature.strategies.data.length) {
                                // if there are strategies and they're all
                                // incomplete and false, then the feature
                                // is also false
                                expect(feature.isEnabled).toEqual(false);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: An unrecognized strategy with failing constraint checks should result in strategy evaluation being incomplete and the feature being disabled.


test('should evaluate a feature as unknown if there is at least one incomplete strategy among all failed strategies', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    fc
                        .tuple(
                            fc.uuid(),
                            clientFeaturesAndSegments({ minLength: 1 }),
                        )
                        .map(([uuid, { features, ...rest }]) => ({
                            ...rest,
                            features: features.map((feature) => ({
                                ...feature,
                                // use a constraint that will never be true
                                strategies: [
                                    ...feature.strategies!.map((strategy) => ({
                                        ...strategy,
                                        constraints: [
                                            {
                                                contextName: 'appName',
                                                operator: 'IN' as const,
                                                values: [uuid],
                                            },
                                        ],
                                    })),
                                    { name: 'my-custom-strategy' },
                                ],
                            })),
                        })),
                    generateContext(),
                    async (featsAndSegments, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...featsAndSegments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) => {
                            if (feature.strategies.data.length) {
                                // if there are strategies and they're
                                // all incomplete and unknown, then
                                // the feature is also unknown and
                                // thus 'false' (from an SDK point of
                                // view)
                                expect(feature.isEnabled).toEqual(false);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: A feature is evaluated as unknown and disabled if at least one strategy is incomplete or all strategies are unknown.


test("features can't be evaluated to true if they're not enabled in the current environment", async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }).map(
                        ({ features, ...rest }) => ({
                            ...rest,
                            features: features.map((feature) => ({
                                ...feature,
                                enabled: false,
                                // remove any constraints and use a name that doesn't exist
                                strategies: [{ name: 'default' }],
                            })),
                        }),
                    ),
                    generateContext(),
                    fc.context(),
                    async (featsAndSegments, context, ctx) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...featsAndSegments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) =>
                            feature.strategies.data.forEach((strategy) => {
                                expect(strategy.result.evaluationStatus).toBe(
                                    playgroundStrategyEvaluation.evaluationComplete,
                                );
                                expect(strategy.result.enabled).toBe(true);
                            }),
                        );

                        ctx.log(JSON.stringify(serviceFeatures));
                        serviceFeatures.forEach((feature) => {
                            expect(feature.isEnabled).toBe(false);
                            expect(feature.isEnabledInCurrentEnvironment).toBe(
                                false,
                            );
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: Features should not evaluate to true if they are not enabled in the current environment.


test('output toggles should have the same variants as input toggles', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async ({ features, segments }, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features,
                                segments,
                                context,
                            },
                        );

                        const variantsMap = features.reduce(
                            (acc, feature) => ({
                                ...acc,
                                [feature.name]: feature.variants,
                            }),
                            {},
                        );

                        serviceFeatures.forEach((feature) => {
                            if (variantsMap[feature.name]) {
                                expect(feature.variants).toEqual(
                                    expect.arrayContaining(
                                        variantsMap[feature.name],
                                    ),
                                );
                                expect(variantsMap[feature.name]).toEqual(
                                    expect.arrayContaining(feature.variants),
                                );
                            } else {
                                expect(feature.variants).toStrictEqual([]);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: Output toggles should contain the same variants as the input toggles after feature insertion and evaluation.


test('isEnabled matches strategies.results', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async ({ features, segments }, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features,
                                segments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) => {
                            if (feature.isEnabled) {
                                expect(
                                    feature.isEnabledInCurrentEnvironment,
                                ).toBe(true);
                                expect(feature.strategies.result).toBe(true);
                            } else {
                                expect(
                                    !feature.isEnabledInCurrentEnvironment ||
                                        feature.strategies.result !== true,
                                ).toBe(true);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: `isEnabled` should match `strategies.result` for each feature after evaluation.


it('should throw whenever max is an invalid date', () =>
    fc.assert(
      fc.property(invalidMaxConstraintsArb(), (constraints) => {
        // Act / Assert
        expect(() => date(constraints)).toThrowError();
      }),
    ))

Summary: Throw an error when the `max` constraint is an invalid date.


test('strategies.results matches the individual strategy results', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async ({ features, segments }, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features,
                                segments,
                                context,
                            },
                        );

                        serviceFeatures.forEach(({ strategies }) => {
                            if (strategies.result === false) {
                                expect(
                                    strategies.data.every(
                                        (strategy) =>
                                            strategy.result.enabled === false,
                                    ),
                                ).toBe(true);
                            } else if (
                                strategies.result ===
                                playgroundStrategyEvaluation.unknownResult
                            ) {
                                expect(
                                    strategies.data.some(
                                        (strategy) =>
                                            strategy.result.enabled ===
                                            playgroundStrategyEvaluation.unknownResult,
                                    ),
                                ).toBe(true);

                                expect(
                                    strategies.data.every(
                                        (strategy) =>
                                            strategy.result.enabled !== true,
                                    ),
                                ).toBe(true);
                            } else {
                                if (strategies.data.length > 0) {
                                    expect(
                                        strategies.data.some(
                                            (strategy) =>
                                                strategy.result.enabled ===
                                                true,
                                        ),
                                    ).toBe(true);
                                }
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: The `strategies.results` should correspond to the individual results of feature strategies, where the collective result reflects individual strategy outcomes, ensuring consistency across evaluation contexts.


test('unevaluated features should not have variants', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async ({ features, segments }, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features,
                                segments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) => {
                            if (
                                feature.strategies.result ===
                                playgroundStrategyEvaluation.unknownResult
                            ) {
                                expect(feature.variant).toEqual({
                                    name: 'disabled',
                                    enabled: false,
                                    feature_enabled: false,
                                });
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })

Summary: Unevaluated features must have variants set to `{ name: 'disabled', enabled: false, feature_enabled: false }`.


test('url-friendly strings are URL-friendly', () =>
    fc.assert(
        fc.property(urlFriendlyString(), (input: string) =>
            /^[\w~.-]+$/.test(input),
        ),
    ))

Summary: The property should ensure that `urlFriendlyString` generates strings containing only URL-safe characters (alphanumeric, hyphens, underscores, tildes, and dots).


test('variant payloads are either present or undefined; never null', () =>
    fc.assert(
        fc.property(
            variant(),
            (generatedVariant) =>
                !!generatedVariant.payload ||
                generatedVariant.payload === undefined,
        ),
    ))

Summary: Variant payloads must be either defined or undefined, but never null.


it('Returned features should be a subset of the provided flags', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeatures({ minLength: 1 }),
                    generateRequest(),
                    async (features, request) => {
                        // seed the database
                        await seedDatabase(db, features, request.environment);

                        const body = await playgroundRequest(
                            app,
                            token.secret,
                            request,
                        );

                        // the returned list should always be a subset of the provided list
                        expect(features.map((feature) => feature.name)).toEqual(
                            expect.arrayContaining(
                                body.features.map((feature) => feature.name),
                            ),
                        );
                    },
                )
                .afterEach(reset(db)),
            testParams,
        );
    })

Summary: Returned features from `playgroundRequest` should always be a subset of the provided feature flags.


it('should be able to shrink any value it shrunk if not adapted or shrinkable adapted', () => {
      fc.assert(
        fc.property(
          fc.option(fc.integer({ min: 2 }), { nil: undefined }),
          fc.anything(),
          fc.anything(),
          fc.record({ adapted: fc.boolean(), value: fc.anything() }),
          fc.anything(),
          fc.anything(),
          fc.record({ adapted: fc.boolean(), value: fc.anything() }),
          fc.anything(),
          fc.anything(),
          fc.record({ adapted: fc.boolean(), value: fc.anything() }),
          fc.anything(),
          fc.anything(),
          fc.record({ adapted: fc.boolean(), value: fc.anything() }),
          fc.anything(),
          fc.anything(),
          fc.record({ adapted: fc.boolean(), value: fc.anything() }),
          fc.boolean(),
          (
            biasFactor,
            vA,
            cA,
            adaptedA,
            vAA,
            cAA,
            adaptedAA,
            vAB,
            cAB,
            adaptedAB,
            vAC,
            cAC,
            adaptedAC,
            vABC,
            cABC,
            adaptedABC,
            canShrinkIfAdapted,
          ) => {
            // Arrange
            fc.pre(allUniques(vA, vAA, vAB, vAC, vABC)); // check for adapterFunction
            const valueA = new Value(vA, cA);
            const valueAA = new Value(vAA, cAA);
            const valueAB = new Value(vAB, cAB);
            const valueAC = new Value(vAC, cAC);
            const valueABC = new Value(vABC, cABC);
            const { instance, generate, shrink, canShrinkWithoutContext } = fakeArbitrary();
            generate.mockReturnValueOnce(valueA);
            shrink.mockReturnValueOnce(Stream.of(valueAA, valueAB, valueAC)).mockReturnValueOnce(Stream.of(valueABC));
            if (adaptedA.adapted) canShrinkWithoutContext.mockReturnValueOnce(true);
            canShrinkWithoutContext.mockReturnValueOnce(canShrinkIfAdapted);
            const { instance: mrng } = fakeRandom();
            const adapterFunction = vi
              .fn<(arg0: any) => AdapterOutput<any>>()
              .mockImplementation((v) =>
                Object.is(v, vA)
                  ? adaptedA
                  : Object.is(v, vAA)
                    ? adaptedAA
                    : Object.is(v, vAB)
                      ? adaptedAB
                      : Object.is(v, vAC)
                        ? adaptedAC
                        : adaptedABC,
              );

            // Act
            const arb = adapter(instance, adapterFunction);
            const g = arb.generate(mrng, biasFactor);
            const g2 = [...arb.shrink(g.value, g.context)][1];
            const shrinks = [...arb.shrink(g2.value, g2.context)];

            // Assert
            expect(generate).toHaveBeenCalledWith(mrng, biasFactor);
            if (adaptedA.adapted) {
              expect(shrink).toHaveBeenCalledWith(adaptedA.value, undefined);
            } else {
              expect(shrink).toHaveBeenCalledWith(vA, cA);
            }
            if (!adaptedAB.adapted || canShrinkIfAdapted) {
              expect(shrinks).toHaveLength(1);
              if (adaptedABC.adapted) {
                expect(shrinks[0].value_).toBe(adaptedABC.value);
              } else {
                expect(shrinks[0]).toBe(valueABC);
              }
              if (adaptedAB.adapted) {
                expect(shrink).toHaveBeenCalledWith(adaptedAB.value, undefined);
                expect(canShrinkWithoutContext).toHaveBeenCalledWith(adaptedAB.value);
              } else {
                expect(shrink).toHaveBeenCalledWith(vAB, cAB);
              }
            } else {
              expect(shrinks).toHaveLength(0);
              expect(canShrinkWithoutContext).toHaveBeenCalledWith(adaptedAB.value);
            }
          },
        ),
      );
    })

Summary: The ability to shrink any value it produces is verified, except when the value is adapted and marked as not shrinkable, ensuring correctness in the shrinking behavior of `adapter`.


it('should filter the list according to the input parameters', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    generateRequest(),
                    clientFeatures({ minLength: 1 }),
                    async (request, features) => {
                        await seedDatabase(db, features, request.environment);

                        // get a subset of projects that exist among the features
                        const [projects] = fc.sample(
                            fc.oneof(
                                fc.constant(ALL as '*'),
                                fc.uniqueArray(
                                    fc.constantFrom(
                                        ...features.map(
                                            (feature) => feature.project,
                                        ),
                                    ),
                                ),
                            ),
                        );

                        request.projects = projects as any;

                        // create a list of features that can be filtered
                        // pass in args that should filter the list
                        const body = await playgroundRequest(
                            app,
                            token.secret,
                            request,
                        );

                        switch (projects) {
                            case ALL:
                                // no features have been filtered out
                                return body.features.length === features.length;
                            case []:
                                // no feature should be without a project
                                return body.features.length === 0;
                            default:
                                // every feature should be in one of the prescribed projects
                                return body.features.every((feature) =>
                                    projects.includes(feature.projectId),
                                );
                        }
                    },
                )
                .afterEach(reset(db)),
            testParams,
        );
    })

Summary: The feature filtering should correctly match the input parameters in terms of projects, ensuring all features belong to specified projects or none if no projects are specified.


it('should map project and name correctly', async () => {
        // note: we're not testing `isEnabled` and `variant` here, because
        // that's the SDK's responsibility and it's tested elsewhere.
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeatures(),
                    fc.context(),
                    async (features, ctx) => {
                        await seedDatabase(db, features, 'default');

                        const body = await playgroundRequest(
                            app,
                            token.secret,
                            {
                                projects: ALL,
                                environment: DEFAULT_ENV,
                                context: {
                                    appName: 'playground-test',
                                },
                            },
                        );

                        const createDict = (xs: { name: string }[]) =>
                            xs.reduce(
                                (acc, next) => ({ ...acc, [next.name]: next }),
                                {},
                            );

                        const mappedToggles = createDict(body.features);

                        if (features.length !== body.features.length) {
                            ctx.log(
                                `I expected the number of mapped flags (${body.features.length}) to be the same as the number of created toggles (${features.length}), but that was not the case.`,
                            );
                            return false;
                        }

                        return features.every((feature) => {
                            const mapped: PlaygroundFeatureSchema =
                                mappedToggles[feature.name];

                            expect(mapped).toBeTruthy();

                            return (
                                feature.name === mapped.name &&
                                feature.project === mapped.projectId
                            );
                        });
                    },
                )
                .afterEach(reset(db)),
            testParams,
        );
    })

Summary: The property should ensure that for each created feature toggle, the project and name are accurately mapped in the playground response.


it('isEnabledInCurrentEnvironment should always match feature.enabled', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeatures(),
                    fc.context(),
                    async (features, ctx) => {
                        await seedDatabase(db, features, DEFAULT_ENV);

                        const body = await playgroundRequest(
                            app,
                            token.secret,
                            {
                                projects: ALL,
                                environment: DEFAULT_ENV,
                                context: {
                                    appName: 'playground-test',
                                },
                            },
                        );

                        const createDict = (xs: { name: string }[]) =>
                            xs.reduce(
                                (acc, next) => ({ ...acc, [next.name]: next }),
                                {},
                            );

                        const mappedToggles = createDict(body.features);

                        ctx.log(JSON.stringify(features));
                        ctx.log(JSON.stringify(mappedToggles));

                        return features.every(
                            (feature) =>
                                feature.enabled ===
                                mappedToggles[feature.name]
                                    .isEnabledInCurrentEnvironment,
                        );
                    },
                )
                .afterEach(reset(db)),
            testParams,
        );
    })

Summary: The `isEnabledInCurrentEnvironment` property should match the `feature.enabled` status for all features in the test environment.


it('applies appName constraints correctly', async () => {
            const appNames = ['A', 'B', 'C'];

            // Choose one of the app names at random
            const appName = () => fc.constantFrom(...appNames);

            // generate a list of features that are active only for a specific
            // app name (constraints). Each feature will be constrained to a
            // random appName from the list above.
            const constrainedFeatures = (): Arbitrary<ClientFeatureSchema[]> =>
                fc.uniqueArray(
                    fc
                        .tuple(
                            clientFeature(),
                            fc.record({
                                name: fc.constant('default'),
                                constraints: fc
                                    .record({
                                        values: appName().map(toArray),
                                        inverted: fc.constant(false),
                                        operator: fc.constant('IN' as const),
                                        contextName: fc.constant('appName'),
                                        caseInsensitive: fc.boolean(),
                                    })
                                    .map(toArray),
                            }),
                        )
                        .map(([feature, strategy]) => ({
                            ...feature,
                            enabled: true,
                            strategies: [strategy],
                        })),
                    { selector: (feature) => feature.name },
                );

            await fc.assert(
                fc
                    .asyncProperty(
                        fc
                            .tuple(appName(), generateRequest())
                            .map(([generatedAppName, req]) => ({
                                ...req,
                                // generate a context that has appName set to
                                // one of the above values
                                context: {
                                    appName: generatedAppName,
                                    environment: DEFAULT_ENV,
                                },
                            })),
                        constrainedFeatures(),
                        async (req, features) => {
                            await seedDatabase(db, features, req.environment);
                            const body = await playgroundRequest(
                                app,
                                token.secret,
                                req,
                            );

                            const shouldBeEnabled = features.reduce(
                                (acc, next) => ({
                                    ...acc,
                                    [next.name]:
                                        // @ts-ignore
                                        next.strategies[0].constraints[0]
                                            .values[0] === req.context.appName,
                                }),
                                {},
                            );

                            return body.features.every(
                                (feature) =>
                                    feature.isEnabled ===
                                    shouldBeEnabled[feature.name],
                            );
                        },
                    )
                    .afterEach(reset(db)),
                {
                    ...testParams,
                    examples: [],
                },
            );
        })

Summary: AppName constraints are applied correctly by ensuring that features are only enabled when their associated constraints match the specified app name in the request context.


it('applies dynamic context fields correctly', async () => {
            const contextValue = () =>
                fc.oneof(
                    fc.record({
                        name: fc.constant('remoteAddress'),
                        value: fc.ipV4(),
                        operator: fc.constant('IN' as const),
                    }),
                    fc.record({
                        name: fc.constant('sessionId'),
                        value: fc.uuid(),
                        operator: fc.constant('IN' as const),
                    }),
                    fc.record({
                        name: fc.constant('userId'),
                        value: fc.emailAddress(),
                        operator: fc.constant('IN' as const),
                    }),
                );

            const constrainedFeatures = (): Arbitrary<ClientFeatureSchema[]> =>
                fc.uniqueArray(
                    fc
                        .tuple(
                            clientFeature(),
                            contextValue().map((context) => ({
                                name: 'default',
                                constraints: [
                                    {
                                        values: [context.value],
                                        inverted: false,
                                        operator: context.operator,
                                        contextName: context.name,
                                        caseInsensitive: false,
                                    },
                                ],
                            })),
                        )
                        .map(([feature, strategy]) => ({
                            ...feature,
                            enabled: true,
                            strategies: [strategy],
                        })),
                    { selector: (feature) => feature.name },
                );
            await fc.assert(
                fc
                    .asyncProperty(
                        fc
                            .tuple(contextValue(), generateRequest())
                            .map(([generatedContextValue, req]) => ({
                                ...req,
                                // generate a context that has a dynamic context field set to
                                // one of the above values
                                context: {
                                    ...req.context,
                                    [generatedContextValue.name]:
                                        generatedContextValue.value,
                                },
                            })),
                        constrainedFeatures(),
                        async (req, features) => {
                            await seedDatabase(db, features, 'default');

                            const body = await playgroundRequest(
                                app,
                                token.secret,
                                req,
                            );

                            const contextField = Object.values(req.context)[0];

                            const shouldBeEnabled = features.reduce(
                                (acc, next) => ({
                                    ...acc,
                                    [next.name]:
                                        next.strategies![0].constraints![0]
                                            .values![0] === contextField,
                                }),
                                {},
                            );
                            return body.features.every(
                                (feature) =>
                                    feature.isEnabled ===
                                    shouldBeEnabled[feature.name],
                            );
                        },
                    )
                    .afterEach(reset(db)),
                testParams,
            );
        })

Summary: Dynamic context fields should correctly enable or disable features based on matching constraints within the provided context.


test('playgroundRequestSchema', () =>
    fc.assert(
        fc.property(
            generate(),
            (data: PlaygroundRequestSchema) =>
                validateSchema(playgroundRequestSchema.$id, data) === undefined,
        ),
    ))

Summary: Validation of `PlaygroundRequestSchema` instances should pass without errors, ensuring they conform to the defined schema.


test('playgroundFeatureSchema', () =>
    fc.assert(
        fc.property(
            generate(),
            fc.context(),
            (data: PlaygroundFeatureSchema, ctx) => {
                const results = validateSchema(
                    playgroundFeatureSchema.$id,
                    data,
                );
                ctx.log(JSON.stringify(results));
                return results === undefined;
            },
        ),
    ))

Summary: The generated `PlaygroundFeatureSchema` should validate successfully against the `playgroundFeatureSchema` without errors.


it('should return the provided input arguments as part of the response', async () => {
        await fc.assert(
            fc.asyncProperty(
                generateRequest(),
                async (payload: PlaygroundRequestSchema) => {
                    const { request, base } = await getSetup();
                    const { body } = await request
                        .post(`${base}/api/admin/playground`)
                        .send(payload)
                        .expect('Content-Type', /json/)
                        .expect(200);

                    expect(body.input).toStrictEqual(payload);

                    return true;
                },
            ),
            testParams,
        );
    })

Summary: The response should include the provided input arguments as part of the body.


it('should return 400 if any of the required query properties are missing', async () => {
        await fc.assert(
            fc.asyncProperty(
                generateRequest(),
                fc.constantFrom(...playgroundRequestSchema.required),
                async (payload, requiredKey) => {
                    const { request, base } = await getSetup();

                    delete payload[requiredKey];

                    const { status } = await request
                        .post(`${base}/api/admin/playground`)
                        .send(payload)
                        .expect('Content-Type', /json/);

                    expect(status).toBe(400);
                },
            ),
            testParams,
        );
    })

Summary: A 400 status code should be returned when a required query property is missing in the request payload.


it("should only produce integer values for the numerator and denominator", () => {
  fc.assert(
    fc.property(
      fc.integer(),
      fc.integer().filter((n) => n !== 0),
      (numerator, denominator) => {
        const fSource = { numerator, denominator };
        const fOut = simplifyFraction(fSource);
        expect(Number.isInteger(fOut.numerator)).toBe(true);
        expect(Number.isInteger(fOut.denominator)).toBe(true);
      }
    )
  );
})

Summary: `simplifyFraction` ensures the output has integer values for both the numerator and denominator.


test('For any size TSID array, first item should small than the second one', () => {
      fc.assert(
        fc.property(fc.integer({ min: 2, max: 10_000 }), (size) => {
          const arr: Array<TSID> = Array.from({ length: size }, () => getTsid())
          expect(arr[0].toBigInt()).toBeLessThan(arr[1].toBigInt())
        })
      )
    })

Summary: For any TSID array of specified size, the first item should be smaller than the second item when compared as BigInt.


test('For any size TSID array, last item should bigger than the last second one', () => {
      fc.assert(
        fc.property(fc.integer({ min: 2, max: 10_000 }), (size) => {
          const arr: Array<TSID> = Array.from({ length: size }, () => getTsid())
          expect(arr.pop()?.toBigInt()).toBeGreaterThan(arr[0].toBigInt())
        })
      )
    })

Summary: For any TSID array, the last item should be greater than the first item.


test('For any size TSID array, each item should be unique', () => {
      fc.assert(
        fc.property(fc.integer({ min: 2, max: 10_000 }), (size) => {
          const tsidArr: Array<TSID> = Array.from({ length: size }, () => getTsid())
          const tsidSet: Set<TSID> = new Set(tsidArr)
          expect(tsidArr).toHaveLength(tsidSet.size)
        })
      )
    })

Summary: For any given size of a TSID array, all items must be unique.


test("fast check", () => {
    fc.assert(
      fc.property(fc.uuid(), (uuid) => {
        expect(fromIfcGuid(toIfcGuid(uuid))).toEqual(uuid);
      }),
      { numRuns: 1_000 }
    );
  })

Summary: Converting a UUID to an IFC GUID and back should yield the original UUID.