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

challenger unit test #62

Merged
merged 1 commit into from
Jan 22, 2025
Merged

challenger unit test #62

merged 1 commit into from
Jan 22, 2025

Conversation

sh-cha
Copy link
Collaborator

@sh-cha sh-cha commented Jan 22, 2025

Summary by CodeRabbit

Based on the comprehensive summary, here are the release notes:

Release Notes

  • Testing Improvements

    • Added comprehensive unit tests for deposit, oracle, withdrawal, and handler functionalities
    • Enhanced test coverage for event parsing and handling across multiple components
  • Code Refactoring

    • Simplified event handling and parsing logic
    • Improved mock implementations for testing scenarios
    • Standardized event attribute generation and processing
  • Minor Enhancements

    • Updated function signatures in parsing methods
    • Introduced more robust error handling in test cases
    • Refined event attribute management

No user-facing features or breaking changes are introduced in this release.

@sh-cha sh-cha self-assigned this Jan 22, 2025
@sh-cha sh-cha requested a review from a team as a code owner January 22, 2025 05:20
Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Walkthrough

This pull request introduces comprehensive testing and refactoring across multiple packages in the child and provider modules. The changes focus on enhancing test coverage for deposit, withdrawal, and oracle-related functionalities. New mock implementations for hosts and challengers are added, and several test utilities are created to simulate different scenarios. The modifications simplify event parsing, update function signatures, and improve the overall testing infrastructure for the child and provider components.

Changes

