it('should only return errors if the waiting fails', async () => {
                    await fc.assert(
                        fc.asyncProperty(fc.array(transactionArbitrary), async (transactions) => {
                            // We'll prepare some mock objects for this test
                            // to mock the transaction responses and receipts
                            const error = new Error('Failed transaction')
                            // Our unsuccessful wait will throw an error
                            const wait = jest.fn().mockRejectedValue(error)
                            const response: OmniTransactionResponse = {
                                transactionHash: '0x0',
                                wait,
                            }

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

                            // Now we send all the transactions to the flow and observe the output
                            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).toEqual([])
                            expect(errors).toContainAllValues(
                                transactions.map((transaction) => ({ transaction, error }))
                            )
                            expect(pending).toContainAllValues(transactions)

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

Summary: Ensures that when transactions fail during the waiting process, no transactions are marked as successful, errors are returned corresponding to each transaction, and all transactions are reported as pending.


unknown

it('should always strictly increase distance from target as we move in the stream', () =>
    fc.assert(
      fc.property(fc.maxSafeInteger(), fc.maxSafeInteger(), fc.boolean(), (current, target, tryAsap) => {
        // Arrange / Act
        const shrinks = [...shrinkInteger(current, target, tryAsap)];
        const absDiff = (a: number, b: number): bigint => {
          const result = BigInt(a) - BigInt(b);
          return result >= 0 ? result : -result;
        };

        // Assert
        for (let idx = 1; idx < shrinks.length; ++idx) {
          const previousDistance = absDiff(shrinks[idx - 1].value, target);
          const currentDistance = absDiff(shrinks[idx].value, target);
          expect(currentDistance).toBeGreaterThan(previousDistance);
        }
      }),
    ))

Summary: Each successive value in the `shrinkInteger` stream should have a greater distance from the target than the previous value.


it('should only return successes if waiting succeeds', async () => {
                    await fc.assert(
                        fc.asyncProperty(fc.array(transactionArbitrary), async (transactions) => {
                            const receipt = { transactionHash: '0x0' }

                            // Our successful wait will produce a receipt
                            const wait = jest.fn().mockResolvedValue(receipt)
                            const response: OmniTransactionResponse = {
                                transactionHash: '0x0',
                                wait,
                            }

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

                            // Now we send all the transactions to the flow and observe the output
                            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(
                                transactions.map((transaction) => ({ transaction, receipt }))
                            )
                            expect(errors).toEqual([])
                            expect(pending).toEqual([])

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

Summary: The function `signAndSendTransactions` processes an array of transactions, ensuring it only returns successful transactions if all waits succeed, while the errors and pending arrays remain empty.


it('should return padded values for address', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, (address) => {
                    const bytes = makeBytes32(address)

                    expect(bytes.length).toBe(66)
                    expect(BigInt(bytes)).toBe(BigInt(address))
                })
            )
        })

Summary: `makeBytes32` should convert an address to a 66-character padded string, preserving its numeric value.


it('should never include current in the stream', () =>
    fc.assert(
      fc.property(fc.bigInt(), fc.bigInt(), fc.boolean(), (current, target, tryAsap) => {
        // Arrange / Act
        const shrinks = [...shrinkBigInt(current, target, tryAsap)];
        const values = shrinks.map((v) => v.value);

        // Assert
        expect(values).not.toContain(current);
      }),
    ))

Summary: The `shrinkBigInt` function should generate a stream of values that does not include the current value.


it('should return true for an address and bytes', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, (address) => {
                    expect(areBytes32Equal(address, makeBytes32(address))).toBe(true)
                })
            )
        })

Summary: `areBytes32Equal` returns true when comparing an address with its converted bytes32 representation using `makeBytes32`.


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

                    expect(areBytes32Equal(bytes, address)).toBe(false)
                })
            )
        })

Summary: Returns false when comparing a zeroish value with a non-zeroish address using `areBytes32Equal`.


it('should never include target in the stream when try asap is not requested', () =>
    fc.assert(
      fc.property(fc.bigInt(), fc.bigInt(), (current, target) => {
        // Arrange / Act
        const shrinks = [...shrinkBigInt(current, target, false)];
        const values = shrinks.map((v) => v.value);

        // Assert
        expect(values).not.toContain(target);
      }),
    ))

Summary: The property ensures that the target value is not included in the output stream of `shrinkBigInt` when "try asap" is set to false.


