test('should return the same enabled toggles as the raw SDK correctly mapped', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    fc
                        .tuple(generateContext(), commonISOTimestamp())
                        .map(([context, currentTime]) => ({
                            ...context,
                            userId: 'constant',
                            sessionId: 'constant2',
                            currentTime,
                        })),
                    fc.context(),
                    async ({ segments, features }, context, ctx) => {
                        const serviceToggles = await insertAndEvaluateFeatures({
                            features: features,
                            context,
                            segments,
                        });

                        const [head, ...rest] =
                            await featureToggleService.getClientFeatures();
                        if (!head) {
                            return serviceToggles.length === 0;
                        }

                        const client = await offlineUnleashClientNode({
                            features: [head, ...rest],
                            context,
                            logError: console.log,
                            segments: segments.map(mapSegmentSchemaToISegment),
                        });

                        const clientContext = {
                            ...context,

                            currentTime: context.currentTime
                                ? new Date(context.currentTime)
                                : undefined,
                        };

                        return serviceToggles.every((feature) => {
                            ctx.log(
                                `Examining feature ${
                                    feature.name
                                }: ${JSON.stringify(feature)}`,
                            );

                            // the playground differs from a normal SDK in that
                            // it _must_ evaluate all strategies and features
                            // regardless of whether they're supposed to be
                            // enabled in the current environment or not.
                            const expectedSDKState = feature.isEnabled;

                            const enabledStateMatches =
                                expectedSDKState ===
                                client.isEnabled(feature.name, clientContext);

                            ctx.log(
                                `feature.isEnabled, feature.isEnabledInCurrentEnvironment, presumedSDKState: ${feature.isEnabled}, ${feature.isEnabledInCurrentEnvironment}, ${expectedSDKState}`,
                            );
                            ctx.log(
                                `client.isEnabled: ${client.isEnabled(
                                    feature.name,
                                    clientContext,
                                )}`,
                            );
                            expect(enabledStateMatches).toBe(true);

                            // if x is disabled, then the variant will be the
                            // disabled variant.
                            if (!feature.isEnabled) {
                                ctx.log(`${feature.name} is not enabled`);
                                ctx.log(JSON.stringify(feature.variant));
                                ctx.log(JSON.stringify(enabledStateMatches));
                                ctx.log(
                                    JSON.stringify(
                                        feature.variant?.name === 'disabled',
                                    ),
                                );
                                ctx.log(
                                    JSON.stringify(
                                        feature.variant?.enabled === false,
                                    ),
                                );
                                return (
                                    enabledStateMatches &&
                                    isDisabledVariant(feature.variant)
                                );
                            }
                            ctx.log('feature is enabled');

                            const clientVariant = client.getVariant(
                                feature.name,
                                clientContext,
                            );

                            // if x is enabled, but its variant is the disabled
                            // variant, then the source does not have any
                            // variants
                            if (isDisabledVariant(feature.variant)) {
                                return (
                                    enabledStateMatches &&
                                    isDisabledVariant(clientVariant)
                                );
                            }

                            ctx.log(`feature "${feature.name}" has a variant`);
                            ctx.log(
                                `Feature variant: ${JSON.stringify(
                                    feature.variant,
                                )}`,
                            );
                            ctx.log(
                                `Client variant: ${JSON.stringify(
                                    clientVariant,
                                )}`,
                            );
                            ctx.log(
                                `enabledStateMatches: ${enabledStateMatches}`,
                            );

                            // variants should be the same if the
                            // toggle is enabled in both versions. If
                            // they're not and one of them has a
                            // variant, then they should be different.
                            if (expectedSDKState === true) {
                                expect(feature.variant).toEqual(clientVariant);
                            } else {
                                expect(feature.variant).not.toEqual(
                                    clientVariant,
                                );
                            }

                            return enabledStateMatches;
                        });
                    },
                )
                .afterEach(cleanup),
            { ...testParams, examples: [] },
        );
    })

Summary: Verifies that the enabled feature toggles returned by the playground service align with those derived from the raw SDK, ensuring consistent evaluation of features and their variants regardless of environment settings.


unknown

