Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅ Test(actions): more test coverage #1455

Merged

Conversation

roninjin10
Copy link
Collaborator

@roninjin10 roninjin10 commented Sep 25, 2024

Description

Concise description of proposed changes

Testing

Explain the quality checks that have been done on the code changes

Additional Information

Your ENS/address:

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive test suites for various Ethereum JSON-RPC procedures, ensuring robust validation of transaction processing, account validation, and receipt retrieval functionalities.
    • Enhanced type safety for JSON-RPC request parameters by implementing immutable tuples.
  • Bug Fixes

    • Improved error handling across multiple procedures to ensure accurate responses for invalid requests and non-existent transactions.
  • Tests

    • Added unit tests for procedures including processTx, validateSetAccountParams, ethAccountsProcedure, and others to cover both successful and error scenarios.

Copy link

vercel bot commented Sep 25, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Updated (UTC)
tevm-monorepo-tevm ⬜️ Ignored (Inspect) Sep 25, 2024 7:07pm

Copy link

changeset-bot bot commented Sep 25, 2024

⚠️ No Changeset found

Latest commit: b1fa6f6

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Collaborator Author

roninjin10 commented Sep 25, 2024

This stack of pull requests is managed by Graphite. Learn more about stacking.

Join @roninjin10 and the rest of your teammates on Graphite Graphite

@roninjin10 roninjin10 marked this pull request as ready for review September 25, 2024 02:06
Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Walkthrough

This pull request introduces multiple test suites for various functions related to Ethereum transaction processing, validation, and retrieval. It enhances the codebase by adding comprehensive unit tests for functions such as processTx, validateSetAccountParams, and several JSON-RPC procedures, ensuring robust validation and error handling. Additionally, it modifies type declarations in the EthJsonRpcRequest.ts file to improve type safety by changing mutable tuples to immutable tuples.

Changes

File(s) Change Summary
packages/actions/src/Mine/processTx.spec.ts Introduced a test suite for the processTx function, validating transaction processing and receipt generation.
packages/actions/src/SetAccount/validateSetAccountParams.spec.ts Added unit tests for validateSetAccountParams, covering various input validation scenarios and error handling.
packages/actions/src/eth/EthJsonRpcRequest.ts Modified parameter types of several JSON-RPC request types to immutable tuples for enhanced type safety.
packages/actions/src/eth/ethAccountsProcedure.spec.ts Created tests for ethAccountsProcedure, validating responses with and without an id in JSON-RPC requests.
packages/actions/src/eth/ethGetTransactionByBlockHashAndIndexProcedure.spec.ts Introduced tests for retrieving transactions by block hash and index, covering both successful retrieval and error scenarios.
packages/actions/src/eth/ethGetTransactionByBlockNumberAndIndexProcedure.spec.ts Added tests for retrieving transactions by block number and index, validating both successful and error responses.
packages/actions/src/eth/ethGetTransactionByHashProcedure.spec.ts Established tests for ethGetTransactionByHash, ensuring correct retrieval of transaction details and handling of non-existent transactions.
packages/actions/src/eth/ethGetTransactionReceiptProcedure.spec.ts Created tests for retrieving transaction receipts, validating successful and unsuccessful retrieval scenarios.
packages/actions/src/eth/ethGetTransactionReceipt.spec.ts Introduced tests for ethGetTransactionReceiptHandler, covering successful retrieval and handling of non-existent receipts.
packages/actions/src/eth/ethSignProcedure.spec.ts Added tests for ethSignProcedure, validating message signing and error handling for non-existent accounts.
packages/actions/src/eth/getStorageAtHandler.spec.ts Established tests for getStorageAtHandler, covering various scenarios for retrieving storage values and error handling.
packages/errors/package.json Updated the scripts section to add new commented-out testing scripts for vitest, while removing previous entries.
packages/precompiles/src/logToEthjsLog.ts Modified the construction of argsArray for improved readability without changing logic.
packages/actions/src/Call/callHandlerOpts.js Clarified the precedence in the conditional expression for baseFeePerGas without altering the functionality.

Possibly related PRs

🐰 In the meadow where rabbits play,
New tests hop in to save the day!
For transactions, they check and see,
Ensuring all works perfectly!
With every test, the code grows bright,
A joyful leap, oh what a sight! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Base automatically changed from 09-24-_clown_face_chore_comment_out_errors_test_scripts to main September 25, 2024 02:10
@roninjin10 roninjin10 force-pushed the 09-24-_white_check_mark_test_actions_more_test_coverage branch from d1d36fe to d0825d8 Compare September 25, 2024 02:11
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Outside diff range and nitpick comments (28)
packages/actions/src/eth/ethAccountsProcedure.spec.ts (2)