it('should return false two non-matching UInt8Array instances', () => {
            fc.assert(
                fc.property(
                    fc.uint8Array({ minLength: 1, maxLength: 32 }),
                    fc.uint8Array({ minLength: 1, maxLength: 32 }),
                    (a, b) => {
                        // We need to filter out matching arrays
                        fc.pre(
                            // We walk over the first array and check that there is at least one non-matching element
                            //
                            // We default any missing (undefined) values in the second array to 0
                            // since any leading zeros are equal to undefined
                            a.some((v, i) => v !== b[i] || 0) ||
                                // And we do the same for the second array (since we don't know which one lis longer)
                                b.some((v, i) => v !== a[i] || 0)
                        )

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

Summary: `areBytes32Equal` returns false for two non-matching `UInt8Array` instances where at least one element differs or is undefined in one array.


it('should return false two a UInt8Array & non-matching hex string', () => {
            fc.assert(
                fc.property(
                    fc.uint8Array({ minLength: 1, maxLength: 32 }),
                    fc.uint8Array({ minLength: 1, maxLength: 32 }),
                    (a, b) => {
                        fc.pre(
                            // We walk over the first array and check that there is at least one non-matching element
                            //
                            // We default any missing (undefined) values in the second array to 0
                            // since any leading zeros are equal to undefined
                            a.some((v, i) => v !== b[i]) ||
                                // And we do the same for the second array (since we don't know which one lis longer)
                                b.some((v, i) => v !== a[i])
                        )

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

Summary: `areBytes32Equal` returns false when there is at least one non-matching element between a `UInt8Array` and a `makeBytes32` conversion of another `UInt8Array`.


it('should be able to revert any mapped date correctly even invalid ones', () => {
    fc.assert(
      fc.property(fc.date(), (d) => {
        // Arrange / Act
        const rev = timeToDateUnmapper(d);
        const revRev = timeToDateMapper(rev);

        // Assert
        expect(revRev.getTime()).toEqual(d.getTime());
      }),
    );
  })

Summary: `timeToDateUnmapper` followed by `timeToDateMapper` should revert a date to its original form, even for invalid dates.


it('should return true with a zero-only UInt8Array', () => {
            fc.assert(
                fc.property(fc.uint8Array({ min: 0, max: 0 }), (bytes) => {
                    expect(isZero(bytes)).toBe(true)
                })
            )
        })

Summary: `isZero` returns true when given a `UInt8Array` consisting only of zeros.


it('should be able to revert any mapped date correctly even invalid once', () => {
    fc.assert(
      fc.property(fc.date(), fc.integer({ min: -8640000000000000, max: 8640000000000001 }), (d, nanValue) => {
        // Arrange / Act
        const rev = timeToDateUnmapperWithNaN(nanValue)(d);
        const revRev = timeToDateMapperWithNaN(nanValue)(rev);

        // Assert
        if (d.getTime() === nanValue) {
          expect(rev).toBe(nanValue);
          expect(revRev.getTime()).toEqual(Number.NaN);
        } else {
          expect(revRev.getTime()).toEqual(d.getTime());
        }
      }),
    );
  })

Summary: Reversing a mapped date, whether valid or invalid, should accurately reflect the original date or return NaN if the original timestamp equals a specified NaN value.


it('should return a negative value for zero address and any other address', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, (address) => {
                    fc.pre(!isZero(address))

                    expect(compareBytes32Ascending(AddressZero, address)).toBeLessThan(0)
                    expect(compareBytes32Ascending(AddressZero, makeBytes32(address))).toBeLessThan(0)
                    expect(compareBytes32Ascending(makeBytes32(AddressZero), address)).toBeLessThan(0)
                    expect(compareBytes32Ascending(makeBytes32(AddressZero), makeBytes32(address))).toBeLessThan(0)
                })
            )
        })

Summary: Comparison of `AddressZero` with any other address should return a negative value using `compareBytes32Ascending` function.


it('should return a positive value for zero address and any other address', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, (address) => {
                    fc.pre(!isZero(address))

                    expect(compareBytes32Ascending(address, AddressZero)).toBeGreaterThan(0)
                    expect(compareBytes32Ascending(makeBytes32(address), AddressZero)).toBeGreaterThan(0)
                    expect(compareBytes32Ascending(address, makeBytes32(AddressZero))).toBeGreaterThan(0)
                    expect(compareBytes32Ascending(makeBytes32(address), makeBytes32(AddressZero))).toBeGreaterThan(0)
                })
            )
        })

Summary: The comparison function `compareBytes32Ascending` should return a positive value when comparing a non-zero address with the zero address.


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

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

Summary: When one address comes after another address (case-insensitive), `compareBytes32Ascending` returns a positive number for both original and converted addresses.


it('should work goddammit', async () => {
            await fc.assert(
                fc.asyncProperty(portArbitrary, anvilOptionsRecordArbitrary, async (port, anvilOptions) => {
                    const simulationConfig = resolveSimulationConfig({ port }, hre.config)
                    const spec = serializeDockerComposeSpec(createSimulationComposeSpec(simulationConfig, anvilOptions))

                    await writeFile(SPEC_FILE_PATH, spec)

                    const result = validateSpec()

                    expect(result.stderr.toString('utf8')).toBe('')
                    expect(result.status).toBe(0)
                }),
                { numRuns: 20 }
            )
        })

Summary: The property validates that a Docker Compose specification, generated from given simulation configurations and options, writes correctly without errors and is valid according to `validateSpec`.


it('should call the contractFactory if contract is not an OmniPoint', async () => {
            await fc.assert(
                fc.asyncProperty(pointHardhatArbitrary, evmAddressArbitrary, async (point, address) => {
                    fc.pre(!isOmniPoint(point))

                    const contract = new Contract(address, [])
                    const contractFactory = jest
                        .fn()
                        .mockImplementation(async (point: OmniPointHardhat) => ({ eid: point.eid, contract }))
                    const transformer = createOmniPointHardhatTransformer(contractFactory)

                    const transformed = await transformer(point)

                    expect(transformed).toEqual({ ...point, address })
                    expect(contractFactory).toHaveBeenCalledTimes(1)
                    expect(contractFactory).toHaveBeenCalledWith(point)
                })
            )
        })

Summary: Call `contractFactory` when the given `point` is not an `OmniPoint`.


it('should add the contractName if point is not an OmniPoint', async () => {
            await fc.assert(
                fc.asyncProperty(pointHardhatArbitrary, evmAddressArbitrary, async (point, address) => {
                    fc.pre(!isOmniPoint(point))

                    const contract = new Contract(address, [])
                    const contractFactory = jest
                        .fn()
                        .mockImplementation(async (point: OmniPointHardhat) => ({ eid: point.eid, contract }))
                    const transformer = createOmniPointHardhatTransformer(contractFactory)

                    const transformed = await transformer(point)

                    expect(transformed).toEqual({ eid: point.eid, address, contractName: point.contractName })
                    expect(contractFactory).toHaveBeenCalledTimes(1)
                    expect(contractFactory).toHaveBeenCalledWith(point)
                })
            )
        })

Summary: Adds a `contractName` to a point if it is not already an `OmniPoint`, using a transformer function that calls a mocked contract factory.


it('should call the pointTransformer on the point', async () => {
            await fc.assert(
                fc.asyncProperty(
                    pointHardhatArbitrary,
                    evmAddressArbitrary,
                    fc.anything(),
                    async (point, address, config) => {
                        fc.pre(!isOmniPoint(point))

                        const pointTransformer = jest.fn().mockImplementation(async (point: OmniPointHardhat) => ({
                            eid: point.eid,
                            address: address,
                        }))
                        const transformer = createOmniNodeHardhatTransformer(pointTransformer)

                        const node = await transformer({ contract: point, config })

                        expect(node).toEqual({ point: { eid: point.eid, address }, config })
                        expect(pointTransformer).toHaveBeenCalledTimes(1)
                        expect(pointTransformer).toHaveBeenCalledWith(point)
                    }
                )
            )
        })

Summary: The `pointTransformer` function should be called once with a specified `point` and should transform it correctly into a node with `eid` and `address`, adhering to the expected output.


it('should call the pointTransformer on from and to', async () => {
            await fc.assert(
                fc.asyncProperty(
                    pointHardhatArbitrary,
                    pointHardhatArbitrary,
                    evmAddressArbitrary,
                    fc.anything(),
                    async (from, to, address, config) => {
                        const pointTransformer = jest.fn().mockImplementation(async (point: OmniPointHardhat) => ({
                            eid: point.eid,
                            address,
                        }))
                        const transformer = createOmniEdgeHardhatTransformer(pointTransformer)

                        const edge = await transformer({ from, to, config })

                        expect(edge).toEqual({
                            vector: { from: { eid: from.eid, address }, to: { eid: to.eid, address } },
                            config,
                        })
                        expect(pointTransformer).toHaveBeenCalledTimes(2)
                        expect(pointTransformer).toHaveBeenCalledWith(from)
                        expect(pointTransformer).toHaveBeenCalledWith(to)
                    }
                )
            )
        })

Summary: The `pointTransformer` should be called twice—once on the `from` point and once on the `to` point—resulting in an edge object with transformed addresses.


it("should always return notice", async () => {
                const file = "foo.html";
                const root = await tempFs.create({ [file]: "" });
                const wrapper = new MarkuplintWrapper(
                    {
                        level: Levels.INFO,
                        fix: false,
                        root,
                        files: [file],
                    },
                    { rules: { "attr-value-quotes": true } },
                );

                await fc.assert(
                    fc.asyncProperty(
                        fc.string({ unit: "binary" }),
                        async (content) => {
                            await fs.writeFile(file, content);

                            const notices = await wrapper.lint(file);
                            for (const notice of notices) {
                                assert.equal(notice.file, file);
                                assert.equal(notice.linter, "markuplint");
                            }
                        },
                    ),
                );
            })

Summary: `MarkuplintWrapper` always returns notices that specify the file as "foo.html" and the linter as "markuplint" when checking binary string content.


it('should call the nodeTransformer and edgeTransformer for every node and edge and return the result', async () => {
            await fc.assert(
                fc.asyncProperty(
                    fc.array(nodeHardhatArbitrary),
                    fc.array(edgeHardhatArbitrary),
                    async (contracts, connections) => {
                        const nodeTransformer = jest.fn().mockImplementation(async (node) => ({ node }))
                        const edgeTransformer = jest.fn().mockImplementation(async (edge) => ({ edge }))
                        const transformer = createOmniGraphHardhatTransformer(nodeTransformer, edgeTransformer)

                        const graph = await transformer({ contracts, connections })

                        expect(graph.contracts).toEqual(contracts.map((node) => ({ node })))
                        expect(graph.connections).toEqual(connections.map((edge) => ({ edge })))
                    }
                )
            )
        })

Summary: `nodeTransformer` and `edgeTransformer` are applied to each node and edge, respectively, and the results match the expected transformed output.


it('should support sequential applicative', async () => {
            await fc.assert(
                fc.asyncProperty(
                    fc.array(nodeHardhatArbitrary),
                    fc.array(edgeHardhatArbitrary),
                    async (contracts, connections) => {
                        const nodeTransformer = jest.fn().mockImplementation(async (node) => ({ node }))
                        const edgeTransformer = jest.fn().mockImplementation(async (edge) => ({ edge }))
                        const transformerSequential = createOmniGraphHardhatTransformer(
                            nodeTransformer,
                            edgeTransformer,
                            sequence
                        )
                        const transformerParallel = createOmniGraphHardhatTransformer(
                            nodeTransformer,
                            edgeTransformer,
                            parallel
                        )

                        const graphSequential = await transformerSequential({ contracts, connections })
                        const graphParallel = await transformerParallel({ contracts, connections })

                        expect(graphSequential).toEqual(graphParallel)
                    }
                )
            )
        })

Summary: The transformation of graph data with sequential application should produce the same result as parallel application when using the `createOmniGraphHardhatTransformer`.


it('should just work', () => {
            fc.assert(
                fc.property(endpointArbitrary, evmAddressArbitrary, (eid, address) => {
                    const omniDeployment: OmniDeployment = { eid, deployment: { address } as Deployment }

                    expect(omniDeploymentToPoint(omniDeployment)).toEqual({ eid, address })
                })
            )
        })

Summary: Converting an `OmniDeployment` to a point should correctly map `eid` and `address` to the expected output object.


it('should just work', () => {
            fc.assert(
                fc.property(endpointArbitrary, evmAddressArbitrary, (eid, address) => {
                    const omniDeployment: OmniDeployment = { eid, deployment: { address, abi: [] } as Deployment }
                    const omniContract = omniDeploymentToContract(omniDeployment)

                    // chai is not great with deep equality on class instances so we need to compare the result property by property
                    expect(omniContract.eid).toBe(eid)
                    expect(omniContract.contract.address).toBe(address)
                    expect(omniContract.contract.interface.fragments).toEqual([])
                })
            )
        })

Summary: The property ensures that converting an `OmniDeployment` to a contract correctly assigns the `eid`, `address`, and an empty `abi` to the resulting `omniContract` instance.


it('should fall back on getting the artifact based on the deployments if artifact not found', async () => {
                await fc.assert(
                    fc.asyncProperty(evmAddressArbitrary, async (address) => {
                        const environmentFactory = createGetHreByEid(hre)
                        const contractFactory = createContractFactory(environmentFactory)

                        const env = await environmentFactory(EndpointId.ETHEREUM_V2_MAINNET)
                        jest.spyOn(env.deployments, 'getArtifact').mockRejectedValue(new Error(`oh no`))
                        jest.spyOn(env.deployments, 'getDeploymentsFromAddress').mockResolvedValue([
                            {
                                address,
                                abi: [],
                            },
                        ])

                        // Then check whether the factory will get it for us
                        const deployment = await contractFactory({
                            eid: EndpointId.ETHEREUM_V2_MAINNET,
                            address,
                            contractName: 'MyContract',
                        })

                        expect(deployment).toEqual({
                            eid: EndpointId.ETHEREUM_V2_MAINNET,
                            contract: expect.any(Contract),
                        })
                        expect(env.deployments.getArtifact).toHaveBeenCalledWith('MyContract')
                        expect(env.deployments.getDeploymentsFromAddress).toHaveBeenCalledWith(address)
                    })
                )
            })

Summary: If the artifact is not found via `getArtifact`, the test ensures retrieval from `getDeploymentsFromAddress` based on given deployments.


it('should reject when eid does not exist', async () => {
                await fc.assert(
                    fc.asyncProperty(evmAddressArbitrary, async (address) => {
                        const contractFactory = createContractFactory()

                        await expect(() =>
                            contractFactory({ eid: EndpointId.CANTO_TESTNET, address })
                        ).rejects.toBeTruthy()
                    })
                )
            })

Summary: Rejects contract creation when `eid` does not exist for the given address.


it('should reject when contract has not been deployed', async () => {
                await fc.assert(
                    fc.asyncProperty(evmAddressArbitrary, async (address) => {
                        const contractFactory = createContractFactory()

                        await expect(() =>
                            contractFactory({ eid: EndpointId.ETHEREUM_V2_MAINNET, address })
                        ).rejects.toThrow(/Could not find a deployment for address/)
                    })
                )
            })

Summary: The test checks that attempting to create a contract factory with an address of a non-deployed contract results in a rejection with the specific error message "Could not find a deployment for address."


it('should resolve when there is only one deployment for the contract', async () => {
                await fc.assert(
                    fc.asyncProperty(evmAddressArbitrary, async (address) => {
                        const environmentFactory = createGetHreByEid(hre)
                        const contractFactory = createContractFactory(environmentFactory)

                        const env = await environmentFactory(EndpointId.ETHEREUM_V2_MAINNET)
                        jest.spyOn(env.deployments, 'getDeploymentsFromAddress').mockResolvedValue([
                            {
                                address,
                                abi: [],
                            },
                        ])

                        // Then check whether the factory will get it for us
                        const deployment = await contractFactory({
                            eid: EndpointId.ETHEREUM_V2_MAINNET,
                            address,
                        })

                        expect(deployment).toEqual({
                            eid: EndpointId.ETHEREUM_V2_MAINNET,
                            contract: expect.any(Contract),
                        })
                        expect(env.deployments.getDeploymentsFromAddress).toHaveBeenCalledWith(address)
                    })
                )
            })

Summary: The test checks that when there is only one deployment for a contract, the contract factory successfully resolves the deployment using the specified environment and address.


it('should merge ABIs when there are multiple deployments with the same address (proxy deployments)', async () => {
                await fc.assert(
                    fc.asyncProperty(evmAddressArbitrary, async (address) => {
                        const environmentFactory = createGetHreByEid(hre)
                        const contractFactory = createContractFactory(environmentFactory)

                        const env = await environmentFactory(EndpointId.ETHEREUM_V2_MAINNET)
                        jest.spyOn(env.deployments, 'getDeploymentsFromAddress').mockResolvedValue([
                            {
                                address,
                                abi: [
                                    { name: 'implementation', outputs: [], stateMutability: 'view', type: 'function' },
                                ],
                            },
                            {
                                address,
                                abi: [
                                    { name: 'contractMethod', outputs: [], stateMutability: 'view', type: 'function' },
                                ],
                            },
                        ])

                        // Then check whether the factory will get it for us
                        const omniContract = await contractFactory({
                            eid: EndpointId.ETHEREUM_V2_MAINNET,
                            address,
                        })

                        expect(omniContract).toEqual({
                            eid: EndpointId.ETHEREUM_V2_MAINNET,
                            contract: expect.any(Contract),
                        })
                        expect(omniContract.contract.implementation).toBeInstanceOf(Function)
                        expect(omniContract.contract.contractMethod).toBeInstanceOf(Function)
                    })
                )
            })

Summary: Merging multiple ABIs into a single contract when multiple deployments share the same address.


it('should reject if contractFactory rejects', async () => {
            await fc.assert(
                fc.asyncProperty(pointArbitrary, async (point) => {
                    const error = new Error()
                    const contractFactory = jest.fn().mockRejectedValue(error)
                    const connectedContractFactory = createConnectedContractFactory(contractFactory)

                    await expect(connectedContractFactory(point)).rejects.toBe(error)
                })
            )
        })

Summary: The function `createConnectedContractFactory` should reject with an error if `contractFactory` is mocked to reject.


it('should return a connected contract', async () => {
            await fc.assert(
                fc.asyncProperty(pointArbitrary, async (point) => {
                    const contract = new Contract(makeZeroAddress(undefined), [])
                    const provider = new JsonRpcProvider()
                    const contractFactory = jest.fn().mockResolvedValue({ eid: point.eid, contract })
                    const providerFactory = jest.fn().mockResolvedValue(provider)
                    const connectedContractFactory = createConnectedContractFactory(contractFactory, providerFactory)

                    const connectedOmniContract = await connectedContractFactory(point)

                    expect(connectedOmniContract.eid).toBe(point.eid)
                    expect(connectedOmniContract.contract).not.toBe(contract)
                    expect(connectedOmniContract.contract).toBeInstanceOf(Contract)
                    expect(connectedOmniContract.contract.provider).toBe(provider)
                })
            )
        })

Summary: A connected contract should be created with the correct `eid`, using a new `Contract` instance linked to the correct `provider`.


it('should not throw if called with an array of networks defined in hardhat config', () => {
            fc.assert(
                fc.property(definedNetworksArrayArbitrary, (networks) => {
                    expect(assertDefinedNetworks(networks)).toBe(networks)
                })
            )
        })

Summary: `assertDefinedNetworks` should return the networks array when called with an array of networks defined in the hardhat configuration.


it('should not throw if called with a Set of networks defined in hardhat config', () => {
            fc.assert(
                fc.property(definedNetworksSetArbitrary, (networks) => {
                    expect(assertDefinedNetworks(networks)).toBe(networks)
                })
            )
        })

Summary: The function `assertDefinedNetworks` should return the input set of networks when called with networks defined in the hardhat configuration.


it('should throw if called if a network has not been defined in an array', () => {
            fc.assert(
                fc.property(definedNetworksArrayArbitrary, fc.string(), (networks, network) => {
                    fc.pre(!definedNetworks.includes(network))

                    expect(() => assertDefinedNetworks([...networks, network])).toThrow()
                })
            )
        })

Summary: `assertDefinedNetworks` throws an error if it is called with a network not included in the defined networks array.


it('should throw if called if a network has not been defined in a Set', () => {
            fc.assert(
                fc.property(definedNetworksSetArbitrary, fc.string(), (networks, network) => {
                    fc.pre(!definedNetworks.includes(network))

                    expect(() => assertDefinedNetworks(networks.add(network))).toThrow()
                })
            )
        })

Summary: The test checks that calling `assertDefinedNetworks` throws an error when attempting to add a network that is not included in `definedNetworks`.


it('should throw if negative index is passed', () => {
            fc.assert(
                fc.property(fc.integer({ max: -1 }), (index) => {
                    expect(() => signer.parse('signer', String(index))).toThrow()
                })
            )
        })

Summary: Passing a negative index to the `signer.parse` function should throw an error.


it('should return the address if valid address is passed', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, (address) => {
                    expect(signer.parse('signer', address)).toEqual({ type: 'address', address })
                })
            )
        })

Summary: The test checks that the `signer.parse` function returns an object with a valid address when a valid address is passed.


it('should return the index if non-negative index is passed', () => {
            fc.assert(
                fc.property(fc.integer({ min: 0 }), (index) => {
                    expect(signer.parse('signer', String(index))).toEqual({ type: 'index', index })
                })
            )
        })

Summary: A non-negative integer index parsed by `signer.parse` should return an object with the same index and type 'index'.


it('should parse all valid endpoint IDs', () => {
            fc.assert(
                fc.property(endpointArbitrary, (eid) => {
                    expect(types.eid.parse('eid', String(eid))).toEqual(eid)
                })
            )
        })

Summary: Parsing should correctly convert valid endpoint IDs using `types.eid.parse`.


it("should convert principal", () => {
    fc.assert(
      fc.property(generators, (expected) => {
        const principal = publicKeyToAddress(expected.hex);

        const resultStandard = stringToCV(principal, "principal");
        expect(resultStandard.type).toEqual("principal");
        expect(resultStandard.value).toBePrincipal(principal);

        const contract = `${principal}.${expected.name}`;
        const resultContract = stringToCV(contract, "principal");
        expect(resultContract.type).toEqual("principal");
        expect(resultContract.value).toStrictEqual(principalCV(contract));
      })
    );
  })

Summary: Converting a principal or contract string representation using `stringToCV` should produce a CV of type "principal" matching the expected principal or contract.


it("should parse with simple annotations", () => {
    fc.assert(fc.property(generators, (expected) => {
      const result = extractTestAnnotations(
        `
;; @name ${expected.name}
(define-public (${expected.functionName})
    ;; @mine-before is ignored here
    (ok true))
`
      );
      expect(result[expected.functionName]).toEqual({
        name: expected.name,
      });
    }));
  })

Summary: Parsing should correctly identify and extract `@name` annotations associated with function names.


it("should parse with all annotations", () => {
    fc.assert(fc.property(fc.uniqueArray(generators), (array) => {
      const contractSource = array
        .map((expected) =>
          `
;; @name ${expected.name}
;; @description ${expected.description}
;; @mine-before ${expected.mineBefore}
;; @caller ${expected.caller}
(define-public (${expected.functionName})
    (ok true))
`
        )
        .join();

      const result = extractTestAnnotations(contractSource);

      array.forEach(expected => {
        expect(result[expected.functionName]).toEqual({
          name: expected.name,
          description: expected.description,
          "mine-before": expected.mineBefore,
          caller: expected.caller,
        });
      });
    }));
  })

Summary: Parsing extracts expected annotations from contract source strings containing name, description, mine-before, and caller fields for each function.


it("should convert string to cv", () => {
    fc.assert(
      fc.property(fc.string(), (someStr) => {
        const result = stringToCV(someStr, { "string-utf8": { length: 100 } });
        expect(result).toEqual({
          type: "string",
          value: stringUtf8CV(someStr),
        });
      })
    );
  })

Summary: Converting a string to CV results in an object with a type of "string" and a value from `stringUtf8CV` of the original string.


it("should convert uint to cv", () => {
    fc.assert(
      fc.property(uint128, (someUInt) => {
        const result = stringToCV(`u${someUInt}`, "uint128");
        expect(result).toEqual({
          type: "uint",
          value: uintCV(someUInt),
        });
      })
    );
  })

Summary: The function `stringToCV` should correctly convert a string representation of a uint into a cv with the type "uint" and the corresponding value.


it("should convert tuple to cv", () => {
    fc.assert(
      fc.property(
        fc.record({
          key: fc.stringMatching(/^[a-zA-Z][a-zA-Z0-9]{0,9}$/),
          val: int128,
        }),
        (r) => {
          const result = stringToCV(`{${r.key}: ${r.val}}`, {
            tuple: [{ name: r.key, type: "int128" }],
          });
          expect(result).toEqual({
            type: "tuple",
            value: {
              value: { [r.key]: intCV(r.val) },
              type: ClarityType.Tuple,
            },
          });
        }
      )
    );
  })

Summary: A tuple string representation is converted to a Clarity Value (CV) tuple with an `int128` value using `stringToCV`.


it('Can get an age group given a numerical age', () => {
		fc.assert(
			fc.property(
				fc.float(),
				(age: number) => typeof convertAgeToGroup(age) === 'string'
			)
		);

		// @ts-ignore
		expect(convertAgeToGroup(undefined)).toEqual('n/a');
		expect(convertAgeToGroup(-1)).toEqual('n/a');
	})

Summary: `convertAgeToGroup` should return a string for any numerical age input, and "n/a" for undefined or negative age inputs.


it('Creates a cauchy variable', () => {
		fc.assert(
			fc.property(
				fc.float(),
				fc.float({ next: false, min: 0.01 }),
				(a, b) => {
					const rv = createCauchy('testCauchy', a, b);

					return (
						rv._.dist === 'cauchy' &&
						rv.scale === b &&
						rv.location === a
					);
				}
			)
		);
	})

Summary: Creating a Cauchy variable correctly assigns the distribution type as 'cauchy', and sets the location and scale parameters according to the inputs.


it("should filter duplicates", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          let registry = makeScopedRegistry("test", someRegistryUrl);

          registry = addScope(registry, packumentName);
          registry = addScope(registry, packumentName);

          expect(registry.scopes).toEqual([packumentName]);
        })
      );
    })