it('applies custom context fields correctly', async () => {
            const environment = 'default';
            const contextValue = () =>
                fc.record({
                    name: fc.constantFrom('Context field A', 'Context field B'),
                    value: fc.constantFrom(
                        'Context value 1',
                        'Context value 2',
                    ),
                });
            const constrainedFeatures = (): Arbitrary<ClientFeatureSchema[]> =>
                fc.uniqueArray(
                    fc
                        .tuple(
                            clientFeature(),
                            contextValue().map((context) => ({
                                name: 'default',
                                constraints: [
                                    {
                                        values: [context.value],
                                        inverted: false,
                                        operator: 'IN' as const,
                                        contextName: context.name,
                                        caseInsensitive: false,
                                    },
                                ],
                            })),
                        )
                        .map(([feature, strategy]) => ({
                            ...feature,
                            enabled: true,
                            strategies: [strategy],
                        })),
                    { selector: (feature) => feature.name },
                );

            // generate a constraint to be used for the context and a request
            // that contains that constraint value.
            const constraintAndRequest = () =>
                fc
                    .tuple(
                        contextValue(),
                        fc.constantFrom('top', 'nested'),
                        generateRequest(),
                    )
                    .map(([generatedContextValue, placement, req]) => {
                        const request =
                            placement === 'top'
                                ? {
                                      ...req,
                                      environment,
                                      context: {
                                          ...req.context,
                                          [generatedContextValue.name]:
                                              generatedContextValue.value,
                                      },
                                  }
                                : {
                                      ...req,
                                      environment,
                                      context: {
                                          ...req.context,
                                          properties: {
                                              [generatedContextValue.name]:
                                                  generatedContextValue.value,
                                          },
                                      },
                                  };

                        return {
                            generatedContextValue,
                            request,
                        };
                    });

            await fc.assert(
                fc
                    .asyncProperty(
                        constraintAndRequest(),
                        constrainedFeatures(),
                        fc.context(),
                        async (
                            { generatedContextValue, request },
                            features,
                            ctx,
                        ) => {
                            await seedDatabase(db, features, environment);

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

                            const shouldBeEnabled = features.reduce(
                                (acc, next) => {
                                    const constraint =
                                        next.strategies![0].constraints![0];

                                    return {
                                        ...acc,
                                        [next.name]:
                                            constraint.contextName ===
                                                generatedContextValue.name &&
                                            constraint.values![0] ===
                                                generatedContextValue.value,
                                    };
                                },
                                {},
                            );

                            ctx.log(
                                `Got these ${JSON.stringify(
                                    body.features,
                                )} and I expect them to be enabled/disabled: ${JSON.stringify(
                                    shouldBeEnabled,
                                )}`,
                            );

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

Summary: A feature's enabled status should match the expected outcome based on custom context fields and constraints when processed through the playground request.


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

Summary: `SdkContextSchema` is validated successfully by ensuring that randomly generated data conforming to its structure results in no validation errors.


it('executorComposeOption', async () => {
        await fc.assert(
            fc.asyncProperty(
                omnicounterIncrementTypeArbitrary,
                composedIndexArbitrary,
                gasLimitArbitrary,
                nativeDropArbitrary,

                // Test the generation and submission of arbitrary COMPOSE Options.  The transaction should succeed, and
                // the options from the transaction receipt logs should match the generated input.
                async (type, index, gasLimit, nativeDrop) => {
                    const options = Options.newOptions()
                        .addExecutorComposeOption(index, gasLimit, nativeDrop)
                        // We also need to add a lzReceive option to avoid Executor_ZeroLzReceiveGasProvided error
                        .addExecutorLzReceiveOption(MIN_GAS_LIMIT)
                    const packetSentEvents = await incrementAndReturnLogs(type, options)
                    expect(packetSentEvents).toEqual([
                        expect.objectContaining({
                            args: expect.objectContaining({
                                options: expect.toEqualCaseInsensitive(options.toHex()),
                            }),
                        }),
                    ])
                    const rawPacketOptions = packetSentEvents[0]!.args.options
                    expect(rawPacketOptions).toEqualCaseInsensitive(options.toHex())

                    // test decoding
                    const packetOptions = Options.fromOptions(rawPacketOptions)
                    const decodedExecutorComposeOptions = packetOptions.decodeExecutorComposeOption()
                    expect(decodedExecutorComposeOptions).toEqual([
                        {
                            index,
                            gas: gasLimit,
                            value: nativeDrop,
                        },
                    ])
                    expect(packetOptions.decodeExecutorLzReceiveOption()).toEqual({
                        gas: MIN_GAS_LIMIT,
                        value: BigInt(0),
                    })
                    expect(packetOptions.decodeExecutorNativeDropOption()).toEqual([])
                    expect(packetOptions.decodeExecutorOrderedExecutionOption()).toEqual(false)
                }
            ),
            { numRuns: 20 }
        )
    })

Summary: The test verifies that generating and submitting arbitrary `COMPOSE` options results in successful transactions, with the transaction receipt logs matching the generated inputs. It also confirms proper decoding of the `ExecutorComposeOption` and other options, ensuring accuracy in the options' processing and representation.


it('not parse an event with many args with unknown name from a different contract', async () => {
        await fc.assert(
            fc.asyncProperty(fc.integer({ min: 0, max: 10 }), fc.string(), async (count, name) => {
                fc.pre(name !== 'NoArgEvent')
                fc.pre(name !== 'OneArgEvent')
                fc.pre(name !== 'FourArgEvent')

                const receipt = await (await child.emitMany(count)).wait()

                expect(parseLogsWithName(receipt, parent, name)).toEqual([])
            }),
            { numRuns: 10 }
        )
    })

Summary: Ensures that events with unspecified names from a contract's logs do not get parsed into recognizable events when emitted multiple times.


it('should parse revert with arguments', async () => {
            await fc.assert(
                fc.asyncProperty(endpointArbitrary, async (eid) => {
                    const errorParser = await createContractErrorParser({ contract, eid })
                    const error = await assertFailed(contract.throwWithRevertAndArgument('my bad'))
                    const parsedError = await errorParser(error)

                    expect(parsedError).toEqual(new RevertError('my bad'))
                })
            )
        })

Summary: The test checks that `createContractErrorParser` correctly parses an error from a contract revert with a specific argument.


it('should parse require with a custom error with an argument', async () => {
            await fc.assert(
                fc.asyncProperty(endpointArbitrary, fc.string(), async (eid, arg) => {
                    const errorParser = await createContractErrorParser({ contract, eid })
                    const error = await assertFailed(contract.throwWithCustomErrorAndArgument(arg))
                    const parsedError = await errorParser(error)

                    expect(parsedError).toEqual(new CustomError('CustomErrorWithAnArgument', [arg]))
                })
            )
        })

Summary: Parses a custom error with an argument from a contract execution, ensuring it matches the expected format.


it('should work for non-negative integers', () => {
            fc.assert(
                fc.property(fc.integer({ min: 0 }), (value) => {
                    expect(UIntBigIntSchema.parse(value)).toBe(BigInt(value))
                })
            )
        })

Summary: `UIntBigIntSchema` correctly parses non-negative integers into their `BigInt` equivalents.


it("should produce different serialized values if the vector don't match", () => {
                fc.assert(
                    fc.property(pointArbitrary, pointArbitrary, (pointA, pointB) => {
                        fc.pre(!arePointsEqual(pointA, pointB))

                        expect(serializePoint(pointA)).not.toBe(serializePoint(pointB))
                    })
                )
            })

Summary: Different serialized values are produced if points are not equal.


it('should bail on the first submission error', async () => {
                    await fc.assert(
                        fc.asyncProperty(
                            fc.array(transactionArbitrary),
                            transactionArbitrary,
                            fc.array(transactionArbitrary),
                            async (firstBatch, failedTransaction, secondBatch) => {
                                // We'll prepare some mock objects for this test
                                // to mock the transaction responses and receipts
                                const error = new Error('Failed transaction')
                                const receipt = { transactionHash: '0x0' }
                                const successfulWait = jest.fn().mockResolvedValue(receipt)
                                const successfulResponse: OmniTransactionResponse = {
                                    transactionHash: '0x0',
                                    wait: successfulWait,
                                }

                                // In order to resolve the good ones and reject the bad ones
                                // we'll prepare a map between a transaction and its response
                                //
                                // This map relies on the fact that we are passing the transaction object without modifying it
                                // so the objects are referentially equal
                                const implementations: Map<OmniTransaction, Promise<unknown>> = new Map([
                                    ...firstBatch.map((t) => [t, Promise.resolve(successfulResponse)] as const),
                                    ...secondBatch.map((t) => [t, Promise.resolve(successfulResponse)] as const),
                                    [failedTransaction, Promise.reject(error)],
                                ])

                                const expectedSuccessful = [
                                    // The first batch should all go through
                                    ...firstBatch,
                                    // The transactions that are not on the chain affected by the failed transaction should also pass
                                    ...secondBatch.filter(({ point }) => point.eid !== failedTransaction.point.eid),
                                ]

                                const expectedPending = secondBatch.filter(
                                    ({ point }) => point.eid === failedTransaction.point.eid
                                )

                                // Our signAndSend will then use the map to resolve/reject transactions
                                const signAndSend = jest.fn().mockImplementation((t) => implementations.get(t))
                                const sign = jest.fn().mockRejectedValue('Oh god no')
                                const signerFactory: OmniSignerFactory = jest
                                    .fn()
                                    .mockResolvedValue({ signAndSend, sign })
                                const signAndSendTransactions = createSignAndSend(signerFactory)

                                // Now we send all the transactions to the flow and observe the output
                                const transactions = [...firstBatch, failedTransaction, ...secondBatch]
                                const [successful, errors, pending] = await signAndSendTransactions(transactions)

                                // Since we are executing groups of transactions in parallel,
                                // in general the order of successful transaction will not match the order of input transactions
                                expect(successful).toContainAllValues(
                                    expectedSuccessful.map((transaction) => ({ transaction, receipt }))
                                )
                                expect(errors).toEqual([{ transaction: failedTransaction, error }])
                                expect(pending).toEqual([failedTransaction, ...expectedPending])

                                // What needs to match though is the order of successful transactions within groups
                                //
                                // For that we group the successful transactions and make sure those are equal to the grouped original transactions
                                const groupedSuccessful = groupTransactionsByEid(
                                    successful.map(({ transaction }) => transaction)
                                )
                                expect(groupedSuccessful).toEqual(groupTransactionsByEid(expectedSuccessful))

                                // We also check that the signer factory has been called with the eids
                                expect(signerFactory).toHaveBeenCalledWith(failedTransaction.point.eid)
                                for (const transaction of firstBatch) {
                                    expect(signerFactory).toHaveBeenCalledWith(transaction.point.eid)
                                }
                            }
                        )
                    )
                })

Summary: The property ensures that when a series of transactions are processed, an error in the first submitted transaction causes it to stop attempting further submissions within the same group, and correctly reports successful, errored, and pending transactions.


it('should return true for two nullish values', () => {
            fc.assert(
                fc.property(zeroishBytes32Arbitrary, zeroishBytes32Arbitrary, (a, b) => {
                    expect(areBytes32Equal(a, b)).toBe(true)
                })
            )
        })

Summary: `areBytes32Equal` returns true for two nullish `bytes32` values.


it('should return true for two identical values', () => {
            fc.assert(
                fc.property(evmBytes32Arbitrary, (a) => {
                    expect(areBytes32Equal(a, a)).toBe(true)
                })
            )
        })

Summary: `areBytes32Equal` returns true when comparing two identical `Bytes32` values.


it('should return false for a zeroish value and a non-zeroish bytes', () => {
            fc.assert(
                fc.property(zeroishBytes32Arbitrary, evmBytes32Arbitrary, (a, b) => {
                    fc.pre(!isZero(b))

                    expect(areBytes32Equal(a, b)).toBe(false)
                })
            )
        })

Summary: The test checks that `areBytes32Equal` returns false when comparing a zeroish value with a non-zeroish bytes value, where the non-zeroish bytes value is ensured not to be zero.


it('should return 0 for two identical addresses', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, (address) => {
                    expect(compareBytes32Ascending(address, address)).toBe(0)
                    expect(compareBytes32Ascending(address, makeBytes32(address))).toBe(0)
                    expect(compareBytes32Ascending(makeBytes32(address), makeBytes32(address))).toBe(0)
                })
            )
        })

Summary: Comparing two identical Ethereum addresses, whether converted to a 32-byte format or not, should result in `compareBytes32Ascending` returning 0.


it('should resolve if all resolve', async () => {
            await fc.assert(
                fc.asyncProperty(valuesArbitrary, async (values) => {
                    const tasks = values.map((value) => jest.fn().mockResolvedValue(value))

                    expect(await sequence(tasks)).toEqual(values)

                    // Make sure all the tasks got called
                    for (const task of tasks) {
                        expect(task).toHaveBeenCalledTimes(1)
                        expect(task).toHaveBeenCalledWith()
                    }
                })
            )
        })

Summary: `sequence` resolves all tasks in order and ensures each task is called once with no arguments.


it('should return a negative if address comes before the other address', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, evmAddressArbitrary, (addressA, addressB) => {
                    fc.pre(addressA.toLowerCase() < addressB.toLowerCase())

                    expect(compareBytes32Ascending(addressA, addressB)).toBeLessThan(0)
                    expect(compareBytes32Ascending(addressA, makeBytes32(addressB))).toBeLessThan(0)
                    expect(compareBytes32Ascending(makeBytes32(addressA), addressB)).toBeLessThan(0)
                    expect(compareBytes32Ascending(makeBytes32(addressA), makeBytes32(addressB))).toBeLessThan(0)
                })
            )
        })

Summary: The function `compareBytes32Ascending` should return a negative value when one Ethereum address comes before another in a lexicographical order.


it('should reject with the first rejection', async () => {
            await fc.assert(
                fc.asyncProperty(valuesArbitrary, valueArbitrary, valuesArbitrary, async (values1, error, values2) => {
                    const tasks1 = values1.map((value) => jest.fn().mockResolvedValue(value))
                    const failingTask = jest.fn().mockRejectedValue(error)
                    const tasks2 = values2.map((value) => jest.fn().mockResolvedValue(value))
                    const tasks = [...tasks1, failingTask, ...tasks2]

                    await expect(sequence(tasks)).rejects.toBe(error)

                    // Make sure the first batch got called
                    for (const task of tasks1) {
                        expect(task).toHaveBeenCalledTimes(1)
                        expect(task).toHaveBeenCalledWith()
                    }

                    // Make sure the failing task got called
                    expect(failingTask).toHaveBeenCalledTimes(1)
                    expect(failingTask).toHaveBeenCalledWith()

                    // Make sure the second batch didn't get called
                    for (const task of tasks2) {
                        expect(task).not.toHaveBeenCalled()
                    }
                })
            )
        })

Summary: The test ensures that a sequence of asynchronous tasks will be rejected with the first encountered rejection, allowing preceding tasks to execute while preventing subsequent tasks from being called after the rejection occurs.


it('should pass the original value if contract is already an OmniPoint', async () => {
            await fc.assert(
                fc.asyncProperty(pointArbitrary, async (point) => {
                    const contractFactory = jest.fn().mockRejectedValue('Oh no')
                    const transformer = createOmniPointHardhatTransformer(contractFactory)

                    const transformed = await transformer(point)

                    expect(transformed).toBe(point)
                    expect(contractFactory).not.toHaveBeenCalled()
                })
            )
        })