17-25: LGTM: Good coverage for requests without id. Consider adding a negative test.

This test case effectively complements the first one by covering the scenario where the request doesn't include an 'id'. The expectations are comprehensive and the use of 'as const' ensures type safety.

Consider adding a negative test case to check how the function handles invalid inputs, such as:

  • A request with an invalid method name
  • A request with an invalid jsonrpc version

This would further improve the robustness of your test suite.


1-26: Great addition to test coverage. Consider expanding edge cases.

This new test file for ethAccountsProcedure is well-structured and provides good coverage for the main scenarios. It aligns well with the PR objective of increasing test coverage.

To further enhance the robustness of the test suite, consider:

  1. Adding negative test cases (as mentioned earlier).
  2. Testing with different numbers of accounts in testAccounts.
  3. Verifying the behavior when testAccounts is empty.

These additions would provide more comprehensive coverage and help catch potential edge cases.

packages/actions/src/Mine/processTx.spec.ts (1)

10-28: LGTM with suggestions: Comprehensive test case with room for enhancement.

The test case effectively sets up the TEVM environment and processes a transaction. However, consider the following improvements:

  1. Add more diverse test cases with different transaction parameters to increase coverage.
  2. Include assertions to verify the transaction details in the receipt (e.g., gas used, to address, value).
  3. Consider testing edge cases, such as transactions with insufficient gas or invalid recipients.

Here's an example of how you could enhance the assertions:

expect(receipts[0]).toMatchObject({
  status: 1,
  gasUsed: expect.any(BigInt),
  to: '0x1234567890123456789012345678901234567890',
  transactionHash: expect.any(String),
})

Additionally, consider adding a test case for a failing transaction:

it('should process a failing transaction', async () => {
  // ... setup code ...

  const tx = TransactionFactory.fromTxData({
    to: '0x1234567890123456789012345678901234567890',
    value: 1000000000000000000000000n, // Very high value to ensure failure
    gasLimit: 21000n,
    gasPrice: 10n,
  }).sign(hexToBytes(PREFUNDED_PRIVATE_KEYS[0]))

  await processTx(client, tx, blockBuilder, receipts)

  expect(receipts).toHaveLength(1)
  expect(receipts[0]).toBeDefined()
  expect(receipts[0].status).toBe(0) // Expect failure status
})
packages/actions/src/eth/ethSignProcedure.spec.ts (2)

6-24: LGTM: Well-structured test case with comprehensive assertions.

The test case effectively verifies the ethSignProcedure function's behavior for signing a message. It checks both the structure and content of the response, which is a good practice.

Consider extracting the expected response into a separate variable for improved readability:

const expectedResponse = {
  id: 1,
  jsonrpc: '2.0',
  method: 'eth_sign',
  result: await testAccounts[0].signMessage({ message: data }),
};

expect(response).toEqual(expectedResponse);

This change would make it easier to understand the expected structure at a glance and simplify maintenance if the structure changes in the future.


26-38: LGTM: Well-structured error case test with specific assertion.

The test case effectively verifies the error handling of ethSignProcedure when an invalid account is provided. The use of expect().rejects.toThrow() is appropriate for testing asynchronous errors.

Consider extracting the invalid address into a constant for improved readability and maintainability:

const INVALID_ADDRESS = `0x${'69'.repeat(20)}`;
const request = {
  id: 1,
  jsonrpc: '2.0',
  method: 'eth_sign',
  params: [INVALID_ADDRESS, data],
} as const;

// ... rest of the test ...

await expect(procedure(request)).rejects.toThrow(`Account ${INVALID_ADDRESS} not found`);

This change would make the test more self-documenting and easier to update if the invalid address format needs to change in the future.

packages/actions/src/eth/ethGetTransactionReceipt.spec.ts (3)

8-42: LGTM: Comprehensive test for successful transaction receipt retrieval.

The test case thoroughly checks the happy path scenario for retrieving a transaction receipt. It covers all the essential steps: creating a transaction, mining a block, and verifying the receipt's properties.

Consider adding an expectation for the status field of the receipt. Currently, it's set to undefined, but it should typically be 1 for a successful transaction or 0 for a failed one. You could add:

status: 1n, // or 0n if the transaction is expected to fail

to the expect(receipt).toMatchObject({...}) assertion.


44-54: LGTM: Good test for handling non-existent transaction receipts.

This test case effectively verifies that the handler returns null when a transaction receipt is not found. It's a crucial edge case to cover.

Consider using a more flexible approach for generating a non-existent transaction hash. Instead of hardcoding a specific hash, you could generate a random hash that's guaranteed not to exist in the current state. This would make the test more robust against potential changes in hash formats or node behavior. Here's an example:

import { randomBytes } from 'crypto'

// ...

const nonExistentHash = `0x${randomBytes(32).toString('hex')}` as Hex
const receipt = await handler({ hash: nonExistentHash })

This approach ensures that the hash is always a valid format and is extremely unlikely to collide with any existing transaction.


1-55: Consider adding more test cases for improved coverage.

The current test suite covers the basic successful and unsuccessful scenarios well. To further improve the robustness of the tests, consider adding the following cases:

  1. Test with a transaction that deploys a contract (check contractAddress in the receipt).
  2. Test with a transaction that emits events (verify logs and logsBloom).
  3. Test error handling (e.g., when the node is not available or returns an error).
  4. Test with different gas usage scenarios to verify gasUsed and cumulativeGasUsed calculations.

These additional tests would provide more comprehensive coverage of the ethGetTransactionReceiptHandler functionality and help catch potential edge cases.

packages/actions/src/eth/ethGetTransactionREceiptProcedure.spec.ts (3)

9-53: LGTM: Comprehensive test for successful transaction receipt retrieval.

The test case thoroughly covers the scenario where a transaction receipt is successfully retrieved. It simulates the entire process from sending a transaction to mining a block and then fetching the receipt. The assertions are comprehensive and cover all relevant fields of the transaction receipt.

Consider adding an assertion for the effectiveGasPrice field in the transaction receipt, as it's a standard field in Ethereum transaction receipts:

effectiveGasPrice: expect.any(String),

This addition would make the test even more comprehensive.


55-77: LGTM: Good test for non-existent transaction receipt.

This test case effectively covers the scenario where a transaction receipt is not found. It correctly asserts that the result is null when requesting a non-existent transaction receipt.

To make the test more robust, consider using a randomly generated transaction hash instead of a hardcoded one. This can help prevent any potential false positives if the hardcoded hash accidentally matches a real transaction in the future. Here's a suggestion:

import { randomBytes } from 'crypto'

// ...

const nonExistentTxHash = `0x${randomBytes(32).toString('hex')}`
const request = {
  // ...
  params: [nonExistentTxHash],
  // ...
}

This change would make the test more resilient to potential future changes in the test environment.


1-78: Great job on the test coverage! Consider adding more edge cases.

The test file provides excellent coverage for the main scenarios of the ethGetTransactionReceiptJsonRpcProcedure. Both the successful retrieval of a transaction receipt and the handling of a non-existent transaction are well tested.

To further enhance the test suite, consider adding the following test cases:

  1. Test with a pending transaction (not yet mined).
  2. Test with a transaction that has been reverted.
  3. Test with invalid input parameters (e.g., malformed transaction hash).
  4. Test concurrent requests for multiple transaction receipts.

These additional tests would cover more edge cases and error scenarios, making the test suite even more robust.

packages/actions/src/eth/ethGetTransactionByHashProcedure.spec.ts (2)

8-62: LGTM: Comprehensive test for successful transaction retrieval.

This test case thoroughly covers the happy path scenario for retrieving a transaction. It correctly sets up the environment, creates a transaction, mines a block, and then verifies the retrieved transaction details.

The use of regex for blockHash expectation is a good practice for handling dynamic values.

Consider adding a brief comment explaining the purpose of skipBalance: true in the transaction creation for better clarity:

 		const callResult = await callHandler(client)({
 			createTransaction: true,
 			to,
 			value: 420n,
+			// Skip balance check for testing purposes
 			skipBalance: true,
 		})

1-90: Great job on the test coverage! Consider adding more edge cases.

The test suite for ethGetTransactionByHashJsonRpcProcedure is well-structured and covers both the success and error scenarios effectively. The tests are comprehensive and follow good testing practices.

To further enhance the test coverage, consider adding the following test cases:

  1. Test with a pending transaction (not yet mined).
  2. Test with a transaction from a different block (not the latest).
  3. Test with invalid input formats (e.g., malformed transaction hash).
  4. Test the behavior when the node is in a specific state (e.g., syncing).