Summary: The test checks that adding the same scope twice to a registry results in no duplicates, ensuring the `scopes` list contains only one instance of the `packumentName`.


it("should have scope that was added", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          let registry = makeScopedRegistry("test", someRegistryUrl);

          registry = addScope(registry, packumentName);

          expect(hasScope(registry, packumentName)).toBeTruthy();
        })
      );
    })

Summary: A scope added to a registry should be confirmed as present using `hasScope`.


it("should not have scope that was not added", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          const registry = makeScopedRegistry("test", someRegistryUrl);

          expect(hasScope(registry, packumentName)).toBeFalsy();
        })
      );
    })

Summary: Verifies that a newly created scoped registry does not contain any scope that was not explicitly added.


it("should not have scope after removing it", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          let registry = makeScopedRegistry("test", someRegistryUrl, [
            packumentName,
          ]);

          registry = removeScope(registry, packumentName);

          expect(hasScope(registry, packumentName)).toBeFalsy();
        })
      );
    })

Summary: Removing a scope from a registry should result in `hasScope` returning false for that scope.


it("should remove duplicate scopes", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          let registry = makeScopedRegistry("test", someRegistryUrl, [
            packumentName,
            packumentName,
          ]);

          registry = removeScope(registry, packumentName);

          expect(registry.scopes).toHaveLength(0);
        })
      );
    })