Summary: The property should maintain the original value if the input is already an OmniPoint, without invoking the `contractFactory`.


it("should handle arbitrary inputs gracefully without crashing", () => {
    fc.assert(fc.property(fc.string(), (arbitrary) => {
      const result = extractTestAnnotations(arbitrary);
      expect(result).toEqual({});
    }));
  })

Summary: `extractTestAnnotations` should return an empty object when processing arbitrary string inputs without crashing.


it("should remove from testables", () => {
      fc.assert(
        fc.property(arbNonEmptyManifest, (manifest) => {
          const packageName = recordKeys(manifest.dependencies)[0]!;

          const [updated] = tryRemoveProjectDependency(
            manifest,
            packageName
          ).unwrap();

          const hasTestable = updated.testables?.includes(packageName) ?? false;
          expect(hasTestable).toBeFalsy();
        })
      );
    })

Summary: Removing a package dependency from a manifest should also ensure it is not present in the `testables` list.


it("should should be atomic", () => {
      fc.assert(
        fc.property(
          arbManifestWithDependencyCount(10),
          arbDomainName,
          (manifest, missingPackage) => {
            // In the rare case where the generated manifest has the dependency
            // we skip this test.
            if (hasDependency(manifest, missingPackage)) return;

            // A mix of packages that are in the package and one
            // which is not.
            const packagesToRemove = [
              ...recordKeys(manifest.dependencies).slice(0, 2),
              missingPackage,
              ...recordKeys(manifest.dependencies).slice(3, 5),
            ];

            const error = tryRemoveProjectDependencies(
              manifest,
              packagesToRemove
            ).unwrapErr();

            expect(error).toEqual(new PackumentNotFoundError(missingPackage));
          }
        )
      );
    })

Summary: Removing dependencies from a manifest should result in an error if a non-existent package is included, ensuring the operation is atomic.


it("should have correct change for existing dependency", () => {
      fc.assert(
        fc.property(
          arbManifest,
          arbDomainName,
          abrDependencyVersion,
          (manifest, packageName, version) => {
            // Make sure version is already in the manifest
            manifest = addProjectDependency(manifest, packageName, version)[0];

            const [, change] = addProjectDependency(
              manifest,
              packageName,
              version
            );

            expect(change).toEqual<AddResult>({
              type: "noChange",
              version,
            });
          }
        )
      );
    })

Summary: Adding an existing dependency version to a manifest should result in a change type of "noChange".


it("should round-trip", () => {
    fc.assert(
      fc.property(fc.string(), (expected) => {
        const encoded = encodeBase64(expected);
        const actual = decodeBase64(encoded);

        expect(actual).toEqual(expected);
      })
    );
  })

Summary: Encoding a string with `encodeBase64` and then decoding it with `decodeBase64` should return the original string.


it('does not allow to edit for invalid input', async () =>
          await fc.assert(
            fc.asyncProperty(invertedRegex(/^[0-9]*$/), async testValue => {
              input!.value = testValue;
              await element.requestUpdate();
              expect(input!.checkValidity()).to.be.false;
            })
          ))

Summary: Editing is disallowed for inputs that do not match the regex pattern of digits only.


it('allow to edit for valid input', async () =>
          await fc.assert(
            fc.asyncProperty(ipV6SubNet(), async testValue => {
              input!.value = testValue;
              await element.requestUpdate();
              expect(input!.checkValidity()).to.be.true;
            })
          ))

Summary: The test ensures that the validity check on an input element returns true for valid IPv6 subnet values.


it('does not allow to edit for invalid input', async () =>
          await fc.assert(
            fc.asyncProperty(invertedRegex(regExp.IPv6), async testValue => {
              input!.value = testValue;
              await element.requestUpdate();
              expect(input!.checkValidity()).to.be.false;
            })
          ))

Summary: Editing is disallowed for invalid IPv6 input values based on checkValidity returning false.


it('Length of interspersed = len(arr) + len(arr)-1', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.integer(),
      (arr, delimiter) => {
        const actual = Jam.intersperse(arr, delimiter);
        const expected = arr.length === 0 ? 0 : arr.length * 2 - 1;
        assert.deepEqual(actual.length, expected);
      }
    ));
  })

Summary: The length of the array returned by `Jam.intersperse` is equal to the original array's length plus its length minus one when a delimiter is added.


it('forall of a non-empty array with a predicate that always returns true is true', () => {
    fc.assert(fc.property(
      fc.array(fc.integer(), 1, 30),
      (xs) => {
        assert.isTrue(Arr.forall(xs, Fun.always));
      }
    ));
  })

Summary: A non-empty array with a predicate that always returns true results in `Arr.forall` returning true.


it('foldl concat ys xs === reverse(xs) ++ ys', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.array(fc.integer()),
      (xs, ys) => {
        const output = Arr.foldl(xs, (b, a) => [ a ].concat(b), ys);
        assert.deepEqual(output, Arr.reverse(xs).concat(ys));
      }
    ));
  })

Summary: `Arr.foldl` with concatenation should produce the same result as reversing the first array and concatenating it with the second array.


it('returns none if predicate always returns false', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (arr) => {
      assertNone(Arr.findIndex(arr, Fun.never));
    }));
  })

Summary: `Arr.findIndex` returns none when the predicate always returns false on an array of integers.


it('foldr concat ys xs === xs ++ ys', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.array(fc.integer()),
      (xs, ys) => {
        const output = Arr.foldr(xs, (b, a) => [ a ].concat(b), ys);
        assert.deepEqual(output, xs.concat(ys));
      }
    ));
  })

Summary: `Arr.foldr` concatenates two arrays such that the result is equivalent to appending the second array to the first.


it('finds elements that pass the predicate', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (arr) => {
      const pred = (x: number) => x % 3 === 0;
      assert.isTrue(Arr.findIndex(arr, pred).forall((x) => pred(arr[x])));
    }));
  })

Summary: The test verifies that `Arr.findIndex` correctly identifies the index of elements in an integer array that satisfy a predicate checking if a number is divisible by 3.


it('is consistent with exists', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (arr) => {
      const pred = (x: number) => x % 6 === 0;
      assert.equal(Arr.findIndex(arr, pred).isSome(), Arr.exists(arr, pred));
    }));
  })

Summary: `Arr.findIndex` returning an optional value should be consistent with `Arr.exists` when using the same predicate.


it('Element not found when predicate always returns false', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (arr) => !Arr.exists(arr, never)));
  })

Summary: `Arr.exists` should return false when applied with a predicate that always returns false.


it('queries with `splits: inline` returns only non-parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 20,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'inline' })
              .serialize(),
          );

          expect(data.filter(t => t.is_parent).length).toBe(0);
          expect(data.filter(t => t.tombstone).length).toBe(0);

          const { data: defaultData } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .serialize(),
          );

          // inline should be the default
          expect(defaultData).toEqual(data);
        },
      ),
      { numRuns: 50 },
    );
  })

Summary: Queries with `splits: inline` should return transactions that are non-parent and non-tombstoned, matching the default query behavior.