These additional tests would help ensure the robustness of the ethGetTransactionByHashJsonRpcProcedure function across various scenarios.

packages/actions/src/eth/ethGetTransactionByBlockHashAndIndexProcedure.spec.ts (3)

9-63: LGTM: Comprehensive test case for successful transaction retrieval.

This test case thoroughly covers the scenario where a transaction is successfully retrieved. The setup, execution, and assertions are well-structured and comprehensive.

Consider adding a comment explaining the purpose of skipBalance: true in the callHandler options. This would improve the readability and understanding of the test setup.


65-95: LGTM: Well-structured test case for transaction not found scenario.

This test case effectively covers the scenario where a transaction is not found, ensuring the correct error response is returned.

Consider adding the following test scenarios to improve coverage:

  1. Test with an invalid block hash.
  2. Test with an out-of-range index for a block with transactions.
  3. Test with various edge cases for the index (e.g., negative values, very large values).

These additional scenarios would help ensure the robustness of the ethGetTransactionByBlockHashAndIndexJsonRpcProcedure function.


1-95: Great job on increasing test coverage!

This new test file for ethGetTransactionByBlockHashAndIndexJsonRpcProcedure is well-structured, comprehensive, and aligns perfectly with the PR objective of increasing test coverage. The tests cover both successful and error scenarios, providing a solid foundation for ensuring the reliability of the procedure.

To further enhance the test suite:

  1. Consider implementing property-based testing for more exhaustive input combinations.
  2. Explore edge cases such as maximum gas limits, unusual transaction types, or interactions with other EVM features.
  3. If applicable, add integration tests that verify this procedure's interaction with other components of the system.

These additions would further strengthen the robustness of your testing strategy and align with best practices in Ethereum development.

packages/actions/src/eth/ethGetTransactionByBlockNumberAndIndexProcedure.spec.ts (3)

8-62: LGTM: Comprehensive test for successful transaction retrieval.

The test case thoroughly covers the scenario of retrieving an existing transaction. It properly sets up the environment, creates a transaction, mines a block, and verifies the retrieved transaction's properties.

Consider adding a comment explaining the significance of the 420n value used in the transaction. If it's an arbitrary value for testing, you might want to use a more descriptive constant like TEST_VALUE_WEI.


64-93: LGTM: Error handling scenario is well-tested.

The test case effectively covers the scenario where a transaction is not found. It correctly sets up an empty block and verifies the appropriate error response.

Consider adding a test case for an invalid block number or index to ensure complete error handling coverage.


1-94: LGTM: Well-structured and comprehensive test suite.

The test suite effectively covers both successful transaction retrieval and error handling scenarios. The tests are clear, well-organized, and use realistic data to simulate blockchain operations.

Consider adding the following test cases to further improve coverage:

  1. Retrieving a transaction with a non-zero index.
  2. Handling of invalid input parameters (e.g., malformed block number or index).
  3. Edge cases such as retrieving transactions from the genesis block or the latest block.
packages/actions/src/eth/getStorageAtHandler.spec.ts (4)

33-74: LGTM: Comprehensive coverage of block tag scenarios.

These test cases effectively cover different block tag scenarios, including 'pending' and a specific block number. The inclusion of block mining in the third test is particularly good for testing historical state retrieval.

Consider adding a test case for an 'earliest' block tag to cover all possible block tag values. This would ensure complete coverage of the API's capabilities.


88-104: LGTM: Good error handling test for storage retrieval.

This test case effectively verifies that errors from getContractStorage are properly handled and propagated. The use of mocking to simulate the error condition is appropriate.

Consider adding a more specific error message in the expectation:

).rejects.toThrow('Storage retrieval error')

This would ensure that the exact error message is being propagated, providing an extra layer of verification.


106-122: LGTM: Good error handling test for block retrieval.

This test case effectively verifies that errors from blockchain.getBlockByTag are properly handled and propagated. The use of mocking to simulate the error condition is appropriate.

Similar to the previous test, consider adding a more specific error message in the expectation:

).rejects.toThrow('Block retrieval error')

This would ensure that the exact error message is being propagated, providing an extra layer of verification.


1-123: Great job on the comprehensive test suite!

The test suite for getStorageAtHandler is well-structured and covers a wide range of scenarios, including basic functionality, different block tags, error handling, and edge cases. The use of constants and helper functions enhances readability and maintainability.