Summary: Ensures duplicate scopes are removed from a scoped registry, resulting in no remaining scopes.


it("should add dependency when adding first time", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          let manifest = emptyProjectManifest;

          manifest = setDependency(
            manifest,
            packumentName,
            SemanticVersion.parse("1.2.3")
          );

          expect(manifest.dependencies).toEqual({ [packumentName]: "1.2.3" });
        })
      );
    })

Summary: Adding a dependency for the first time results in the dependency appearing in the manifest with the specified version.


it("should overwrite dependency when adding second time", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          let manifest = emptyProjectManifest;

          manifest = setDependency(
            manifest,
            packumentName,
            SemanticVersion.parse("1.2.3")
          );
          manifest = setDependency(
            manifest,
            packumentName,
            SemanticVersion.parse("2.3.4")
          );

          expect(manifest.dependencies).toEqual({ [packumentName]: "2.3.4" });
        })
      );
    })

Summary: Adding a dependency with the same name updates the version in the project manifest to the latest specified version.


it("should remove existing dependency", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          let manifest = emptyProjectManifest;

          manifest = setDependency(
            manifest,
            packumentName,
            SemanticVersion.parse("1.2.3")
          );
          manifest = removeDependency(manifest, packumentName);

          expect(manifest.dependencies).toEqual({});
        })
      );
    })

Summary: Removing a dependency should result in an empty dependencies object in the manifest.


it("should remove scope from all scoped registries", () => {
      fc.assert(
        fc.property(arbDomainName, arbDomainName, (scope1, scope2) => {
          const original: UnityProjectManifest = {
            dependencies: {},
            scopedRegistries: [
              {
                name: "Scope A",
                url: RegistryUrl.parse("https://a.com"),
                scopes: [scope1],
              },
              {
                name: "Scope B",
                url: RegistryUrl.parse("https://b.com"),
                scopes: [scope1, scope2],
              },
            ],
          };

          const actual = removeScopeFromAllScopedRegistries(original, scope1);

          expect(actual).toEqual<UnityProjectManifest>({
            dependencies: {},
            scopedRegistries: [
              {
                name: "Scope A",
                url: RegistryUrl.parse("https://a.com"),
                scopes: [],
              },
              {
                name: "Scope B",
                url: RegistryUrl.parse("https://b.com"),
                scopes: [scope2],
              },
            ],
          });
        })
      );
    })

Summary: The function `removeScopeFromAllScopedRegistries` should remove a specified scope from all `scopedRegistries` in a `UnityProjectManifest`.


it("should leave non-empty scoped registries", () => {
      fc.assert(
        fc.property(arbDomainName, (scope) => {
          const original: UnityProjectManifest = {
            dependencies: {},
            scopedRegistries: [
              {
                name: "Scope A",
                url: RegistryUrl.parse("https://a.com"),
                scopes: [scope],
              },
            ],
          };

          const actual = removeEmptyScopedRegistries(original);

          expect(actual).toEqual<UnityProjectManifest>(original);
        })
      );
    })

Summary: The function `removeEmptyScopedRegistries` should not alter a `UnityProjectManifest` if it contains non-empty scoped registries.


it('should have no effect for undefined "testables"', () => {
      fc.assert(
        fc.property(arbDomainName, (packageName) => {
          const original: UnityProjectManifest = { dependencies: {} };

          const actual = removeTestable(original, packageName);

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

Summary: Removing a package in `removeTestable` should have no effect if "testables" is undefined in `original`.


it("should remove testable", () => {
      fc.assert(
        fc.property(arbDomainName, (packageName) => {
          const original: UnityProjectManifest = {
            dependencies: {},
            testables: [packageName],
          };

          const actual = removeTestable(original, packageName);

          expect(actual).toEqual<UnityProjectManifest>({
            dependencies: {},
            testables: [],
          });
        })
      );
    })

Summary: `removeTestable` removes a specified package name from the `testables` list in a `UnityProjectManifest`.


it("should be ok for http", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          const input = `http://github.com/user/${{ packumentName }}`;
          expect(isZod(input, PackageUrl)).toBeTruthy();
        })
      );
    })

Summary: Validates that a URL with the HTTP scheme and a given domain name is considered valid by the `isZod` function with the `PackageUrl` object.


it("should be ok for https", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          const input = `https://github.com/user/${{ packumentName }}`;
          expect(isZod(input, PackageUrl)).toBeTruthy();
        })
      );
    })

Summary: URLs with the structure `https://github.com/user/{packumentName}` should be valid according to `PackageUrl`.


it("should be ok for git", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          const input = `git@github:user/${{ packumentName }}`;
          expect(isZod(input, PackageUrl)).toBeTruthy();
        })
      );
    })

Summary: `isZod` should return true for inputs formatted as Git URLs with domain names.


it("should be ok for name with latest tag", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          const input = `${packumentName}@latest`;
          expect(isPackageSpec(input)).toBeTruthy();
        })
      );
    })

Summary: `isPackageSpec` should return true for package names combined with the `@latest` tag.


it("should split package without version", () =>
      fc.assert(
        fc.property(arbDomainName, (packageName) =>
          shouldSplitCorrectly(packageName)
        )
      ))

Summary: Packages are split correctly when no version is provided.


it("should split package with semantic version", () =>
      fc.assert(
        fc.property(arbDomainName, arbSemanticVersion, (packageName, version) =>
          shouldSplitCorrectly(packageName, version)
        )
      ))

Summary: `shouldSplitCorrectly` ensures a package with a semantic version is split appropriately.


it("should split package with package-url", () =>
      fc.assert(
        fc.property(arbDomainName, arbPackageUrl, (packageName, version) =>
          shouldSplitCorrectly(packageName, version)
        )
      ))

Summary: The function verifies that a package with a package URL is split correctly using given domain names and package URLs.