describe('transaction executors', () => {
  it('queries with `splits: inline` returns only non-parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 20,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'inline' })
              .serialize(),
          );

          expect(data.filter(t => t.is_parent).length).toBe(0);
          expect(data.filter(t => t.tombstone).length).toBe(0);

          const { data: defaultData } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .serialize(),
          );

          // inline should be the default
          expect(defaultData).toEqual(data);
        },
      ),
      { numRuns: 50 },
    );
  });

  it('queries with `splits: none` returns only parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 8,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'none' })
              .serialize(),
          );

          expect(data.filter(t => t.is_child).length).toBe(0);
        },
      ),
      { numRuns: 50 },
    );
  });

  it('aggregate queries work with `splits: grouped`', async () => {
    const payeeIds = ['payee1', 'payee2', 'payee3', 'payee4', 'payee5'];

    await fc.assert(
      fc
        .asyncProperty(
          arbs.makeTransactionArray({ splitFreq: 2, payeeIds, maxLength: 100 }),
          async arr => {
            await insertTransactions(arr, payeeIds);

            const aggQuery = q('transactions')
              .filter({
                $or: [{ amount: { $lt: -5 } }, { amount: { $gt: -2 } }],
                'payee.name': { $gt: '' },
              })
              .options({ splits: 'grouped' })
              .calculate({ $sum: '$amount' });

            const { data } = await runQuery(aggQuery.serialize());

            const sum = aliveTransactions(arr).reduce((sum, trans) => {
              const amount = trans.amount || 0;
              const matched =
                (amount < -5 || amount > -2) && trans.payee != null;
              if (!trans.tombstone && !trans.is_parent && matched) {
                return sum + amount;
              }
              return sum;
            }, 0);

            expect(data).toBe(sum);
          },
        )
        .beforeEach(() => {
          setClock(null);
          setSyncingMode('import');
          return db.execQuery(`
            DELETE FROM transactions;
            DELETE FROM payees;
            DELETE FROM payee_mapping;
          `);
        }),
    );
  });

  function runTest(makeQuery) {
    const payeeIds = ['payee1', 'payee2', 'payee3', 'payee4', 'payee5'];

    async function check(arr) {
      const orderFields = ['payee.name', 'amount', 'id'];

      // Insert transactions and get a list of all the alive
      // ones to make it easier to check the data later (don't
      // have to always be filtering out dead ones)
      await insertTransactions(arr, payeeIds);
      const allTransactions = aliveTransactions(arr);

      // Query time
      const { query, expectedIds, expectedMatchedIds } = makeQuery(arr);

      // First to a query without order to make sure the default
      // order works
      const { data: defaultOrderData } = await runQuery(query.serialize());
      expectTransactionOrder(defaultOrderData);
      expect(new Set(defaultOrderData.map(t => t.id))).toEqual(expectedIds);

      // Now do the full test, and add a custom order to make
      // sure that doesn't effect anything
      const orderedQuery = query.orderBy(orderFields);
      const { data } = await runQuery(orderedQuery.serialize());
      expect(new Set(data.map(t => t.id))).toEqual(expectedIds);

      // Validate paging and ordering
      await expectPagedData(orderedQuery, arr.length, data);
      expectTransactionOrder(data, orderFields);

      const matchedIds = new Set();

      // Check that all the subtransactions were returned
      for (const trans of data) {
        expect(trans.tombstone).toBe(false);

        if (expectedMatchedIds) {
          if (!trans._unmatched) {
            expect(expectedMatchedIds.has(trans.id)).toBe(true);
            matchedIds.add(trans.id);
          } else {
            expect(expectedMatchedIds.has(trans.id)).not.toBe(true);
          }
        }

        if (trans.is_parent) {
          // Parent transactions should never have a category
          expect(trans.category).toBe(null);

          expect(trans.subtransactions.length).toBe(
            allTransactions.filter(t => t.parent_id === trans.id).length,
          );

          // Subtransactions should be ordered as well
          expectTransactionOrder(trans.subtransactions, orderFields);

          trans.subtransactions.forEach(subtrans => {
            expect(subtrans.tombstone).toBe(false);

            if (expectedMatchedIds) {
              if (!subtrans._unmatched) {
                expect(expectedMatchedIds.has(subtrans.id)).toBe(true);
                matchedIds.add(subtrans.id);
              } else {
                expect(expectedMatchedIds.has(subtrans.id)).not.toBe(true);
              }
            }
          });
        }
      }

      if (expectedMatchedIds) {
        // Check that transactions that should be matched are
        // marked as such
        expect(matchedIds).toEqual(expectedMatchedIds);
      }
    }

    return fc.assert(
      fc
        .asyncProperty(
          arbs.makeTransactionArray({
            splitFreq: 0.1,
            payeeIds,
            maxLength: 100,
          }),
          check,
        )
        .beforeEach(() => {
          setClock(null);
          setSyncingMode('import');
          return db.execQuery(`
            DELETE FROM transactions;
            DELETE FROM payees;
            DELETE FROM payee_mapping;
          `);
        }),
      { numRuns: 300 },
    );
  }

  it('queries the correct transactions without filters', async () => {
    return runTest(arr => {
      const expectedIds = new Set(
        arr.filter(t => !t.tombstone && !t.is_child).map(t => t.id),
      );

      // Even though we're applying some filters, these are always
      // guaranteed to return the full split transaction so they
      // should take the optimized path
      const happyQuery = q('transactions')
        .filter({
          date: { $gt: '2017-01-01' },
        })
        .options({ splits: 'grouped' })
        .select(['*', 'payee.name']);

      // Make sure it's actually taking the happy path
      expect(isHappyPathQuery(happyQuery.serialize())).toBe(true);

      return {
        expectedIds,
        query: happyQuery,
      };
    });
  });

  it(`queries the correct transactions with a filter`, async () => {
    return runTest(arr => {
      const expectedIds = new Set();

      // let parents = toGroup(
      //   arr.filter(t => t.is_parent),
      //   new Map(Object.entries(groupById(arr.filter(t => t.parent_id))))
      // );

      const parents = groupById(arr.filter(t => t.is_parent && !t.tombstone));
      const matched = new Set();

      // Pick out some ids to query
      let ids = arr.reduce((ids, trans, idx) => {
        if (idx % 2 === 0) {
          const amount = trans.amount == null ? 0 : trans.amount;
          const matches = (amount < -2 || amount > -1) && trans.payee > '';

          if (matches && isAlive(trans, parents)) {
            expectedIds.add(trans.parent_id || trans.id);
            matched.add(trans.id);
          }

          ids.push(trans.id);
        }

        return ids;
      }, []);

      // Because why not? It should deduplicate them
      ids = repeat(ids, 100);

      const unhappyQuery = q('transactions')
        .filter({
          id: [{ $oneof: ids }],
          payee: { $gt: '' },
          $or: [{ amount: { $lt: -2 } }, { amount: { $gt: -1 } }],
        })
        .options({ splits: 'grouped' })
        .select(['*', 'payee.name'])
        // Using this because we want `payee` to have ids for the above
        // filter regardless if it points to a dead one or not
        .withoutValidatedRefs();

      expect(isHappyPathQuery(unhappyQuery.serialize())).toBe(false);

      return {
        expectedIds,
        expectedMatchedIds: matched,
        query: unhappyQuery,
      };
    });
  });
})

insertTransactions aliveTransactions expectTransactionOrder expectPagedData isAlive repeat

Summary: The test ensures that querying transactions with `splits: inline` returns only non-parents and no tombstones, while `splits: none` returns only parents. It validates the aggregate queries with `splits: grouped`, checking the calculation of sums, and verifies correct transaction queries both with and without filters. The expected transaction order and paging consistency are also checked, ensuring transactions and subtransactions meet defined conditions.


it('queries with `splits: none` returns only parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 8,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'none' })
              .serialize(),
          );

          expect(data.filter(t => t.is_child).length).toBe(0);
        },
      ),
      { numRuns: 50 },
    );
  })

Summary: Queries with `splits: none` should return only parent transactions, excluding any child transactions.


it('aggregate queries work with `splits: grouped`', async () => {
    const payeeIds = ['payee1', 'payee2', 'payee3', 'payee4', 'payee5'];

    await fc.assert(
      fc
        .asyncProperty(
          arbs.makeTransactionArray({ splitFreq: 2, payeeIds, maxLength: 100 }),
          async arr => {
            await insertTransactions(arr, payeeIds);

            const aggQuery = q('transactions')
              .filter({
                $or: [{ amount: { $lt: -5 } }, { amount: { $gt: -2 } }],
                'payee.name': { $gt: '' },
              })
              .options({ splits: 'grouped' })
              .calculate({ $sum: '$amount' });

            const { data } = await aqlQuery(aggQuery.serialize());

            const sum = aliveTransactions(arr).reduce((sum, trans) => {
              const amount = trans.amount || 0;
              const matched =
                (amount < -5 || amount > -2) && trans.payee != null;
              if (!trans.tombstone && !trans.is_parent && matched) {
                return sum + amount;
              }
              return sum;
            }, 0);

            expect(data).toBe(sum);
          },
        )
        .beforeEach(() => {
          setClock(null);
          setSyncingMode('import');
          return db.execQuery(`
            DELETE FROM transactions;
            DELETE FROM payees;
            DELETE FROM payee_mapping;
          `);
        }),
    );
  }, 20_000)

Summary: Aggregate queries should produce the same sum of transaction amounts as calculated manually when using `splits: grouped` with specified filters and conditions.


it('ys-xs contains no elements from xs', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.array(fc.integer()), (xs, ys) => {
      const diff = Arr.difference(ys, xs);
      return Arr.forall(xs, (x) => !Arr.contains(diff, x));
    }));
  })

Summary: The test ensures that the result of `Arr.difference(ys, xs)` contains no elements from `xs`.


it('is idempotent', () => {
    fc.assert(fc.property(
      fc.array(fc.nat()), (arr) => {
        assert.deepEqual(Arr.sort(Arr.sort(arr)), Arr.sort(arr));
      }
    ));
  })

Summary: Sorting an array with `Arr.sort` is idempotent, as sorting it twice yields the same result as sorting it once.


it('returns none for element of empty list', () => {
    fc.assert(fc.property(fc.integer(), (n) => {
      assertNone(Arr.get<number>([], n));
    }));
  })

Summary: The function `Arr.get` should return `none` when attempting to access any element in an empty list.


it('Arr.findMap of non-empty is first if f is Optional.some', () => {
    fc.assert(fc.property(
      fc.integer(),
      fc.array(fc.integer()),
      (head, tail) => {
        const arr = [ head, ...tail ];
        assertSome(Arr.findMap(arr, Optional.some), head);
      }
    ));
  })

Summary: `Arr.findMap` returns the first element of a non-empty array when the function `f` is `Optional.some`.


it('Arr.findMap does not find an element', () => {
    fc.assert(fc.property(
      fc.array(fc.nat()),
      fc.nat(),
      (arr, ret) => {
        assertNone(Arr.findMap(arr, (x) => Optionals.someIf(x === -1, ret)));
      }
    ));
  })

Summary: `Arr.findMap` should return `None` when no element matches the condition `x === -1` in the array.


it('should never reject', async () => {
            const errorParser = await createErrorParser()

            await fc.assert(
                fc.asyncProperty(fc.anything(), async (error) => {
                    const parsedError = await errorParser(error)

                    expect(parsedError).toBeInstanceOf(UnknownError)
                    expect(parsedError.reason).toBeUndefined()
                    expect(parsedError.message).toMatch(/Unknown error: /)
                })
            )
        })

Summary: Parsing any error should result in an instance of `UnknownError` with an undefined reason and a message matching "Unknown error: ".


it('should return false if the optionalDVNs are different', async () => {
            await fc.assert(
                fc.asyncProperty(
                    channelIdArbitrary,
                    evmAddressArbitrary,
                    ulnConfigArbitrary,
                    dvnsArbitrary,
                    async (channelId, oapp, ulnConfig, extraOptionalDVNs) => {
                        getAppUlnConfigSpy.mockReset()
                        getAppUlnConfigSpy.mockResolvedValue(ulnConfig)

                        await expect(
                            ulnSdk.hasAppUlnConfig(channelId, oapp, {
                                ...ulnConfig,
                                optionalDVNs: [...ulnConfig.optionalDVNs, ...extraOptionalDVNs],
                            })
                        ).resolves.toBeFalsy()
                    }
                ),
                { numRuns: 20 }
            )
        })