File Change Summary
challenger/child/common_test.go Added mock implementations for mockHost and mockChallenger with methods for database, events, and challenges
challenger/child/deposit.go Simplified finalizeDepositHandler by integrating handleFinalizeDeposit directly
challenger/child/deposit_test.go Added test for finalizeDepositHandler with event queue validation
challenger/child/handler.go Modified endBlockHandler to send pendingChallenges
challenger/child/handler_test.go Added tests for beginBlockHandler and endBlockHandler
challenger/child/oracle_test.go Added test for oracleTxHandler
challenger/child/withdraw.go Minor modification in initiateWithdrawalHandler
challenger/child/withdraw_test.go Added comprehensive tests for withdrawal-related methods
executor/child/*_test.go Removed custom event generation functions, replaced with provider methods
provider/child/parse.go Updated function signatures for deposit and withdrawal parsing
provider/child/parse_test.go Added tests for parsing deposit, oracle, and withdrawal events
provider/child/testutil.go Added utility functions for generating event attributes

Sequence Diagram

sequenceDiagram
    participant Child
    participant Host
    participant Challenger
    participant Provider

    Child->>Provider: Parse Event Attributes
    Provider-->>Child: Return Parsed Event Data
    Child->>Host: Set Synced Outputs
    Child->>Challenger: Send Pending Challenges
    Challenger-->>Host: Process Challenges
Loading

Possibly related PRs

Suggested reviewers

  • beer-1

Poem

🐰 Hop, hop, through code so bright,
Testing challengers with all my might!
Mocks and events, a playful dance,
Refactoring with rabbit's glance.
Code quality blooms like spring's delight! 🌱

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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: 4

🧹 Nitpick comments (10)
executor/child/oracle_test.go (1)

Line range hint 35-52: Consider adding error test cases.

The test suite currently only covers the success case. Consider adding test cases for:

  • Invalid l1BlockHeight format
  • Missing required attributes
  • Empty sender address
challenger/child/oracle_test.go (1)

35-59: Expand test coverage with additional scenarios.

The test cases could be enhanced by adding:

  1. Oracle disabled scenario
  2. Invalid external commit bytes
  3. Zero block height case
  4. Future block time validation

Example test case:

{
    name:          "oracle disabled",
    oracleEnabled: false,
    blockHeight:   3,
    blockTime:     time.Unix(0, 100).UTC(),
    extCommitBz:   []byte("oracle_tx"),
    expected:      []challengertypes.ChallengeEvent{}, // Empty queue when oracle disabled
},
challenger/child/common_test.go (1)

47-61: Consider using custom error types for better error handling.

Instead of using a generic "collections: not found" error message, consider defining custom error types for better error handling and testing.

+var (
+    ErrBridgeNotFound = errors.New("bridge not found")
+    ErrOutputNotFound = errors.New("output not found")
+)

 func (m *mockHost) QuerySyncedOutput(ctx context.Context, bridgeId uint64, outputIndex uint64) (*ophosttypes.QueryOutputProposalResponse, error) {
     if _, ok := m.syncedOutputs[bridgeId]; !ok {
-        return nil, errors.New("collections: not found")
+        return nil, ErrBridgeNotFound
     }

     if _, ok := m.syncedOutputs[bridgeId][outputIndex]; !ok {
-        return nil, errors.New("collections: not found")
+        return nil, ErrOutputNotFound
     }
executor/child/deposit_test.go (1)

43-43: Consider adding more test cases.

The test looks good but only covers the success case. Consider adding test cases for:

  • Invalid event attributes
  • Missing required attributes
  • Edge cases with different amounts
provider/child/parse.go (1)

109-109: Consider adding validation for denom format.

While the denom parsing is implemented correctly, consider adding validation to ensure the denom follows the correct format (e.g., starts with 'u' for micro units).

 case opchildtypes.AttributeKeyDenom:
-    denom = attr.Value
+    if !strings.HasPrefix(attr.Value, "u") {
+        err = fmt.Errorf("invalid denom format %s, must start with 'u'", attr.Value)
+        return
+    }
+    denom = attr.Value

Also applies to: 131-132

provider/child/parse_test.go (3)

12-89: Add test case for invalid amount format in TestParseDepositEvents.

Consider adding a test case to verify error handling when the amount attribute contains an invalid format.

 		{
+			name: "invalid amount format",
+			eventAttrs: FinalizeDepositEvents(1, "sender", "recipient", "uinit", "baseDenom", sdk.NewInt64Coin("uinit", 10000), 2),
+			err:  true,
+		},

91-131: Add test case for invalid height format in TestParseUpdateOracle.

Consider adding a test case to verify error handling when the height attribute contains an invalid format.

 		{
+			name: "invalid height format",
+			eventAttrs: []abcitypes.EventAttribute{
+				{Key: opchildtypes.AttributeKeyHeight, Value: "invalid"},
+				{Key: opchildtypes.AttributeKeyFrom, Value: "sender"},
+			},
+			err:  true,
+		},

133-204: Add test case for invalid amount format in TestParseInitiateWithdrawal.

Consider adding a test case to verify error handling when the amount attribute contains an invalid format.

 		{
+			name: "invalid amount format",
+			eventAttrs: []abcitypes.EventAttribute{
+				{Key: opchildtypes.AttributeKeyFrom, Value: "from"},
+				{Key: opchildtypes.AttributeKeyTo, Value: "to"},
+				{Key: opchildtypes.AttributeKeyDenom, Value: "denom"},
+				{Key: opchildtypes.AttributeKeyBaseDenom, Value: "uinit"},
+				{Key: opchildtypes.AttributeKeyAmount, Value: "invalid"},
+				{Key: opchildtypes.AttributeKeyL2Sequence, Value: "1"},
+			},
+			err: true,
+		},
challenger/child/withdraw_test.go (1)

1-738: Comprehensive test coverage with room for improvement.

The test implementation thoroughly covers withdrawal scenarios, tree handling, and output preparation. Consider adding the following improvements:

  1. Add assertions for event emission in TestInitiateWithdrawalHandler
  2. Add boundary test cases for tree height in TestPrepareTree
  3. Add test cases for concurrent withdrawals in TestHandleOutput
executor/child/withdraw_test.go (1)

Line range hint 1-738: Add test cases for error scenarios.

Consider adding the following test cases to improve coverage:

  1. Error handling in InitiateWithdrawalEvents for invalid inputs
  2. Invalid denomination scenarios
  3. Edge cases for withdrawal amounts
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 640649b and 0a59991.

📒 Files selected for processing (16)
  • challenger/child/common_test.go (1 hunks)
  • challenger/child/deposit.go (2 hunks)
  • challenger/child/deposit_test.go (1 hunks)
  • challenger/child/handler.go (1 hunks)
  • challenger/child/handler_test.go (1 hunks)
  • challenger/child/oracle_test.go (1 hunks)
  • challenger/child/withdraw.go (1 hunks)
  • challenger/child/withdraw_test.go (1 hunks)
  • challenger/host/common_test.go (1 hunks)
  • executor/child/deposit_test.go (1 hunks)
  • executor/child/oracle_test.go (1 hunks)
  • executor/child/withdraw.go (1 hunks)
  • executor/child/withdraw_test.go (3 hunks)
  • provider/child/parse.go (4 hunks)
  • provider/child/parse_test.go (1 hunks)
  • provider/child/testutil.go (2 hunks)
🔇 Additional comments (14)
challenger/child/deposit.go (1)

Line range hint 18-29: LGTM! Event queue handling and logging look good.

The event queue handling is properly implemented with clear logging of all relevant fields.

challenger/host/common_test.go (1)

67-68: LGTM! Good practice with compile-time interface check.

The addition of var _ challenger = (*mockChallenger)(nil) ensures that mockChallenger properly implements the challenger interface at compile time.

executor/child/oracle_test.go (1)

41-41: LGTM! Good use of provider package.

Using childprovider.UpdateOracleEvents centralizes the event attribute creation logic in the provider package.

challenger/child/oracle_test.go (2)

33-33: LGTM! Good use of cryptographic hash.

Using SHA3-256 for the oracle transaction data checksum is a good choice for integrity verification.


61-68: Consider adding error assertions.

The test should verify that the handler properly handles error cases and doesn't panic.

challenger/child/common_test.go (2)

12-17: LGTM! Clean mock implementation with proper initialization.

The mockHost struct and its constructor are well-designed with proper field initialization.

Also applies to: 19-26


65-85: LGTM! Clean mock implementation.

The mockChallenger struct and its methods are well-implemented with proper initialization.

provider/child/testutil.go (3)

47-86: LGTM! Well-structured event creation utility.

The FinalizeDepositEvents function is well-implemented with proper type conversions and consistent attribute key usage.


88-102: LGTM! Clean implementation of oracle event creation.

The UpdateOracleEvents function follows the established pattern and properly handles type conversions.


104-138: LGTM! Well-implemented withdrawal event creation.

The InitiateWithdrawalEvents function maintains consistency with other event creation utilities and properly handles all required attributes.

challenger/child/handler.go (1)

95-95: LGTM!

The variable rename from challenges to pendingChallenges maintains consistency with the variable used throughout the function.

provider/child/parse.go (1)

27-27: LGTM!

The rename from l1BlockHeight to finalizeHeight improves clarity and better represents the variable's purpose.

challenger/child/withdraw.go (1)

24-24: LGTM!

The change correctly handles the new denom parameter by ignoring it with _ as it's not needed in this context. Error handling remains robust.

challenger/child/handler_test.go (1)

1-424: Well-structured test implementation!

The test cases are comprehensive and cover important scenarios including:

  • Begin block handling with event queue and stage management
  • End block handling with various conditions
  • Deposit timeout scenarios
  • Error cases and panic conditions

challenger/child/deposit.go Show resolved Hide resolved
challenger/child/deposit_test.go Show resolved Hide resolved
challenger/child/deposit_test.go Show resolved Hide resolved
executor/child/withdraw.go Show resolved Hide resolved
Copy link
Member

@beer-1 beer-1 left a comment

Choose a reason for hiding this comment

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

LGTM

@sh-cha sh-cha merged commit 8252e73 into main Jan 22, 2025
6 checks passed
@sh-cha sh-cha deleted the test/challenger2 branch January 22, 2025 08:12
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.

2 participants