it("should be ok for name with semantic version", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) => {
          const input = `${packumentName}@1.2.3`;
          expect(isPackageId(input)).toBeTruthy();
        })
      );
    })

Summary: The function `isPackageId` should return true for names appended with a semantic version like `@1.2.3`.


it("should not be ok for just name", () => {
      fc.assert(
        fc.property(arbDomainName, (packumentName) =>
          expect(isPackageId(packumentName)).toBeFalsy()
        )
      );
    })

Summary: `isPackageId` should return false for a domain name.


it("should return error for package that is not in manifest", () => {
      fc.assert(
        fc.property(arbManifest, arbDomainName, (manifest, packageName) => {
          // In the rare case where the manifest has the dependency we cancel
          // the test.
          if (hasDependency(manifest, packageName)) return;

          const error = tryRemoveProjectDependency(
            manifest,
            packageName
          ).unwrapErr();

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

Summary: Attempting to remove a package not listed in a manifest should result in a `PackumentNotFoundError`.


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

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

          const hasDependency = recordKeys(updated.dependencies).includes(
            packageName
          );
          expect(hasDependency).toBeFalsy();
        })
      );
    })

Summary: Removing a dependency from a non-empty manifest should result in the dependency being absent in the updated manifest.


it("should return removed version", () => {
      fc.assert(
        fc.property(arbNonEmptyManifest, (manifest) => {
          const packageName = recordKeys(manifest.dependencies)[0]!;
          const versionInManifest = manifest.dependencies[packageName]!;

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

          expect(removedPackage).toEqual({
            name: packageName,
            version: versionInManifest,
          });
        })
      );
    })

Summary: Checking that `tryRemoveProjectDependency` returns the removed package with its original name and version from the manifest.


it('should accept any subdomain composed of only alphabet characters and with at most 63 characters', () =>
    fc.assert(
      fc.property(fc.string({ unit: alphaChar(), minLength: 1, maxLength: 63 }), (subdomainLabel) => {
        expect(filterInvalidSubdomainLabel(subdomainLabel)).toBe(true);
      }),
    ))

Summary: `filterInvalidSubdomainLabel` accepts subdomains composed solely of alphabetic characters with lengths up to 63 characters.


it("should remove empty scoped registries", () => {
      fc.assert(
        fc.property(arbManifestWithDependencyCount(1), (manifest) => {
          const originalScopedRegistryUrl = manifest.scopedRegistries![0]!.url;
          // Add a second scoped registry so that at least one non-empty registry
          // will remain in the manifest. Otherwise it would fully remove the
          // scoped registries property.
          const otherRegistry = RegistryUrl.parse("http://other.registry");
          manifest = mapScopedRegistry(manifest, otherRegistry, () =>
            makeScopedRegistry("Other registry", otherRegistry, [
              DomainName.parse("com.some.package"),
            ])
          );
          const packageName = recordKeys(manifest.dependencies)[0]!;

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

          const hasOriginalScopedRegistry = updated.scopedRegistries!.some(
            (it) => it.url === originalScopedRegistryUrl
          );
          expect(hasOriginalScopedRegistry).toBeFalsy();
        })
      );
    })

Summary: Removing a project dependency with `tryRemoveProjectDependency` should eliminate empty scoped registries from the manifest, ensuring that the original scoped registry is no longer present.


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

Summary: `fibo(n)` should equal the sum of `fibo(n-1)` and `fibo(n-2)` for integers `n` greater than or equal to 2.


it('should fulfill fibo(p)*fibo(q+1)+fibo(p-1)*fibo(q) = fibo(p+q)', () => {
    fc.assert(
      fc.property(fc.integer({ min: 1, max: MaxN }), fc.integer({ min: 0, max: MaxN }), (p, q) => {
        expect(fibo(p + q)).toBe(fibo(p) * fibo(q + 1) + fibo(p - 1) * fibo(q));
      }),
    );
  })

Summary: The equality `fibo(p) * fibo(q + 1) + fibo(p - 1) * fibo(q) = fibo(p + q)` holds for Fibonacci numbers.


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

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

          expect(updated.testables).not.toBeDefined();
        })
      );
    })

Summary: Removing a project dependency should result in the `testables` property being undefined if it was empty.


it("should have no effect for empty package list", () => {
      fc.assert(
        fc.property(arbManifest, (manifest) => {
          const [updated] = tryRemoveProjectDependencies(manifest, []).unwrap();

          expect(updated).toEqual(manifest);
        })
      );
    })

Summary: Removing dependencies from a manifest with an empty package list should result in no changes to the manifest.


it('should fulfill Catalan identity', () => {
    fc.assert(
      fc.property(fc.integer({ min: 0, max: MaxN }), fc.integer({ min: 0, max: MaxN }), (a, b) => {
        const [p, q] = a < b ? [b, a] : [a, b];
        const sign = (p - q) % 2 === 0 ? 1n : -1n; // (-1)^(p-q)
        expect(fibo(p) * fibo(p) - fibo(p - q) * fibo(p + q)).toBe(sign * fibo(q) * fibo(q));
      }),
    );
  })

Summary: The Fibonacci function should satisfy the Catalan identity for non-negative integers \(a\) and \(b\), where \(a \geq b\).


it("should remove packages", () => {
      fc.assert(
        fc.property(arbManifestWithDependencyCount(10), (manifest) => {
          const packagesToRemove = recordKeys(manifest.dependencies).slice(
            0,
            5
          );

          const [updated, removed] = tryRemoveProjectDependencies(
            manifest,
            packagesToRemove
          ).unwrap();

          // Here we only do some surface level tests to check that the
          // packages were removed correctly. More detailed tests are in
          // the section for the "remove single" function because the
          // "remove multiple" version uses that internally.

          packagesToRemove.forEach((it) => {
            const hasDependency = recordKeys(updated.dependencies).includes(it);
            expect(hasDependency).toEqual(false);
          });
          expect(removed.map((it) => it.name)).toEqual(packagesToRemove);
        })
      );
    })

Summary: `tryRemoveProjectDependencies` should correctly remove specified packages from a manifest's dependencies.


it("should have dependency after adding", () => {
      fc.assert(
        fc.property(
          arbManifest,
          arbDomainName,
          abrDependencyVersion,
          (manifest, packageName, version) => {
            const [updated] = addProjectDependency(
              manifest,
              packageName,
              version
            );

            expect(updated.dependencies?.[packageName]).toEqual(version);
          }
        )
      );
    })

Summary: Adding a project dependency results in the manifest containing the dependency with the specified version.


it('should fulfill Cassini identity', () => {
    fc.assert(
      fc.property(fc.integer({ min: 1, max: MaxN }), (p) => {
        const sign = p % 2 === 0 ? 1n : -1n; // (-1)^p
        expect(fibo(p + 1) * fibo(p - 1) - fibo(p) * fibo(p)).toBe(sign);
      }),
    );
  })

Summary: The test verifies that the Cassini identity holds for Fibonacci numbers, ensuring \( \text{fibo}(p+1) \times \text{fibo}(p-1) - \text{fibo}(p)^2 \) equals \( (-1)^p \).


it('should fibo(nk) divisible by fibo(n)', () => {
    fc.assert(
      fc.property(fc.integer({ min: 1, max: MaxN }), fc.integer({ min: 0, max: 100 }), (n, k) => {
        expect(fibo(n * k) % fibo(n)).toBe(0n);
      }),
    );
  })

Summary: `fibo(n * k)` should be divisible by `fibo(n)`.


it("should have correct change for updated dependency", () => {
      fc.assert(
        fc.property(
          arbManifest,
          arbDomainName,
          abrDependencyVersion,
          abrDependencyVersion,
          (manifest, packageName, previousVersion, version) => {
            // If generated versions are equal, we cancel the test
            if (previousVersion === version) return;

            // Add previous version
            manifest = addProjectDependency(
              manifest,
              packageName,
              previousVersion
            )[0];

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

            expect(change).toEqual<AddResult>({
              type: "upgraded",
              fromVersion: previousVersion,
              toVersion: version,
            });
          }
        )
      );
    })

Summary: Updating a dependency in a manifest should reflect a change of type "upgraded" with correct `fromVersion` and `toVersion` details.


test("fuzz `event` w/ `object`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.object(), async (event) => {
			await handler(event, context);
		}),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})


test("fuzz `event` w/ `record`", async () => {
	await fc.assert(
		fc.asyncProperty(
			fc.record({
				getObjectContext: fc.record({
					inputS3Url: fc.webUrl(),
					outputRoute: fc.webUrl(),
					outputToken: fc.string(),
				}),
				Body: fc.string(),
			}),
			async (event) => {
				await handler(event, context);
			},
		),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})

Summary: The handler processes a fuzzed event with nested `getObjectContext` and `Body` properties without errors.


it("should transform repo", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.string(), // name
        fc.string(), // html_url
        fc.option(fc.webUrl()), // homepage
        fc.option(fc.string()), // description?
        fc.option(fc.string()), // language?
        fc.boolean(), // fork
        fc.option(
          // source?
          fc.record({
            full_name: fc.string(),
            html_url: fc.string(),
          })
        ),
        fc.integer(), // stargazers_count
        fc.integer(), // forks
        async (name, url, hp, desc, lang, frk, src, sg, frks) => {
          const hpr = hp ? hp : "";
          const raw = buildRaw(name, url, hpr, desc, lang, frk, src, sg, frks);
          const repo = buildRepo(name, url, hp, desc, lang, frk, src, sg, frks);

          if (lang != null) {
            fetchColors.mockResolvedValue({
              [lang]: { color: "the-color", url: "" },
            });
          }

          const n = nock("https://api.github.com/repos")
            .get(`/${slug}`)
            .reply(200, raw);

          await expect(getRepo(slug)).resolves.toStrictEqual(repo);

          n.done();
        }
      )
    );
  })