Summary: The function `hasAppUlnConfig` should return false when the `optionalDVNs` field in the ULN configuration differs due to additional elements.


it('should return true if the configs are identical', async () => {
            await fc.assert(
                fc.asyncProperty(
                    endpointArbitrary,
                    evmAddressArbitrary,
                    ulnConfigArbitrary,
                    async (eid, oapp, ulnConfig) => {
                        getAppUlnConfigSpy.mockReset()
                        getAppUlnConfigSpy.mockResolvedValue(ulnConfig)

                        await expect(
                            ulnSdk.hasAppUlnConfig(eid, oapp, ulnConfig, Uln302ConfigType.Receive)
                        ).resolves.toBeTruthy()
                    }
                ),
                { numRuns: 20 }
            )
        })

Summary: `ulnSdk.hasAppUlnConfig` returns true when the endpoint and EVM address have a configuration identical to the provided `ulnConfig`.


it('should return true if the configs are identical', async () => {
            await fc.assert(
                fc.asyncProperty(
                    endpointArbitrary,
                    evmAddressArbitrary,
                    executorConfigArbitrary,
                    async (eid, oapp, executorConfig) => {
                        getAppExecutorConfigSpy.mockReset()
                        getAppExecutorConfigSpy.mockResolvedValue(executorConfig)

                        await expect(ulnSdk.hasAppExecutorConfig(eid, oapp, executorConfig)).resolves.toBeTruthy()
                    }
                ),
                { numRuns: 20 }
            )
        })

Summary: `ulnSdk.hasAppExecutorConfig` should return true when the fetched executor configuration matches the provided configuration.


it('should call onStart & onFailure when callback rejects', async () => {
                await fc.assert(
                    fc.asyncProperty(fc.array(fc.anything()), fc.anything(), async (args, error) => {
                        const fn = jest.fn().mockRejectedValue(error)
                        const onStart = jest.fn().mockImplementation((logger: Logger) => logger.debug(`onStart`))
                        const onError = jest.fn().mockImplementation((logger: Logger) => logger.debug(`onSuccess`))

                        await expect(withAsyncLogger(fn, { onStart, onError })(...args)).rejects.toBe(error)

                        expect(onStart).toHaveBeenCalledWith(expect.anything(), args)
                        expect(onError).toHaveBeenCalledWith(expect.anything(), args, error)
                        expect(onStart).toHaveBeenCalledBefore(onError)
                    })
                )
            })

Summary: When a callback function rejects, `onStart` should be called before `onError`, with each receiving the relevant arguments.


it('should flatten any arrays', () => {
            fc.assert(
                fc.property(
                    fc.array(fc.oneof(transactionArbitrary, nullableArbitrary, fc.array(transactionArbitrary))),
                    (transactions) => {
                        const flattened = flattenTransactions(transactions)

                        for (const transaction of flattened) {
                            expect(transaction).not.toBeInstanceOf(Array)
                        }
                    }
                )
            )
        })

Summary: The function `flattenTransactions` removes array nesting, ensuring that all items in the output are not arrays.


it('should parse successfully', () => {
                fc.assert(
                    fc.property(pointArbitrary, good, (point, config) => {
                        expect(schema.safeParse({ point, config }).success).toBeTruthy()
                    })
                )
            })

Summary: `schema.safeParse` should successfully parse objects containing `point` and `config`.


it('should not parse', () => {
                fc.assert(
                    fc.property(vectorArbitrary, bad, (vector, config) => {
                        expect(schema.safeParse({ vector, config }).success).toBeFalsy()
                    })
                )
            })

Summary: The test checks that the `schema.safeParse` function returns `false` when attempting to parse a given set of `vector` and `config` inputs.


it('should not work for negative bigints', () => {
            fc.assert(
                fc.property(fc.bigInt({ max: BigInt(-1) }), (value) => {
                    expect(() => UIntBigIntSchema.parse(value)).toThrow()
                })
            )
        })

Summary: `UIntBigIntSchema` throws an error when parsing negative bigints.


it('should normalize a nullish value to empty bytes', () => {
                fc.assert(
                    fc.property(evmEndpointArbitrary, nullishArbitrary, (eid, address) => {
                        const normalized = normalizePeer(address, eid)
                        const denormalized = denormalizePeer(normalized, eid)

                        expect(normalized).toEqual(new Uint8Array(32))
                        expect(isZero(normalized)).toBe(true)
                        expect(isZero(denormalized)).toBe(true)
                    })
                )
            })

Summary: Normalizing a nullish value results in a byte array of length 32 filled with zeros, and both the normalized and denormalized values should be zeroed arrays.


it('should serialize correctly when args are empty', () => {
            fc.assert(
                fc.property(reasonArbitrary, (reason) => {
                    expect(String(new CustomError(reason, []))).toBe(
                        `CustomError: Contract reverted with custom error. Error ${reason}()`
                    )
                })
            )
        })

Summary: `CustomError` with an empty argument list serializes to a specific string format incorporating the error reason.


it('should return the same address, just checksumed', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, (address) => {
                    expect(addChecksum(address)).toEqualCaseInsensitive(address)
                })
            )
        })

Summary: The `addChecksum` function should return the input address with the same value, but formatted with checksum.


it('should resolve with the first successful task', async () => {
            await fc.assert(
                fc.asyncProperty(valuesArbitrary, valueArbitrary, async (errors, value) => {
                    const tasks = errors.map((error) => jest.fn().mockRejectedValue(error))
                    const task = jest.fn().mockResolvedValue(value)

                    expect(await first([...tasks, task])).toBe(value)

                    // Make sure all the tasks got called
                    for (const factory of tasks) {
                        expect(factory).toHaveBeenCalledTimes(1)
                    }

                    expect(task).toHaveBeenCalledTimes(1)
                })
            )
        })

Summary: `first` resolves with the first successful task, ensuring all tasks are called once.


it('should reject with the original error if the onError callback throws', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, valueArbitrary, async (error, anotherError) => {
                    const task = jest.fn().mockRejectedValue(error)
                    const handleError = jest.fn().mockImplementation(() => {
                        throw anotherError
                    })

                    await expect(tapError(task, handleError)).rejects.toBe(error)
                    expect(handleError).toHaveBeenCalledOnce()
                    expect(handleError).toHaveBeenCalledExactlyOnceWith(error)
                })
            )
        })

Summary: `tapError` should reject with the original error if the `onError` callback throws another error.


it('should return false if the amount of attempts has been reached, the wrapped strategy value otherwise', () => {
                    fc.assert(
                        fc.property(numAttemptsArbitrary, (numAttempts) => {
                            // We'll create a simple wrapped strategy
                            const wrappedStrategy = (attempt: number) => [attempt]
                            const strategy = createSimpleRetryStrategy(numAttempts, wrappedStrategy)

                            // The first N attempts should return the return value of the wrapped strategy
                            for (let attempt = 1; attempt <= numAttempts; attempt++) {
                                expect(strategy(attempt, 'error', [0], [0])).toEqual(wrappedStrategy(attempt))
                            }

                            // The N+1th attempt should return false
                            expect(strategy(numAttempts + 1, 'error', [0], [0])).toBeFalsy()
                        })
                    )
                })

Summary: `createSimpleRetryStrategy` returns the wrapped strategy's value for attempts up to the limit and returns false once the limit is exceeded.


it('should instantiate from entries', () => {
                fc.assert(
                    fc.property(fc.array(fc.tuple(keyArbitrary, valueArbitrary)), (entries) => {
                        const map = new TestMap(entries)

                        // This looks like the simplest way of deduplicating the entries
                        //
                        // For the test below we want to make sure that we check that the map
                        // contains the last value belonging to a key - entries can contain
                        // duplicate keys so we need this helper data structure to store the last value set for a key
                        const valuesByHash = Object.fromEntries(entries.map(([key, value]) => [hash(key), value]))

                        for (const [key] of entries) {
                            const hashedKey = hash(key)
                            expect(hashedKey in valuesByHash).toBeTruthy()

                            const value = valuesByHash[hashedKey]

                            expect(map.has(key)).toBeTruthy()
                            expect(map.get(key)).toBe(value)
                        }
                    })
                )
            })

Summary: A `TestMap` instantiated from entries should map each key to its last corresponding value, handling duplicates accordingly.


it('should clear correctly', () => {
                fc.assert(
                    fc.property(fc.array(fc.tuple(keyArbitrary, valueArbitrary)), (entries) => {
                        const map = new TestMap(entries)

                        map.clear()

                        expect(map.size).toBe(0)
                        expect(Array.from(map.keys())).toEqual([])
                        expect(Array.from(map.values())).toEqual([])
                        expect(Array.from(map.entries())).toEqual([])
                    })
                )
            })

Summary: `TestMap` clears all entries correctly, resulting in a size of 0 and empty keys, values, and entries arrays.


it('should throw if passed an invalid message', () => {
            fc.assert(
                fc.property(fc.base64String(), (serialized) => {
                    expect(() => deserialize(serialized)).toThrow(/Failed to deserialize data./)
                })
            )
        })

Summary: Deserializing an invalid base64 string should throw an error indicating failure to deserialize the data.


UnitTest.test('ShadowDom - SelectorFind.descendant', () => {
  if (ShadowDom.isSupported()) {
    fc.assert(fc.property(htmlBlockTagName(), htmlInlineTagName(), fc.hexaString(), (block, inline, text) => {
      withShadowElement((ss) => {
        const id = 'theid';
        const inner = Element.fromHtml(`<${block}><p>hello<${inline} id="${id}">${text}</${inline}></p></${block}>`);
        Insert.append(ss, inner);

        const frog: Element<DomElement> = SelectorFind.descendant(ss, `#${id}`).getOrDie('Element not found');
        Assert.eq('textcontent', text, frog.dom().textContent);
      });
    }));
  }
})