To further improve the test suite, consider the following suggestions:

  1. Add a test case for the 'earliest' block tag to ensure complete coverage of all possible block tag values.
  2. Include boundary tests for extremely large or small storage values and positions.
  3. Test the function's behavior with invalid input types or formats.
  4. Consider adding a test for concurrent storage operations to ensure thread safety if applicable.

These additions would provide even more robust coverage and help catch potential edge cases.

packages/actions/src/SetAccount/validateSetAccountParams.spec.ts (3)

26-95: LGTM: Comprehensive coverage of error scenarios.

These test cases effectively cover various error scenarios, each focusing on a specific invalid input. The use of specific error type checks ensures that the function is throwing the correct errors for each scenario.

Consider adding a brief comment before each test case to explain the specific scenario being tested. This can improve readability and maintainability of the test suite.


97-114: LGTM: Excellent test for multiple error scenarios.

This test case effectively verifies the function's ability to handle and report multiple errors simultaneously. It's a crucial test for ensuring comprehensive error checking.

Consider using expect.arrayContaining() instead of individual expect().some() calls. This can make the test more concise and easier to read. For example:

expect(errors).toEqual(
  expect.arrayContaining([
    expect.any(InvalidAddressError),
    expect.any(InvalidNonceError),
    // ... other error types
  ])
)

127-133: LGTM: Good test for handling partial input.

This test case effectively verifies that the function can handle partial input with only the required 'address' field. It's crucial to ensure that undefined optional fields don't cause errors.

Consider adding more variations of this test case with different combinations of optional fields. This would provide even more comprehensive coverage of partial input scenarios. For example:

it('should handle various combinations of optional fields', () => {
  const testCases = [
    { address: '0x1234567890123456789012345678901234567890' as const },
    { address: '0x1234567890123456789012345678901234567890' as const, nonce: 1n },
    { address: '0x1234567890123456789012345678901234567890' as const, balance: 100n },
    // Add more combinations as needed
  ]

  testCases.forEach(params => {
    const errors = validateSetAccountParams(params)
    expect(errors).toHaveLength(0)
  })
})
packages/actions/src/eth/EthJsonRpcRequest.ts (2)

Line range hint 255-266: Readonly tuple in EthSignTransactionJsonRpcRequest with potential for further improvement

The change to use a readonly tuple in EthSignTransactionJsonRpcRequest is consistent with the previous modifications and improves type safety. However, consider whether the inner object should also be made readonly for complete immutability. This would prevent accidental modifications to the object properties as well.

Example:

readonly [{
  readonly from: Address
  readonly to?: Address
  readonly gas?: Hex
  // ... other properties
}]

This suggestion is optional and depends on your team's preferences and use cases.


Line range hint 207-295: Summary of changes: Improved type safety across Ethereum JSON-RPC request types

The changes in this file consistently apply readonly tuples to various Ethereum JSON-RPC request type definitions. These modifications:

  1. Enhance type safety by preventing accidental modifications to parameters.
  2. Align with TypeScript best practices for immutable data structures.
  3. Contribute to improved test coverage by potentially catching issues related to unintended parameter modifications.
  4. Maintain consistency across all type definitions, improving code maintainability and readability.

These changes align well with the PR objective of improving test coverage and overall code quality. The consistent application of this pattern across all relevant type definitions is commendable.

Consider applying this pattern of using readonly tuples to other similar type definitions in the project, if not already done, to maintain consistency and further improve type safety across the codebase.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 27160c5 and d0825d8.

Files selected for processing (11)
  • packages/actions/src/Mine/processTx.spec.ts (1 hunks)
  • packages/actions/src/SetAccount/validateSetAccountParams.spec.ts (1 hunks)
  • packages/actions/src/eth/EthJsonRpcRequest.ts (4 hunks)
  • packages/actions/src/eth/ethAccountsProcedure.spec.ts (1 hunks)
  • packages/actions/src/eth/ethGetTransactionByBlockHashAndIndexProcedure.spec.ts (1 hunks)
  • packages/actions/src/eth/ethGetTransactionByBlockNumberAndIndexProcedure.spec.ts (1 hunks)
  • packages/actions/src/eth/ethGetTransactionByHashProcedure.spec.ts (1 hunks)
  • packages/actions/src/eth/ethGetTransactionREceiptProcedure.spec.ts (1 hunks)
  • packages/actions/src/eth/ethGetTransactionReceipt.spec.ts (1 hunks)
  • packages/actions/src/eth/ethSignProcedure.spec.ts (1 hunks)
  • packages/actions/src/eth/getStorageAtHandler.spec.ts (1 hunks)