Summary: It verifies that transforming a repository data structure with various potential input combinations results in the expected output format when fetched from an external GitHub API.


test("fuzz `event` w/ `object`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.object(), async (event) => {
			try {
				await handler(event, context);
			} catch (e) {
				if (e.cause?.package !== "@middy/validator") {
					throw e;
				}
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})

Summary: The handler function processes various objects without errors, unless the error is specifically caused by the "@middy/validator" package.


it("renders the card correctly", async () => {
  await fc.assert(
    fc.asyncProperty(randomRepo(), async repo => {
      // Reset the DOM, to ensure a clean slate during fast-check.
      resetDOM();
      const slug = `thislooksfun/${repo.name}`;
      fetchRepo.mockResolvedValue(repo);

      const { getByTestId, queryByTestId } = render(RepoCard, { slug });

      // Loading
      const loading = getByTestId("loading");
      expect(loading).toBeInTheDocument();
      await waitForElementToBeRemoved(loading);
      expect(loading).not.toBeInTheDocument();

      // Render
      const name = getByTestId("repo-name");
      expect(name).toBeInTheDocument();
      expect(name.textContent).toEqual(repo.name);

      if (repo.isFork) {
        expect(getByTestId("fork")).toBeInTheDocument();
        const link = getByTestId("fork-link");
        expect(link).toBeInTheDocument();
        expect(link.getAttribute("href")).toEqual(repo.sourceUrl);
        expect(link.textContent).toEqual(repo.sourceName);
      } else {
        expect(queryByTestId("fork")).not.toBeInTheDocument();
      }

      if (repo.description) {
        const desc = getByTestId("description");
        expect(desc).toBeInTheDocument();
        expect(desc.textContent).toEqual(repo.description);
      } else {
        expect(queryByTestId("description")).not.toBeInTheDocument();
      }

      if (repo.language) {
        expect(getByTestId("language")).toBeInTheDocument();
        const lang = getByTestId("lang-name");
        expect(lang).toBeInTheDocument();
        expect(lang.textContent).toEqual(repo.language);
      } else {
        expect(queryByTestId("language")).not.toBeInTheDocument();
      }

      if (repo.stars > 0) {
        expect(getByTestId("stars")).toBeInTheDocument();
        const sc = getByTestId("star-count");
        expect(sc).toBeInTheDocument();
        expect(sc.textContent).toEqual(`${repo.stars}`);
      } else {
        expect(queryByTestId("stars")).not.toBeInTheDocument();
      }

      if (repo.forks > 0) {
        expect(getByTestId("forks")).toBeInTheDocument();
        const fc = getByTestId("fork-count");
        expect(fc).toBeInTheDocument();
        expect(fc.textContent).toEqual(`${repo.forks}`);
      } else {
        expect(queryByTestId("forks")).not.toBeInTheDocument();
      }

      if (repo.homepage) {
        expect(getByTestId("homepage")).toBeInTheDocument();
        const hl = getByTestId("homepage-link");
        expect(hl).toBeInTheDocument();
        expect(hl.getAttribute("href")).toEqual(repo.homepage);
        expect(hl.textContent).toEqual(repo.homepage);
      } else {
        expect(queryByTestId("homepage")).not.toBeInTheDocument();
      }
    })
  );
})

Summary: RepoCard component renders a repository's information correctly, including name, fork status, description, language, stars, forks, and homepage, based on the given repository data.


Summary: The test runs the `handler` function with randomized `event` objects to ensure it handles various object structures without errors.


test("fuzz `event` w/ `record`", async () => {
	await fc.assert(
		fc.asyncProperty(
			fc.record({
				headers: fc.object(),
			}),
			async (event) => {
				await handler(event, context);
			},
		),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})

Summary: The `handler` function should process events with random header objects without throwing errors.


it("shows an error if the loading failed", async () => {
  await fc.assert(
    fc.asyncProperty(fc.string(), fc.string(), async (name, errMsg) => {
      // Reset the DOM, to ensure a clean slate during fast-check.
      resetDOM();
      const slug = `thislooksfun/${name}`;
      fetchRepo.mockRejectedValue(new Error(errMsg));

      const { getByTestId, queryByTestId } = render(RepoCard, { slug });

      // Loading
      const loading = getByTestId("loading");
      expect(loading).toBeInTheDocument();
      expect(loading.textContent).toEqual(`Loading card for ${slug}...`);
      await waitForElementToBeRemoved(loading);
      expect(loading).not.toBeInTheDocument();

      // Error message
      expect(getByTestId("failed")).toBeInTheDocument();

      if (errMsg) {
        const msg = getByTestId("errmsg");
        expect(msg).toBeInTheDocument();
        expect(msg.textContent).toEqual(errMsg);
      } else {
        expect(queryByTestId("errmsg")).not.toBeInTheDocument();
      }
    })
  );
})

Summary: An error message is displayed in the `RepoCard` component if loading a repository fails, with the error message content matching the rejection message, or no specific message if none is provided.


xit("respects the chosen theme", async () => {
  const repo: repo.Repo = {
    name: "foo-bar",
    url: "http://example.com",
    description: "Hello world!",
    language: "typescript",
    isFork: true,
    sourceName: "boo-far",
    sourceUrl: "http://example.com/src",
    stars: 42,
    forks: 24,
  };

  await fc.assert(
    fc.asyncProperty(randomTheme(), async theme => {
      // Reset the DOM, to ensure a clean slate during fast-check.
      resetDOM();
      const slug = `thislooksfun/${repo.name}`;
      fetchRepo.mockResolvedValue(repo);

      const { getByTestId, queryByTestId } = render(RepoCard, { slug, theme });

      // Loading
      const loading = getByTestId("loading");
      expect(loading).toBeInTheDocument();
      const card = loading.parentElement;
      console.log(card?.style);
      if (card) console.log(window.getComputedStyle(card));
      expect(card).toHaveStyle({ color: theme.text });
      expect(loading.firstElementChild).toHaveStyle(`color: ${theme.link}`);
      await waitForElementToBeRemoved(loading);
      expect(loading).not.toBeInTheDocument();

      // Render
      const name = getByTestId("repo-name");
      expect(name).toBeInTheDocument();
      expect(name.textContent).toEqual(repo.name);

      if (repo.isFork) {
        expect(getByTestId("fork")).toBeInTheDocument();
        const link = getByTestId("fork-link");
        expect(link).toBeInTheDocument();
        expect(link.getAttribute("href")).toEqual(repo.sourceUrl);
        expect(link.textContent).toEqual(repo.sourceName);
      } else {
        expect(queryByTestId("fork")).not.toBeInTheDocument();
      }

      if (repo.description) {
        const desc = getByTestId("description");
        expect(desc).toBeInTheDocument();
        expect(desc.textContent).toEqual(repo.description);
      } else {
        expect(queryByTestId("description")).not.toBeInTheDocument();
      }

      if (repo.language) {
        expect(getByTestId("language")).toBeInTheDocument();
        const lang = getByTestId("lang-name");
        expect(lang).toBeInTheDocument();
        expect(lang.textContent).toEqual(repo.language);
      } else {
        expect(queryByTestId("language")).not.toBeInTheDocument();
      }

      if (repo.stars > 0) {
        expect(getByTestId("stars")).toBeInTheDocument();
        const sc = getByTestId("star-count");
        expect(sc).toBeInTheDocument();
        expect(sc.textContent).toEqual(`${repo.stars}`);
      } else {
        expect(queryByTestId("stars")).not.toBeInTheDocument();
      }

      if (repo.forks > 0) {
        expect(getByTestId("forks")).toBeInTheDocument();
        const fc = getByTestId("fork-count");
        expect(fc).toBeInTheDocument();
        expect(fc.textContent).toEqual(`${repo.forks}`);
      } else {
        expect(queryByTestId("forks")).not.toBeInTheDocument();
      }
    })
  );
})

Summary: The `RepoCard` component should correctly apply the specified theme to various elements when rendered with a given repository's data.


it('fails with a message', async () => {
      await fc.assert(fc.asyncProperty(fc.string(), async (s) => {
        await assert.isRejected(PromiseUtils.fail(s), s);
      }));
    })

Summary: `PromiseUtils.fail` should reject with the provided string message.


test("fuzz `event` w/ `record` ({version: 'vpc'})", async () => {
	await fc.assert(
		fc.asyncProperty(
			fc.record({
				method: fc.constantFrom(
					"HEAD",
					"OPTIONS",
					"GET",
					"POST",
					"PATCH",
					"DELETE",
					"TRACE",
					"CONNECT",
				),
				raw_path: fc.webPath(), // TODO webUrl({ withDomain:false, withPath: true, withQueryParameters:true})
			}),
			async (event) => {
				try {
					await handler(event, context);
				} catch (e) {
					if (e.cause?.package !== "@middy/http-router") {
						throw e;
					}
				}
			},
		),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [
				[{ method: "valueOf", raw_path: "?/" }],
				[{ method: "GET", raw_path: "?valueOf" }],
			],
		},
	);
})

Summary: The test verifies that the `handler` function processes events with various HTTP methods and raw paths without throwing exceptions unrelated to `@middy/http-router`.