Summary: `SelectorFind.descendant` should locate an element by ID within a shadow DOM, ensuring its text content matches the provided string.


UnitTest.test('KAssert.eqValue: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('should throw if numbers differ #1', () => {
      KAssert.eqValue('eq', a, Result.value(b));
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqValue('eq', a, Result.value(b), tNumber);
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqValue('eq', a, Result.value(b), tNumber, tBoom());
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('should throw if error #1', () => {
      KAssert.eqValue('eq', i, Result.error(s));
    });
    Assert.throws('should throw if error #2', () => {
      KAssert.eqValue('eq', i, Result.error(s), tBoom());
    });
    Assert.throws('should throw if error #3', () => {
      KAssert.eqValue('eq', i, Result.error(s), tBoom(), tBoom());
    });
  }));
})

Summary: `KAssert.eqValue` throws an error when comparing two different numbers or when comparing a number to an error result.


UnitTest.test('KAssert.eqResult: fail', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('value(a) != (value(!a)) #1', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b));
    });
    Assert.throws('value(a) != (value(!a)) #2', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b), tNumber);
    });
    Assert.throws('value(a) != (value(!a)) #2', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b), tNumber, tBoom());
    });
  }));

  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('error(a) != (error(!a)) #1', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b));
    });
    Assert.throws('error(a) != (error(!a)) #2', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b), tBoom());
    });
    Assert.throws('result(a) != (result(!a)) #2', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b), tBoom(), tNumber);
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('value != error #1', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s));
    });
    Assert.throws('value != error #2', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s), tBoom());
    });
    Assert.throws('value != error #3', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s), tBoom());
    });

    Assert.throws('error != value #1', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s));
    });
    Assert.throws('error != value #2', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s), tBoom());
    });
    Assert.throws('error != value #3', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s), tBoom(), tBoom());
    });
  }));
})

Summary: `KAssert.eqResult` throws an error when comparing unequal `Result` values or types, including different values, different errors, and mismatched value/error pairs.


UnitTest.test('KAssert.eqSome: success (reflexivity)', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    KAssert.eqSome('eq', i, Option.some(i));
    KAssert.eqSome('eq', i, Option.some(i), tNumber);
  }));
})

Summary: `KAssert.eqSome` verifies that an integer equals `Option.some` of the same integer, ensuring reflexivity with optional types.


UnitTest.test('KAssert.eqOption: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('some(i) != some(!i) #1', () => {
      KAssert.eqOption('eq', Option.some(a), Option.some(b));
    });
  }));
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('some(i) != some(!i) #2', () => {
      KAssert.eqOption('eq', Option.some(a), Option.some(b), tNumber);
    });
  }));
  fc.assert(fc.property(fc.integer(), (i) => {
    Assert.throws('none != some(i) #1', () => {
      KAssert.eqOption('eq', Option.none(), Option.some(i));
    });
    Assert.throws('none != some(i) #2', () => {
      KAssert.eqOption('eq', Option.none(), Option.some(i), tBoom());
    });
  }));
  fc.assert(fc.property(fc.integer(), (i) => {
    Assert.throws('some(i) != none #1', () => {
      KAssert.eqOption('eq', Option.some(i), Option.none());
    });
    Assert.throws('some(i) != none #2', () => {
      KAssert.eqOption('eq', Option.some(i), Option.none(), tBoom());
    });
  }));
})

Summary: `KAssert.eqOption` throws an error when comparing two different `Option` values, one being `None` and the other being `Some`, or when the `Some` values are different.


UnitTest.test('Checking some(x).exists(_ -> false) === false', () => {
  fc.assert(fc.property(arbOptionSome(fc.integer()), (opt) => !opt.exists(Fun.constant(false))));
})

Summary: `some(x).exists(_ -> false)` should always return false.


UnitTest.test('Option.isNone', () => {
  Assert.eq('none is none', true, Option.none().isNone());
  fc.assert(fc.property(fc.anything(), (x) => {
    Assert.eq('some is not none', false, Option.some(x).isNone());
  }));
})

Summary: `Option.isNone` returns true for `Option.none()` and false for any value wrapped in `Option.some()`.


UnitTest.test('Obj.isEmpty: single key/value', () => {
  fc.assert(fc.property(
    fc.string(),
    fc.json(),
    (k: string, v: any) => {
      const o = { [k]: v };
      Assert.eq('eq', false, Obj.isEmpty(o));
    }
  ));
})

Summary: Verifies that an object with a single key-value pair is not considered empty by `Obj.isEmpty`.


UnitTest.test('Error is thrown if not all arguments are supplied', () => {
  fc.assert(fc.property(arbAdt, fc.array(arbKeys, 1, 40), (subject, exclusions) => {
    const original = Arr.filter(allKeys, (k) => !Arr.contains(exclusions, k));

    try {
      const branches = Arr.mapToObject(original, () => Fun.identity);
      subject.match(branches);
      return false;
    } catch (err) {
      return err.message.indexOf('nothing') > -1;
    }
  }));
})

Summary: An error should be thrown when calling `match` on a subject with a branches object containing fewer keys than expected.


UnitTest.test('Arr.indexOf: find in middle of array', () => {
  fc.assert(fc.property(fc.array(fc.nat()), arbNegativeInteger(), fc.array(fc.nat()), (prefix, element, suffix) => {
    const arr = prefix.concat([ element ]).concat(suffix);
    Assert.eq(
      'Element should be found immediately after the prefix array',
      Option.some(prefix.length),
      Arr.indexOf(arr, element),
      tOption(tNumber)
    );
  }));
})

Summary: `Arr.indexOf` should return the index position of an element immediately following a prefix array within a concatenated array.


UnitTest.test('adt.nothing.match should pass [ ]', () => {
  fc.assert(fc.property(arbNothing, (subject) => {
    const contents = subject.match({
      nothing: record,
      unknown: Fun.die('should not be unknown'),
      exact: Fun.die('should not be exact')
    });
    Assert.eq('eq', [], contents);
  }));
})

Summary: The test checks that the `adt.nothing.match` function returns an empty array when matching with a `nothing` handler.


UnitTest.test('adt.unknown.match should be same as fold', () => {
  fc.assert(fc.property(arbUnknown, (subject) => {
    const matched = subject.match({
      nothing: Fun.die('should not be nothing'),
      unknown: record,
      exact: Fun.die('should not be exact')
    });

    const folded = subject.fold(Fun.die('should not be nothing'), record, Fun.die('should not be exact'));
    Assert.eq('eq', matched, folded);
  }));
})

Summary: `subject.match` produces the same result as `subject.fold` when handling the 'unknown' case.


UnitTest.test('Arr.sort: idempotency', () => {
  fc.assert(fc.property(
    fc.array(fc.nat()), (arr) => {
      Assert.eq('idempotency', Arr.sort(arr), Arr.sort(Arr.sort(arr)), tArray(tNumber));
    }
  ));
})

Summary: `Arr.sort` applied to an array should produce the same result when applied multiple times consecutively.


it('edits smpRate attribute only for valid inputs', async () => {
        await fc.assert(
          fc.asyncProperty(
            integer({ min: 0 }).map(num => `${num}`),
            async smpRate => {
              inputs[4].value = smpRate;
              await (<WizardTextField>inputs[4]).requestUpdate();
              expect(inputs[4].checkValidity()).to.be.true;
            }
          )
        );
      })

Summary: The `smpRate` attribute should only be edited for valid integer inputs that satisfy the validity checks.


it('does not allow to edit for invalid input', async () =>
          await fc.assert(
            fc.asyncProperty(invertedRegex(/^[0-7]$/), async testValue => {
              input!.value = testValue;
              await element.requestUpdate();
              expect(input!.checkValidity()).to.be.false;
            })
          ))

Summary: Editing is disallowed for input values that do not match the regex pattern /^[0-7]$/, ensuring `input.checkValidity()` returns false.


it('allow to edit for valid input', async () =>
          await fc.assert(
            fc.asyncProperty(regexString(/^\S*$/, 1), async testValue => {
              input!.value = testValue;
              await element.requestUpdate();
              expect(input!.checkValidity()).to.be.true;
            })
          ))

Summary: Editing should be allowed for input strings without whitespace.


UnitTest.test('some !== none, for any predicate', () => {
  fc.assert(fc.property(arbOptionSome(fc.integer()), (opt1) => {
    Assert.eq('eq', false, opt1.equals_(Optional.none(), boom));
  }));
})

Summary: `some` should not equal `none` when comparing an optional integer with an empty optional using any predicate.


UnitTest.test('Checking none.getOrThunk(_ -> v) === v', () => {
  fc.assert(fc.property(fc.func(fc.integer()), (thunk) => {
    Assert.eq('eq', thunk(), Optional.none<number>().getOrThunk(thunk));
  }));
})

Summary: `Optional.none<number>().getOrThunk(thunk)` returns the result of `thunk()`.


UnitTest.test('Optional.isSome: none is not some', () => {
  Assert.eq('none is not some', false, Optional.none().isSome());
  fc.assert(fc.property(fc.anything(), (x) => {
    Assert.eq('some is some', true, Optional.some(x).isSome());
  }));
})

Summary: `Optional.isSome` should return false for `Optional.none` and true for any `Optional.some(x)`.


UnitTest.test('Optional.getOr', () => {
  fc.assert(fc.property(fc.integer(), (x) => {
    Assert.eq('none', x, Optional.none().getOr(x));
    Assert.eq('none', x, Optional.none().getOrThunk(() => x));
  }));
  fc.assert(fc.property(fc.integer(), fc.integer(), (x, y) => {
    Assert.eq('some', x, Optional.some(x).getOr(y));
    Assert.eq('some', x, Optional.some(x).getOrThunk(Fun.die('boom')));
  }));
})