Additional comments not posted (27)
packages/actions/src/eth/ethAccountsProcedure.spec.ts (3)

1-3: LGTM: Imports are appropriate and consistent.

The imports are well-structured and appropriate for a test file. The use of the '.js' extension in imports is consistent with ECMAScript modules.


5-5: LGTM: Well-structured describe block.

The describe block is appropriately named and follows best practices for organizing tests.


6-15: LGTM: Comprehensive test for JSON-RPC response with id.

This test case thoroughly checks the structure and content of the JSON-RPC response when the request includes an 'id'. The expectations are comprehensive and the use of 'as const' ensures type safety.

packages/actions/src/Mine/processTx.spec.ts (3)

1-6: LGTM: Imports are well-organized and relevant.

The imports are appropriately chosen for the test case, including necessary utilities from the TEVM ecosystem and the Vitest testing framework.


8-9: LGTM: Well-structured test suite.

The test suite is properly organized using describe and it blocks. The async nature of the test case is correctly handled.

Also applies to: 29-29


1-29: Overall assessment: Good start with room for improvement.

This new test file for processTx provides a solid foundation for testing the transaction processing functionality. The test is well-structured and covers the basic happy path scenario. To further enhance the test suite:

  1. Add more test cases to cover different scenarios and edge cases.
  2. Enhance assertions to verify more details of the transaction processing.
  3. Consider testing error handling and failure scenarios.

These improvements will increase the robustness and reliability of the test suite, ensuring better coverage of the processTx function's behavior under various conditions.

packages/actions/src/eth/ethSignProcedure.spec.ts (2)

1-3: LGTM: Imports are appropriate for the test file.

The import statements are concise and import only the necessary functions and data for the tests.


1-39: Overall, well-structured and effective test suite with room for expansion.

This test file for ethSignProcedure is well-organized and covers essential scenarios. The use of Vitest and appropriate testing patterns demonstrates good testing practices. The suggestions provided for minor improvements and additional test cases will further enhance the robustness and coverage of the test suite.

Great job on increasing the test coverage! This contribution will help improve the overall quality and reliability of the project.

packages/actions/src/eth/ethGetTransactionReceipt.spec.ts (1)

1-7: LGTM: Import statements are appropriate and well-structured.

The import statements are concise and import only the necessary dependencies. The use of type for the Hex import from 'viem' is a good practice for type-only imports.

packages/actions/src/eth/ethGetTransactionREceiptProcedure.spec.ts (1)

1-8: LGTM: Imports and test suite setup look good.

The import statements cover all necessary dependencies, and the describe block is properly structured for the test suite.

packages/actions/src/eth/ethGetTransactionByHashProcedure.spec.ts (2)

1-7: LGTM: Imports and structure are well-organized.

The imports are appropriate for the testing scenario, including the necessary functions from the project and the Vitest testing framework. The overall structure follows good testing practices with a describe block containing individual test cases.


64-90: LGTM: Well-structured test for non-existent transaction scenario.

This test case effectively covers the error scenario when attempting to retrieve a non-existent transaction. It correctly sets up the environment with an empty block and verifies the expected error response, including the specific error code and message.

The use of a hardcoded transaction hash for the non-existent transaction is appropriate for this test scenario.

packages/actions/src/eth/ethGetTransactionByBlockHashAndIndexProcedure.spec.ts (2)

1-6: LGTM: Import statements are well-organized and relevant.

The import statements are logically ordered and include all necessary dependencies for the test file. Good job on keeping the imports clean and relevant.


8-8: LGTM: Test suite setup is clear and focused.

The describe block accurately identifies the function being tested, providing a clear structure for the test cases.

packages/actions/src/eth/ethGetTransactionByBlockNumberAndIndexProcedure.spec.ts (1)

1-7: LGTM: Imports and test structure are well-organized.

The import statements cover all necessary dependencies, and the describe block is properly set up for the ethGetTransactionByBlockNumberAndIndexJsonRpcProcedure tests.

packages/actions/src/eth/getStorageAtHandler.spec.ts (3)

1-10: LGTM: Imports and constants are well-structured.

The imports cover all necessary dependencies for the test suite, and the constants are clearly defined with descriptive names. This setup provides a solid foundation for the test cases.