it('succeeds for right', async () => {
      await fc.assert(fc.asyncProperty(fc.integer(), async (i) => {
        const actual = await PromiseUtils.eitherToPromise(E.right(i));
        assert.equal(actual, i);
      }));
    })

Summary: `PromiseUtils.eitherToPromise` should resolve to the same value contained in `E.right`.


it('fails for left', async () => {
      await fc.assert(fc.asyncProperty(fc.string(), async (s) => {
        const p = PromiseUtils.eitherToPromise(E.left(s));
        await assert.isRejected(p, s);
      }));
    })

Summary: `PromiseUtils.eitherToPromise` should return a rejected promise for inputs wrapped in `E.left` containing a string.


it('succeeds for some', async () => {
      await fc.assert(fc.asyncProperty(fc.integer(), async (i) => {
        const actual = await PromiseUtils.optionToPromise(O.some(i));
        assert.equal(actual, i);
      }));
    })

Summary: `PromiseUtils.optionToPromise` should resolve to the integer contained within an `O.some`.


it('maps', async () => {
      await fc.assert(fc.asyncProperty(fc.array(fc.integer()), async (xs) => {
        await assert.becomes(
          PromiseUtils.filterMap(xs, (x) => PromiseUtils.succeed(x + 1)),
          xs.map((x) => x + 1)
        );
      }));
    })

Summary: `PromiseUtils.filterMap` correctly transforms an array of integers by applying an asynchronous function to increment each element.


it('is identity when all elements are right', () => {
      fc.assert(fc.property(fc.array(fc.integer()), (xs) => {
        assert.deepEqual(
          EitherUtils.rights(xs.map(E.right)),
          xs
        );
      }));
    })

Summary: `EitherUtils.rights` returns the original array of integers when all elements are wrapped as right values.


it('returns empty array when all elements are left', () => {
      fc.assert(fc.property(fc.array(fc.integer()), (xs) => {
        assert.deepEqual(
          EitherUtils.rights(xs.map(E.left)),
          []
        );
      }));
    })

Summary: `EitherUtils.rights` returns an empty array when all elements in the input array are left.


test("fuzz `event` w/ `record` ({version: '1.0'})", async () => {
	await fc.assert(
		fc.asyncProperty(
			fc.record({
				httpMethod: fc.constantFrom(
					"HEAD",
					"OPTIONS",
					"GET",
					"POST",
					"PATCH",
					"DELETE",
					"TRACE",
					"CONNECT",
				),
				path: fc.webPath(),
			}),
			async (event) => {
				try {
					await handler(event, context);
				} catch (e) {
					if (e.cause?.package !== "@middy/http-multipart-body-parser") {
						throw e;
					}
				}
			},
		),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})

Summary: The test checks if the handler can process events with various HTTP methods and paths without throwing exceptions unrelated to `@middy/http-multipart-body-parser`.


it('parses a correct 3-point version with preRelease', async () => {
      await fc.assert(fc.asyncProperty(smallNat, smallNat, smallNat, smallNat, async (major, minor, patch, preRelease) => {
        const input = `${major}.${minor}.${patch}-${preRelease}`;
        const expected = { major, minor, patch, preRelease: String(preRelease), buildMetaData: undefined };
        await assert.becomes(Version.parseVersion(input), expected);
      }));
    })

Summary: A correctly formatted 3-point version with preRelease information is parsed into its expected components.


it('parses a correct 3-point version with buildmeta', async () => {
      await fc.assert(fc.asyncProperty(smallNat, smallNat, smallNat, fc.integer({ min: 1, max: 100 }), async (major, minor, patch, buildMetaData) => {
        const input = `${major}.${minor}.${patch}+${buildMetaData}`;
        const actual = Version.parseVersion(input);
        const expected = { major, minor, patch, preRelease: undefined, buildMetaData: String(buildMetaData) };
        await assert.becomes(actual, expected);
      }));
    })

Summary: Parses a version string with major, minor, patch, and build metadata into its components, ensuring it matches the expected structure.


test("fuzz `event` w/ `record` ({version: 'vpc'})", async () => {
	await fc.assert(
		fc.asyncProperty(
			fc.record({
				method: fc.constantFrom(
					"HEAD",
					"OPTIONS",
					"GET",
					"POST",
					"PATCH",
					"DELETE",
					"TRACE",
					"CONNECT",
				),
				raw_path: fc.webPath(), // TODO webUrl({ withDomain:false, withPath: true, withQueryParameters:true})
			}),
			async (event) => {
				try {
					await handler(event, context);
				} catch (e) {
					if (e.cause?.package !== "@middy/http-multipart-body-parser") {
						throw e;
					}
				}
			},
		),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})

Summary: A handler processes various HTTP request methods and paths without throwing errors, except for those specifically caused by the `@middy/http-multipart-body-parser` package.


it('round-trips', async () => {
      await fc.assert(fc.asyncProperty(smallNat, smallNat, async (major, minor) => {
        const s = `${major}.${minor}`;
        const v = await Version.parseMajorMinorVersion(s);
        assert.deepEqual(Version.majorMinorVersionToString(v), s);
      }));
    })

Summary: Parsing a string representation of a version into a major and minor structure and then converting it back should result in the original string.


it('round-trips for 3-point version', async () => {
      await fc.assert(fc.asyncProperty(smallNat, smallNat, smallNat, async (major, minor, patch) => {
        const sVersion = `${major}.${minor}.${patch}`;
        const version = await Version.parseVersion(sVersion);
        const actual = Version.versionToString(version);
        assert.deepEqual(actual, sVersion);
      }));
    })

Summary: Parsing a 3-point version string into a version object and then converting it back to a string should yield the original version string.


it('round-trips for version with buildmeta', async () => {
      await fc.assert(fc.asyncProperty(smallNat, smallNat, smallNat, smallNatString,
        async (major, minor, patch, buildMetaData) => {
          const input = `${major}.${minor}.${patch}+${buildMetaData}`;
          const version = await Version.parseVersion(input);
          const actual = Version.versionToString(version);
          assert.deepEqual(actual, input);
        }
      ));
    })

Summary: Parsing and stringifying a version with build metadata should preserve the original format.


test("fuzz `event` w/ `object`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.object(), async (event) => {
			await handler(event, context);
		}),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})


it('is reflexive for 3-point versions', () => {
      fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer(), (major, minor, patch) => {
        assert.equal(Version.compareVersions({ major, minor, patch }, { major, minor, patch }), Comparison.EQ);
      }));
    })

Summary: `Version.compareVersions` returns `Comparison.EQ` when comparing identical versions represented by major, minor, and patch numbers.


test("fuzz `event` w/ `record`", async () => {
	await fc.assert(
		fc.asyncProperty(
			fc.record({
				headers: fc.record({
					"Accept-Charset": fc.string(),
					"Accept-Encoding": fc.string(),
					"Accept-Language": fc.string(),
					Accept: fc.string(),
				}),
			}),
			async (event) => {
				await handler(event, context);
			},
		),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})

Summary: The handler should correctly process events with randomly generated `Accept-*` headers.


it('is reflexive for 3-point versions with prerelease', () => {
      fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer(), fc.hexaString(), (major, minor, patch, preRelease) => {
        assert.equal(Version.compareVersions({ major, minor, patch, preRelease }, { major, minor, patch, preRelease }), Comparison.EQ);
      }));
    })

Summary: Comparing two identical 3-point versions with prerelease results in equality (`Comparison.EQ`).


it('considers preRelease versions lower less than release versions of the same 3-point version', () => {
      fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer(), fc.hexaString(), (major, minor, patch, preRelease) => {
        assert.equal(Version.compareVersions({ major, minor, patch, preRelease }, { major, minor, patch }), Comparison.LT);
        assert.equal(Version.compareVersions({ major, minor, patch }, { major, minor, patch, preRelease }), Comparison.GT);
      }));
    })

Summary: Pre-release versions are considered lower than release versions for the same major, minor, and patch version numbers.


test("fuzz `event` w/ `record`", async () => {
	await fc.assert(
		fc.asyncProperty(
			fc.record({
				headers: fc.object(),
			}),
			async (event) => {
				await handler(event, context);
			},
		),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})


it('compares minor versions', () => {
      fc.assert(fc.property(fc.integer(), fc.integer({ min: 0, max: 1000 }), fc.integer(), fc.integer(), fc.hexaString(), fc.hexaString(),
        (major, minor, patch1, patch2, preRelease1, preRelease2) => {
          assert.equal(Version.compareVersions(
            { major, minor, patch: patch1, preRelease: preRelease1 },
            { major, minor: minor + 1, patch: patch2, preRelease: preRelease2 }
          ), Comparison.LT);
          assert.equal(Version.compareVersions(
            { major, minor: minor + 1, patch: patch2, preRelease: preRelease2 },
            { major, minor, patch: patch1, preRelease: preRelease1 }
          ), Comparison.GT);
        }));
    })

Summary: Comparing versions where one version has a minor version increment results in the original version being less, and the incremented version being greater.


it('compares patch versions', () => {
      fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer({ min: 0, max: 1000 }), fc.hexaString(), fc.hexaString(),
        (major, minor, patch, preRelease1, preRelease2) => {
          assert.equal(Version.compareVersions(
            { major, minor, patch, preRelease: preRelease1 },
            { major, minor, patch: patch + 1, preRelease: preRelease2 }
          ), Comparison.LT);
          assert.equal(Version.compareVersions(
            { major, minor, patch: patch + 1, preRelease: preRelease2 },
            { major, minor, patch, preRelease: preRelease1 }
          ), Comparison.GT);
        }));
    })

Summary: `Version.compareVersions` correctly identifies a version with a higher patch number as greater, and a version with a lower patch number as lesser.