Summary: `Optional.getOr` returns the provided default value for `Optional.none` and the contained value for `Optional.some`.


UnitTest.test('Checking some(x).filter(_ -> true) === some(x)', () => {
  fc.assert(fc.property(fc.integer(), (x) => {
    Assert.eq('eq', true, tOptional().eq(
      some(x),
      some(x).filter(Fun.always)
    ));
  }));
})

Summary: The property should hold that applying a filter function returning true to a `some(x)` object results in the same `some(x)` object.


UnitTest.test('Check identity :: identity(a) === a', () => {
  fc.assert(fc.property(fc.json(), (json) => {
    Assert.eq('eq', json, Fun.identity(json));
  }));
})

Summary: The identity function should return the same value as the input for any JSON object.


UnitTest.test('Arr.find: finds a value in the array', () => {
  fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), fc.array(fc.integer()), (prefix, i, suffix) => {
    const arr = prefix.concat([ i ]).concat(suffix);
    const pred = (x) => x === i;
    const result = Arr.find(arr, pred);
    Assert.eq('Element found in array', Optional.some(i), result, tOptional(tNumber));
  }));
})

Summary: `Arr.find` locates and identifies a specified value within an array using a predicate function.


UnitTest.test('Arr.findMap does not find an element', () => {
  fc.assert(fc.property(
    fc.array(fc.nat()),
    fc.nat(),
    (arr, ret) => {
      Assert.eq('eq', Optional.none(), Arr.findMap(arr, (x) => Optionals.someIf(x === -1, ret)), tOptional());
    }
  ));
})

Summary: `Arr.findMap` should return `Optional.none()` if no element in the array meets the condition specified by the mapping function.


it('should always return boolean for any input', () => {
      fc.assert(
        fc.property(fc.anything(), input => {
          const result = isString(input);
          expect(typeof result).toBe('boolean');
        })
      );
    })

Summary: `isString` always returns a boolean for any input type.


UnitTest.test('KAssert.eqResult: fail', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('value(a) != (value(!a)) #1', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b));
    });
    Assert.throws('value(a) != (value(!a)) #2', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b), tNumber);
    });
    Assert.throws('value(a) != (value(!a)) #2', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b), tNumber, tBoom());
    });
  }));

  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('error(a) != (error(!a)) #1', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b));
    });
    Assert.throws('error(a) != (error(!a)) #2', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b), tBoom());
    });
    Assert.throws('result(a) != (result(!a)) #2', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b), tBoom(), tNumber);
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('value != error #1', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s));
    });
    Assert.throws('value != error #2', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s), tBoom());
    });
    Assert.throws('value != error #3', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s), tBoom());
    });

    Assert.throws('error != value #1', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s));
    });
    Assert.throws('error != value #2', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s), tBoom());
    });
    Assert.throws('error != value #3', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s), tBoom(), tBoom());
    });
  }));
})

Summary: `KAssert.eqResult` properly throws errors when comparing different `Result` values and errors, ensuring mismatched comparisons are detected in different scenarios with `Result.value` and `Result.error`.


it('should reject clearly invalid formats', () => {
      const invalidEmails = fc.oneof(
        fc.constant(''),
        fc.constant('notanemail'),
        fc.constant('@domain.com'),
        fc.constant('user@'),
        fc.string({ minLength: 1, maxLength: 5 }).filter(s => !s.includes('@'))
      );

      fc.assert(
        fc.property(invalidEmails, email => {
          return isValidEmail(email) === false;
        })
      );
    })

Summary: `isValidEmail` returns false for strings that do not conform to basic email format requirements.


it('should be monotonic with respect to weight and distance', () => {
      fc.assert(
        fc.property(shippingGenerator, ([weight, distance]) => {
          const baseShipping = calculateShipping(weight, distance);
          const heavierShipping = calculateShipping(weight * 2, distance);
          const fartherShipping = calculateShipping(weight, distance * 2);

          // More weight or distance should not decrease shipping cost
          return (
            heavierShipping >= baseShipping && fartherShipping >= baseShipping
          );
        })
      );
    })

Summary: The shipping cost should not decrease when either the weight is increased or the distance is increased.


it('should accept strong passwords', () => {
      const strongPassword = fc
        .string({ minLength: 8, maxLength: 20 })
        .map(s => s + 'A1'); // Ensure it has uppercase and number

      fc.assert(
        fc.property(strongPassword, password => {
          const result = validatePassword(password);
          return result.valid === true;
        })
      );
    })

Summary: `validatePassword` should return `valid: true` for passwords that are at least 8 characters long and contain both an uppercase letter and a number.


it('should have additional business logic validation', () => {
      fc.assert(
        fc.property(
          fc.tuple(generators.money(), generators.percentage()),
          ([amount, percentage]) => {
            const discount = calculateDiscount(amount, percentage);

            // Property: discount never exceeds original amount
            return discount <= amount;
          }
        )
      );
    })

Summary: The discount calculated with `calculateDiscount` should not exceed the original amount.


describe('helper/language', () => {
  after(async() => {
    await locale('en',);
  },);
  fc.assert(fc.property(fc.string(), (lang,) => {
    it(`no_tasks should return english string if set to ${ lang }`, async() => {
      if (
        lang.match(/^[a-z]{2}$/u,)
        && existsSync(process.cwd() + 'language/' + lang + '.yml',)
      ) {
        //skip
        return true;
      }
      await locale(lang,);
      expect(language('no_tasks',),).to.be.equal('Can\'t measure zero tasks.',);
      return true;
    },);
  },),);
  fc.assert(fc.property(fc.string(), (key,) => {
    it(`${ key } should return a string`, () => {
      expect(language(key as languageKey,),).to.be.a('string',);
    },);
  },),);
},)

Summary: When a locale is set to a non-existing or unsupported language, the `language` function should return the English string for 'no_tasks'; every input key should result in a string output from the `language` function.


describe('middlewares/max-time', () => {
  fc.assert(fc.property(fc.nat(), fc.nat(), (duration, max,) => {
    it(
      `throws only if the response is too slow(${ duration }<=${ max })`,
      () => {
        const response: Result = {
          id: 'example',
          validators: [],
          duration,
          maxDuration: max,
          response: {
            headers: {},
            cookies: {},
            uri: '',
            status: 0,
            body: '',
          },
        };
        if (duration > max) {
          expect(() => post(response,),)
            .to.throw(
              `The response time was above ${ max } ns`,
            );
          return;
        }
        expect(() => post(response,),).to.not.throw();
      },
    );
  },),);
},)

Summary: A response should only throw an error if its duration exceeds the maximum allowed time.


it('is always the size of the longest sequence', () => {
      fc.assert(
        fc.property(fc.array(fc.nat(), { minLength: 1 }), (lengths) => {
          const ranges = lengths.map((l) => Range(0, l));
          const first = ranges.shift();
          expectToBeDefined(first);
          const zipped = first.zipAll.apply(first, ranges);
          const longestLength = Math.max.apply(Math, lengths);
          expect(zipped.size).toBe(longestLength);
        })
      );
    })

Summary: The zipped sequence's size should equal the length of the longest input sequence.


it("matchX", () => {
        const f = Weather.matchX({
          Rain: "rained",
          [_]: "didn't rain",
        })

        fc.assert(
          fc.property(fc.integer(), n =>
            expect(f(Weather.mk.Rain(n))).toBe("rained"),
          ),
        )

        expect(f(Weather.mk.Sun)).toBe("didn't rain")
      })

Summary: The function `matchX` should return "rained" when matched with `Weather.mk.Rain` and "didn't rain" when matched with `Weather.mk.Sun`.


it("are reversible", () => {
      type Sum = Member<string, number>
      const Sum = create<Sum>()

      fc.assert(
        fc.property(fc.string(), fc.integer(), (k, v) => {
          const x = create<Sum>().mk[k](v)
          expect(deserialize(Sum)(serialize(x))).toEqual(x)
        }),
      )
    })

Summary: Serialized and deserialized `Sum` types should be identical to the original instance.


it('should reverse a string twice to get the original', () => {
    fc.assert(
      fc.property(fc.string(), (s) => {
        return reverseString(reverseString(s)) === s;
      })
    );
  })

Summary: Reversing a string twice should yield the original string.


it('returns the same result with the same config', () => {
  fc.assert(
    fc.property(domainGen.checkConfig(), domainGen.gens(), domainGen.fallibleFunc(), (config, gens, f) => {
      const checkResult0 = dev.check(dev.property(...gens, f), config);
      const checkResult1 = dev.check(dev.property(...gens, f), config);

      expect(checkResult0).toEqual(checkResult1);
    }),
  );
})

Summary: Calling `dev.check` with the same configuration and generators should return the same result consistently.


it('returns 0 when n = origin', () => {
    fc.assert(
      fc.property(
        genRangeParams(),
        LocalGen.scaleMode().filter((s) => s === 'constant'),
        ({ min, max, origin }, scaleMode) => {
          const range = Range.createFrom(nativeCalculator, min, max, origin, scaleMode);

          const distance = range.getProportionalDistance(origin);

          expect(distance).toEqual(0);
        },
      ),
    );
  })

Summary: `Range.getProportionalDistance` returns 0 when the input is equal to the defined origin.


it.each([
    { min: -10, max: 10, origin: 0, n: 5, expectedDistance: 50 },
    { min: -10, max: 10, origin: 0, n: -5, expectedDistance: 50 },
    { min: -5, max: 15, origin: 5, n: 10, expectedDistance: 50 },
    { min: -15, max: 5, origin: -5, n: -10, expectedDistance: 50 },
  ])('examples', ({ min, max, origin, n, expectedDistance }) => {
    fc.assert(
      fc.property(LocalGen.scaleMode(), (scaleMode) => {
        const range = Range.createFrom(
          nativeCalculator,
          nativeCalculator.loadIntegerUnchecked(min),
          nativeCalculator.loadIntegerUnchecked(max),
          nativeCalculator.loadIntegerUnchecked(origin),
          scaleMode,
        );

        const distance = range.getProportionalDistance(nativeCalculator.loadIntegerUnchecked(n));

        expect(distance).toEqual(expectedDistance);
      }),
    );
  })