12-31: LGTM: Well-structured test for basic functionality.

This test case effectively covers the primary use case of getStorageAtHandler. It sets up the necessary state, calls the function with appropriate parameters, and verifies the expected result. The use of constants enhances readability and maintainability.


76-86: LGTM: Good coverage of non-existent storage scenario.

This test case effectively verifies the behavior of getStorageAtHandler when querying non-existent storage. It's crucial to test this edge case to ensure the function behaves correctly in all scenarios.

packages/actions/src/SetAccount/validateSetAccountParams.spec.ts (4)

1-10: LGTM: Imports are appropriate and comprehensive.

The import statements are well-structured, importing necessary error types, testing utilities, and the function under test. This setup provides a solid foundation for the test suite.


13-24: LGTM: Comprehensive test for valid input.

This test case effectively covers the scenario where all input parameters are valid. It's a good practice to start with a positive test case. The use of 'as const' for certain fields enhances type safety.


116-125: LGTM: Good coverage of edge case.

This test case effectively covers the scenario where the 'throwOnFail' parameter is invalid. It's important to test such edge cases to ensure comprehensive input validation.


1-134: Overall: Excellent test coverage with room for minor enhancements.

This test suite provides comprehensive coverage for the validateSetAccountParams function. It effectively tests various scenarios including valid input, individual error cases, multiple errors, edge cases, and partial input. The tests are well-structured and use appropriate assertions.

To further improve the test suite:

  1. Consider adding brief comments before each test case to explain the specific scenario being tested.
  2. In the multiple errors test case, consider using expect.arrayContaining() for more concise assertions.
  3. Expand the partial input test to cover more combinations of optional fields.

These enhancements would make the test suite even more robust and maintainable.

packages/actions/src/eth/EthJsonRpcRequest.ts (5)

207-207: Improved type safety for EthGetTransactionReceiptJsonRpcRequest

The change to make the tuple parameter readonly is a good improvement. It enhances type safety by preventing accidental modifications to the parameter, which can help catch potential issues in tests and usage of this type.


243-243: Consistent improvement in EthSendTransactionJsonRpcRequest

The modification to use a readonly tuple for the EthSendTransactionJsonRpcRequest type is consistent with the previous change. This continues to enhance type safety and aligns with TypeScript best practices for immutable data structures.


248-248: Consistent readonly tuple usage in EthSignJsonRpcRequest

The change to EthSignJsonRpcRequest follows the same pattern of using a readonly tuple. This consistency across type definitions is commendable, as it improves maintainability and makes the codebase easier to understand.


277-277: Readonly tuple in EthNewFilterJsonRpcRequest with serialized content

The change to use a readonly tuple in EthNewFilterJsonRpcRequest is consistent with the previous modifications and improves type safety. The use of SerializeToJson<FilterParams> suggests that the inner structure is already being transformed, which may provide some level of immutability. This combination of readonly tuple and serialization offers good protection against unintended modifications.


295-295: Completion of readonly tuple pattern with EthUninstallFilterJsonRpcRequest

The change to use a readonly tuple in EthUninstallFilterJsonRpcRequest completes the pattern of making all tuple parameters readonly in this file. This consistent approach across all type definitions enhances type safety, prevents accidental modifications to parameters, and aligns with TypeScript best practices for immutable data structures. These changes collectively contribute to a more robust and maintainable codebase.