test("fuzz `event` w/ `object`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.object(), async (event) => {
			try {
				await handler(event, context);
			} catch (e) {
				if (e.cause?.package !== "@middy/cloudformation-router") {
					throw e;
				}
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})

Summary: The test checks that the `handler` function processes an `event` object without throwing an error that does not originate from the `@middy/cloudformation-router` package.


it('makes branch names (property)', () => {
      fc.assert(fc.property(fc.nat(1000), fc.nat(1000), (major, minor) => {
        assert.equal(getReleaseBranchName({ major, minor }), `release/${major}.${minor}`);
      }));
    })

Summary: `getReleaseBranchName` generates branch names in the format `release/major.minor` for given major and minor version numbers.


it('parses versions', async () => {
      await fc.assert(fc.asyncProperty(fc.nat(1000), fc.nat(1000), async (major, minor) => {
        await assert.becomes(
          versionFromReleaseBranch(`release/${major}.${minor}`),
          { major, minor }
        );
      }));
    })

Summary: `versionFromReleaseBranch` correctly parses major and minor version numbers from release branch strings.


test("fuzz `event` w/ `record`", async () => {
	await fc.assert(
		fc.asyncProperty(
			fc.record({
				body: fc.anything(),
			}),
			async (event) => {
				await handler(event, context);
			},
		),
		{
			numRuns: 100_000,
			verbose: 2,

			examples: [],
		},
	);
})

Summary: The handler processes events with arbitrary content in the `body` field without errors.


it('makes a timestamped version on feature branch', async () => {
      await fc.assert(fc.asyncProperty(fc.nat(), fc.nat(), async (major, minor) => {
        const patch = 0;
        const v = `${major}.${minor}.${patch}-main`;
        const actual = Stamp.chooseNewVersion(BranchState.Feature, await Version.parseVersion(v), 'b0d59ad', timeMillis);
        assert.equal(Version.versionToString(actual), `${major}.${minor}.${patch}-feature.${timeFormatted}.shab0d59ad`);
      }));
    })

Summary: A timestamped version should be generated on a feature branch, incorporating the major and minor numbers, patch zero, and specific formatting including a timestamp and SHA prefix.


it('does not change version for release version', async () => {
      await fc.assert(fc.asyncProperty(fc.nat(), fc.nat(), fc.nat(), async (major, minor, patch) => {
        const v = `${major}.${minor}.${patch}`;
        const actual = Stamp.chooseNewVersion(BranchState.ReleaseReady, await Version.parseVersion(v), 'aorseitnoarsetn', timeMillis);
        assert.equal(Version.versionToString(actual), v);
      }));
    })

Summary: `Stamp.chooseNewVersion` retains the original version string for release versions.


test('Should replace simple types', () => {
      fc.assert(
        fc.property(arb, fc.func(arb), (s, f) => {
          return replace(f, (t: string): t is any => true)(s) === f(s);
        }),
      );
    })

Summary: Verifies that the `replace` function behaves like a simple identity function when the type predicate always returns true.


it('succeeds for release command with major.minor arg', async () => {
      await fc.assert(fc.asyncProperty(fc.nat(100), fc.nat(100), async (major, minor) => {
        await assert.becomes(
          parseArgs([ 'release', `${major}.${minor}` ]),
          O.some(BeehiveArgs.releaseArgs(false, process.cwd(), O.none, O.none, `release/${major}.${minor}`, false, false, false, false))
        );
        await assert.becomes(
          parseArgs([ 'release', `${major}.${minor}`, '--dry-run' ]),
          O.some(BeehiveArgs.releaseArgs(true, process.cwd(), O.none, O.none, `release/${major}.${minor}`, false, false, false, false))
        );
      }));
    })

Summary: Parsing the 'release' command with a `major.minor` format should produce the expected `BeehiveArgs`, with and without the `--dry-run` option.


it("Returns the same input always", () => {
    fc.assert(
      fc.property(fc.anything(), fc.anything(), (input, x) =>
        expect(constant(input)(x)).toEqual(input),
      ),
    );
  })

Summary: The function `constant` returns the same input value regardless of the second argument.


it("creates an object from the entries", () => {
    fc.assert(
      fc.property(fc.array(fc.tuple(fc.string(), fc.anything())), entries => {
        const expected = entries.reduce((state, [key, value]) => ({ ...state, [key]: value }), {});
        expect(objectFromEntries<{ [key: string]: unknown }>(entries)).toEqual(expected);
      }),
    );
  })

Summary: `objectFromEntries` creates an object from an array of key-value pairs, matching the expected object structure.


test('Should replace only properties', () => {
      fc.assert(
        fc.property(fc.dictionary(fc.string(), arb), fc.func(arb), (obj, f) => {
          const realResult = Object.fromEntries(
            Object.entries(obj).map(([k, v]) => [k, f(v)]),
          );
          const obtainedResult = replace(
            f,
            (t): t is any => !Array.isArray(t) && typeof t !== 'object',
          )(obj);

          expect(obtainedResult).toStrictEqual(realResult);
        }),
      );
    })

Summary: The function `replace` should transform only the properties of an object by applying a given function, resulting in an output that strictly matches the expected manually transformed object.


it("returns the initial result if passed the output of objectToEntries", () => {
    fc.assert(
      fc.property(fc.object(), (obj: object) => {
        expect(objectFromEntries(objectToEntries(obj))).toEqual(obj);
      }),
    );
  })

Summary: The property should hold that converting an object to entries and then back to an object results in the original object.


it("creates entries from an object", () => {
    fc.assert(
      fc.property(fc.object(), (obj: any) => {
        const expected = Object.keys(obj).map(key => [key, obj[key]]);
        expect(objectToEntries(obj)).toEqual(expected);
      }),
    );
  })

Summary: The function `objectToEntries` should convert an object into an array of key-value pairs matching the output of `Object.keys(obj).map(key => [key, obj[key]])`.


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

Summary: The test ensures that when the input value is a valid IPv6 address, `checkValidity` returns true after updating.


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: The test ensures that inputs not matching the regex pattern `/^[0-9/]*$/` are considered invalid.


Summary: The test confirms that for valid IPv6 inputs, the input element passes the `checkValidity()` check after updating.


test("fuzz sessionLookup w/ value", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (value) => {
			try {
				await sessionLookup(testSession.sid, value);
			} catch (e) {
				catchError(value, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The `sessionLookup` function should handle any input value without producing errors other than specific expected errors.


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 not allowed for inputs that do not match a valid IPv6 format, ensuring `checkValidity` returns false for such cases.


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

Summary: The test ensures that an input element maintains validity for hexadecimal strings with lengths between 1 and 5.


test("fuzz sessionSelect w/ id", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (id) => {
			try {
				await sessionSelect(sub, id);
			} catch (e) {
				catchError(id, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `sessionSelect` should handle inputs robustly by only allowing expected errors: "400 Bad Request", "401 Unauthorized", "404 Not Found", and "409 Conflict".


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

Summary: Editing is disallowed when the input does not match the hexadecimal pattern /^[0-9a-fA-F]{1,5}$/.


Summary: Editing is allowed for valid IPv6 inputs when `input.checkValidity()` returns true after updating.


Summary: Input should be invalid when not matching an IPv6 regex pattern, ensuring `checkValidity` returns false.


test("fuzz sessionCreate w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await sessionCreate(sub, testSession.value, testSession.values);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The function `sessionCreate` should handle any input for `sub` without throwing unexpected errors.


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

Summary: Valid IPv4 inputs allow editing by ensuring `input.checkValidity()` returns true after an update.


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

Summary: Invalid IPv4 inputs should cause the `checkValidity` method to return false.


test("fuzz sessionCreate w/ value", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (value) => {
			try {
				await sessionCreate(sub, value, testSession.values);
			} catch (e) {
				catchError(value, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `sessionCreate` handles various input values without throwing unexpected errors.


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

Summary: The property ensures that for valid input matching a specific regular expression, the element allows editing, and `checkValidity` returns true.


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

Summary: Verifies that invalid input patterns do not pass the validity check and cannot be edited.


it('edits name attribute only for valid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(
          regexString(regExp.abstractDataAttributeName, 1, 32),
          async name => {
            nameTextField.value = name;
            await nameTextField.requestUpdate();
            expect(nameTextField.checkValidity()).to.be.true;
          }
        )
      );
    })

Summary: The test confirms that the `nameTextField` only accepts valid inputs matching a specific regular expression pattern when editing the name attribute.


test("fuzz sessionCheck w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await sessionCheck(sub, testSession.value);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `sessionCheck` handles a wide range of input values without throwing unexpected errors, allowing for expected HTTP errors.


it('edits only for valid inputs', async () => {
        await fc.assert(
          fc.asyncProperty(regexString(regExp.tName, 1), async name => {
            parent.wizardUI.inputs[0].value = name;
            await parent.updateComplete;
            expect(parent.wizardUI.inputs[0].checkValidity()).to.be.true;
          })
        );
      })

Summary: The test verifies that the input field in the wizard UI is valid only when it matches the specified regular expression pattern.


it('edits only for valid inputs', async () => {
        await fc.assert(
          fc.asyncProperty(regexString(regExp.decimal), async BitRate => {
            parent.wizardUI.inputs[3].value = BitRate;
            await parent.updateComplete;
            expect(parent.wizardUI.inputs[3].checkValidity()).to.be.true;
          })
        );
      })

Summary: The validity check ensures the `wizardUI` input accepts only decimal strings by verifying the input's `checkValidity` method returns true.