Summary: The proportional distance calculated from a given number `n` within a specified range should equal the expected distance, regardless of scale mode.


it('returns 100 when n = max, and n > origin', () => {
    fc.assert(
      fc.property(
        genRangeParams().filter((x) => x.max > x.origin),
        LocalGen.scaleMode(),
        ({ min, max, origin }, scaleMode) => {
          const range = Range.createFrom(nativeCalculator, min, max, origin, scaleMode);

          const distance = range.getProportionalDistance(max);

          expect(distance).toEqual(100);
        },
      ),
    );
  })

Summary: When `n` equals `max` and is greater than `origin`, `Range.getProportionalDistance(max)` should return 100.


it('returns [origin,origin] when given size = 0', () => {
      fc.assert(
        fc.property(genRangeParams(), ({ min, max, origin }) => {
          const range = Range.createFrom(nativeCalculator, min, max, origin, 'linear');

          const bounds = range.getSizedBounds(nativeCalculator.zero);

          const expectedBounds: Bounds<number> = [origin, origin];
          expect(bounds).toMatchObject(expectedBounds);
        }),
      );
    })

Summary: When the size is 0, `Range.createFrom` should return bounds `[origin, origin]`.


it('allow to edit for valid input', async () =>
          await fc.assert(
            fc.asyncProperty(
              integer({ min: 1025, max: 65535 }).map(num => `${num}`),
              async testValue => {
                input!.value = testValue;
                await element.requestUpdate();
                expect(input!.checkValidity()).to.be.true;
              }
            )
          ))

Summary: Editing is allowed when the input value is a valid integer string between 1025 and 65535, as it passes validity checks.


test("search step invariant is maintained", () => {
    const arb = fc.array(fc.nat({ max: 32_768 }), {
      maxLength: 10,
    })

    fc.assert(
      fc.property(arb, sizes => {
        const arrs = sizes.map(arrayOfSize)
        const vecs = arrs.map(fromArray)
        const merged = concatMany(vecs)

        assertSearchStepInvariant(merged.root)
      }),
      { numRuns: 1000 }
    )
  })

Summary: The `assertSearchStepInvariant` function verifies that a merged RRB tree maintains its structural invariants after concatenating multiple arrays.


it('should calculate overlap correctly', () => {
      fc.assert(
        fc.property(
          fc.tuple(domainArbitraries.validTimeSlot, domainArbitraries.validTimeSlot),
          ([slot1, slot2]) => {
            // Property: Overlap calculation should be symmetric and accurate
            const calculateOverlap = (a: typeof slot1, b: typeof slot1): number => {
              const overlapStart = Math.max(a.start.getTime(), b.start.getTime());
              const overlapEnd = Math.min(a.end.getTime(), b.end.getTime());

              if (overlapEnd <= overlapStart) {
                return 0; // No overlap
              }

              return (overlapEnd - overlapStart) / (1000 * 60); // Minutes of overlap
            };

            const overlap1to2 = calculateOverlap(slot1, slot2);
            const overlap2to1 = calculateOverlap(slot2, slot1);

            // Symmetry property
            return Math.abs(overlap1to2 - overlap2to1) < 0.001;
          },
        ),
        getPropertyTestConfig('fast'),
      );
    })

Summary: The overlap calculation between two time slots should be symmetric and accurate.


it("combines an array of IOs into a single IO returning an array of the results", () =>
    fc.assert(
      fc.asyncProperty(fc.array(successfulIo), async (actions) => {
        const allResults = await Promise.all(actions.map((io) => io.run()));
        const sequenced = await IO.sequence(actions).run();
        return expect(sequenced).toEqual(allResults);
      })
    ))

Summary: Combining an array of IO operations results in a single IO that returns an array of their outcomes, matching the results of running them independently using `Promise.all`.


it('should calculate durations consistently', () => {
      fc.assert(
        fc.property(fc.tuple(fc.date(), fc.date()), ([date1, date2]) => {
          // Property: Duration calculation should be commutative in absolute terms
          const duration1to2 = Math.abs(date2.getTime() - date1.getTime());
          const duration2to1 = Math.abs(date1.getTime() - date2.getTime());

          return duration1to2 === duration2to1;
        }),
        getPropertyTestConfig('fast'),
      );
    })

Summary: Duration calculations should be commutative in absolute terms between two dates.


it('should validate curriculum codes correctly', () => {
      fc.assert(
        fc.property(domainArbitraries.curriculumCode, (code) => {
          // Property: Valid codes should pass validation
          return validateCurriculumCode(code) === true;
        }),
        getPropertyTestConfig('fast'),
      );
    })

Summary: Valid curriculum codes should pass the `validateCurriculumCode` function.


it('should test string properties', () => {
    fc.assert(
      fc.property(fc.string(), (s) => {
        // Property: String length is non-negative
        return s.length >= 0;
      }),
      { numRuns: 50 },
    );
  })

Summary: String length is always non-negative.


it('should test basic number properties', () => {
    fc.assert(
      fc.property(fc.integer(), (n) => {
        // Property: Adding zero to any number returns the same number
        return n + 0 === n;
      }),
      { numRuns: 100 },
    );
  })

Summary: Adding zero to an integer returns the same integer.


it('should ensure reading complexity progression', () => {
      fc.assert(
        fc.property(
          domainArbitraries.grade,
          fc.string({ minLength: 10, maxLength: 100 }),
          (grade, text) => {
            // Property: Reading materials should match grade reading levels
            const words = text.split(/\s+/);
            const averageWordLength =
              words.reduce((sum, word) => sum + word.length, 0) / words.length;
            const sentenceCount = text.split(/[.!?]+/).length;
            const averageSentenceLength = words.length / sentenceCount;

            // Simplified reading level calculation
            const readingComplexity = (averageWordLength + averageSentenceLength) / 2;

            if (grade <= 2) {
              return readingComplexity <= 6; // Simple texts
            } else if (grade <= 4) {
              return readingComplexity <= 8; // Intermediate texts
            } else if (grade <= 6) {
              return readingComplexity <= 10; // Grade-level texts
            } else {
              return readingComplexity <= 12; // More complex texts
            }
          },
        ),
        getPropertyTestConfig('fast'),
      );
    })

Summary: Reading materials are expected to align with specified grade levels based on calculated reading complexity.


it('should progress collaboration complexity with grade', () => {
      fc.assert(
        fc.property(domainArbitraries.grade, domainArbitraries.grouping, (grade, grouping) => {
          // Property: Collaboration complexity should match social development
          const appropriateGroupings = new Map([
            [1, ['whole class', 'pairs']],
            [2, ['whole class', 'pairs', 'small group']],
            [3, ['whole class', 'pairs', 'small group']],
            [4, ['whole class', 'pairs', 'small group', 'flexible grouping']],
            [5, ['whole class', 'pairs', 'small group', 'flexible grouping', 'individual']],
            [6, ['whole class', 'pairs', 'small group', 'flexible grouping', 'individual']],
            [7, ['whole class', 'pairs', 'small group', 'flexible grouping', 'individual']],
            [8, ['whole class', 'pairs', 'small group', 'flexible grouping', 'individual']],
          ]);

          const validGroupings = appropriateGroupings.get(grade) || ['whole class'];
          return validGroupings.includes(grouping);
        }),
        getPropertyTestConfig('fast'),
      );
    })

Summary: The collaboration complexity should reflect appropriate social development by ensuring the grouping matches valid options for each grade level.


it("should fail to cast neither foo nor bar", () => {
      expect.assertions(100);
      fc.assert(
        fc.property(fc.record({ baz: fc.boolean() }), (input) => {
          expect(castFooBar(input)).toStrictEqual({
            status: "failure",
            expected: "union",
            variants: [
              {
                status: "failure",
                expected: "object",
                properties: {
                  foo: {
                    status: "failure",
                    expected: "string",
                    actual: undefined
                  }
                },
                actual: input
              },
              {
                status: "failure",
                expected: "object",
                properties: {
                  bar: {
                    status: "failure",
                    expected: "number",
                    actual: undefined
                  }
                },
                actual: input
              }
            ]
          });
        })
      );
    })

Summary: `castFooBar` returns a failure status with expected types when input lacks required `foo` (string) and `bar` (number) properties.


it("should successfully cast strings to length", () => {
      expect.assertions(100);
      fc.assert(
        fc.property(fc.string(), (input) => {
          expect(castLength(input)).toStrictEqual({
            status: "success",
            value: input.length,
            values: []
          });
        })
      );
    })

Summary: `castLength` returns an object with status "success", the length of the input string as `value`, and an empty array as `values`.


it('should respect identity', () => {
      return fc.assert(
        fc.asyncProperty(arbExecutableQuery(fc.anything()), async (query) => {
          const result = await query.map(id).run(fakeClient);
          const expected = await query.run(fakeClient);
          expect(result).toStrictEqual(expected);
        })
      );
    })

Summary: Mapping an `ExecutableQuery` with the identity function should produce the same result as the original query when executed.


it("should successfully cast foo and bar", () => {
      expect.assertions(100);
      fc.assert(
        fc.property(
          fc.record({ foo: fc.string(), bar: fc.double() }),
          (input) => {
            const { foo, bar } = input;
            expect(castFooBar(input)).toStrictEqual({
              status: "success",
              value: [{ foo }, { bar }],
              values: []
            });
          }
        )
      );
    })

Summary: `castFooBar` should transform an object with properties `foo` and `bar` into a structured format with a "success" status and corresponding values.