Comment on lines +5 to +39
describe('ethSignProcedure', () => {
it('should sign a message', async () => {
const data = '0x42069'
const request = {
id: 1,
jsonrpc: '2.0',
method: 'eth_sign',
params: [testAccounts[0].address, data],
} as const

const procedure = ethSignProcedure(testAccounts)
const response = await procedure(request)

expect(response).toEqual({
id: 1,
jsonrpc: '2.0',
method: 'eth_sign',
result: await testAccounts[0].signMessage({ message: data }),
})
})

it("should throw an error if account doesn't exist", async () => {
const data = '0x42069'
const request = {
id: 1,
jsonrpc: '2.0',
method: 'eth_sign',
params: [`0x${'69'.repeat(20)}`, data],
} as const

const procedure = ethSignProcedure(testAccounts)

await expect(procedure(request)).rejects.toThrow('Account 0x6969696969696969696969696969696969696969 not found')
})
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding more test cases for improved coverage.

The current test suite covers the basic functionality and one error scenario, which is a good start. To enhance the robustness of the tests, consider adding the following test cases:

  1. Test with different types of messages (e.g., empty string, very long string, special characters).
  2. Test with different accounts from the testAccounts array to ensure consistency across accounts.
  3. Test the behavior when invalid data is provided (e.g., non-hex string).
  4. Test with edge cases for the id and jsonrpc fields in the request object.

These additional test cases will help ensure that ethSignProcedure behaves correctly under various conditions and increase confidence in its reliability.

Comment on lines +1 to +94
import { createTevmNode } from '@tevm/node'
import { describe, expect, it } from 'vitest'
import { callHandler } from '../Call/callHandler.js'
import { mineHandler } from '../Mine/mineHandler.js'
import { ethGetTransactionByBlockNumberAndIndexJsonRpcProcedure } from './ethGetTransactionByBlockNumberAndIndexProcedure.js'

describe('ethGetTransactionByBlockNumberAndIndexJsonRpcProcedure', () => {
it('should return the transaction if found', async () => {
const client = createTevmNode()
const to = `0x${'69'.repeat(20)}` as const

// Send a transaction
const callResult = await callHandler(client)({
createTransaction: true,
to,
value: 420n,
skipBalance: true,
})

// Mine a block to include the transaction
await mineHandler(client)({})

// Get the block number
const block = await client.getVm().then((vm) => vm.blockchain.getCanonicalHeadBlock())
const blockNumber = `0x${block.header.number.toString(16)}` as const

const request = {
id: 1,
method: 'eth_getTransactionByBlockNumberAndIndex',
params: [blockNumber, '0x0'],
jsonrpc: '2.0',
} as const

const procedure = ethGetTransactionByBlockNumberAndIndexJsonRpcProcedure(client)
const response = await procedure(request)

expect(response.result?.hash).toEqual(callResult.txHash)
expect(response).toMatchObject({
id: 1,
jsonrpc: '2.0',
method: 'eth_getTransactionByBlockNumberAndIndex',
result: {
accessList: [],
blobVersionedHashes: undefined,
blockHash: expect.stringMatching(/^0x[a-fA-F0-9]{64}$/),
blockNumber: blockNumber,
data: '0x',
from: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
gas: '0x5a3c',
gasPrice: '0x7',
hash: '0x5e5b342fae6b13548e62c3038078915397ebd2406a8c67afd276e8dc84ebba80',
maxFeePerBlobGas: undefined,
maxFeePerGas: '0x7',
maxPriorityFeePerGas: '0x0',
nonce: '0x0',
to: '0x6969696969696969696969696969696969696969',
transactionIndex: '0x0',
type: '0x2',
value: '0x1a4',
},
})
})

it('should return an error if the transaction is not found', async () => {
const client = createTevmNode()

// Mine a block without any transactions
await mineHandler(client)({})

// Get the block number
const block = await client.getVm().then((vm) => vm.blockchain.getCanonicalHeadBlock())
const blockNumber = `0x${block.header.number.toString(16)}` as const

const request = {
id: 1,
method: 'eth_getTransactionByBlockNumberAndIndex',
params: [blockNumber, '0x0'],
jsonrpc: '2.0',
} as const

const procedure = ethGetTransactionByBlockNumberAndIndexJsonRpcProcedure(client)
const response = await procedure(request)

expect(response).toEqual({
id: 1,
jsonrpc: '2.0',
method: 'eth_getTransactionByBlockNumberAndIndex',
error: {
code: -32602,
message: 'Transaction not found',
},
})
})
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance code quality with constants and type improvements.

While the code is generally well-written, there are a few areas where it could be improved:

  1. Consider replacing magic numbers and strings with named constants. For example:

    const TEST_ADDRESS = `0x${'69'.repeat(20)}` as const;
    const TEST_VALUE_WEI = 420n;
  2. The use of as const is good for type safety, but be cautious of overuse. In some cases, like for request, it might be better to define an interface or type for the request structure.

  3. Consider using more descriptive names for some variables. For example, block could be latestBlock to make its purpose clearer.

These changes will improve code readability and maintainability.

@roninjin10 roninjin10 merged commit a14c61b into main Sep 25, 2024
9 checks passed
@roninjin10 roninjin10 deleted the 09-24-_white_check_mark_test_actions_more_test_coverage branch September 25, 2024 19:30
@coderabbitai coderabbitai bot mentioned this pull request Nov 1, 2024
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant