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(mstaking): implement StakeAuthorization tests #340

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

VolodymyrBg
Copy link

Implements comprehensive test suite for StakeAuthorization in the mstaking module. The tests cover:

  • Creation of new StakeAuthorization objects
  • Basic validation of authorization parameters
  • Message acceptance logic with allow/deny lists
  • Token limit validation and state updates
  • Message type URL handling for different authorization types

This improves the overall test coverage and helps ensure the reliability of the staking authorization functionality.

Implements comprehensive test suite for StakeAuthorization in the mstaking module.
The tests cover:
- Creation of new StakeAuthorization objects
- Basic validation of authorization parameters
- Message acceptance logic with allow/deny lists
- Token limit validation and state updates
- Message type URL handling for different authorization types

This improves the overall test coverage and helps ensure the reliability
of the staking authorization functionality.
@VolodymyrBg VolodymyrBg requested a review from a team as a code owner January 31, 2025 16:24
Copy link

coderabbitai bot commented Jan 31, 2025

📝 Walkthrough

Walkthrough

The pull request introduces comprehensive unit tests for the StakeAuthorization functionality in the authz_test.go file. These tests cover critical methods including NewStakeAuthorization, ValidateBasic, Accept, and MsgTypeURL. The new test suite thoroughly validates the creation, validation, acceptance, and message type URL generation for stake authorizations under various scenarios, ensuring robust error handling and correct behavior across different input configurations.

Changes

File Change Summary
x/mstaking/types/authz_test.go Added 4 new test functions:
- TestNewStakeAuthorization: Tests stake authorization creation
- TestStakeAuthorization_ValidateBasic: Validates basic authorization rules
- TestStakeAuthorization_Accept: Checks message acceptance conditions
- TestStakeAuthorization_MsgTypeURL: Verifies message type URL generation

Poem

🐰 Hop, hop, testing we go!
Stake authorizations in the know
Validators checked, errors caught tight
CodeRabbit's tests shine ever so bright
Quality leaps with each test we write! 🧪

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

@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: 1

🧹 Nitpick comments (3)
x/mstaking/types/authz_test.go (3)

15-75: Add more test cases for comprehensive coverage.

While the current test cases cover basic scenarios, consider adding the following cases to ensure thorough testing:

  1. Having both allow and deny lists (should error)
  2. Empty validator lists
  3. Nil amount
  4. Invalid authorization type
 tests := []struct {
     name              string
     allowedValidators []string
     deniedValidators  []string
     authzType         types.AuthorizationType
     amount           sdk.Coins
     expectError      bool
 }{
     // ... existing test cases ...
+    {
+        name:              "invalid - both allow and deny lists",
+        allowedValidators: []string{"val1"},
+        deniedValidators:  []string{"val2"},
+        authzType:         types.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
+        amount:           sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))),
+        expectError:      true,
+    },
+    {
+        name:              "valid - empty validator lists",
+        allowedValidators: []string{},
+        deniedValidators:  nil,
+        authzType:         types.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
+        amount:           sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))),
+        expectError:      false,
+    },
+    {
+        name:              "valid - nil amount",
+        allowedValidators: []string{"val1"},
+        deniedValidators:  nil,
+        authzType:         types.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
+        amount:           nil,
+        expectError:      false,
+    },
+    {
+        name:              "invalid - unspecified authorization type",
+        allowedValidators: []string{"val1"},
+        deniedValidators:  nil,
+        authzType:         types.AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED,
+        amount:           sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))),
+        expectError:      true,
+    },
 }

77-119: Add test cases for additional validation scenarios.

Consider adding the following test cases to improve validation coverage:

  1. Invalid coin denomination
  2. Zero amount coins
  3. Empty validator lists
 tests := []struct {
     name        string
     auth        types.StakeAuthorization
     expectError bool
 }{
     // ... existing test cases ...
+    {
+        name: "invalid - empty coin denomination",
+        auth: types.StakeAuthorization{
+            MaxTokens:         sdk.Coins{sdk.Coin{Denom: "", Amount: sdk.NewInt(1000)}},
+            AuthorizationType: types.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
+        },
+        expectError: true,
+    },
+    {
+        name: "invalid - zero amount coins",
+        auth: types.StakeAuthorization{
+            MaxTokens:         sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(0))),
+            AuthorizationType: types.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
+        },
+        expectError: true,
+    },
+    {
+        name: "valid - empty allow list",
+        auth: types.StakeAuthorization{
+            Validators: &types.StakeAuthorization_AllowList{
+                AllowList: &types.StakeAuthorization_Validators{
+                    Address: []string{},
+                },
+            },
+            MaxTokens:         sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))),
+            AuthorizationType: types.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
+        },
+        expectError: false,
+    },
 }

124-202: Add test cases for additional message types.

Consider adding test cases for:

  1. Redelegate message type
  2. Cancel unbonding delegation message type
  3. Invalid message type
 tests := []struct {
     // ... existing struct fields ...
 }{
     // ... existing test cases ...
+    {
+        name: "valid redelegate with allow list",
+        auth: types.StakeAuthorization{
+            Validators: &types.StakeAuthorization_AllowList{
+                AllowList: &types.StakeAuthorization_Validators{
+                    Address: []string{"val1"},
+                },
+            },
+            MaxTokens:         sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))),
+            AuthorizationType: types.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
+        },
+        msg: &types.MsgBeginRedelegate{
+            DelegatorAddress:    "delegator",
+            ValidatorSrcAddress: "val2",
+            ValidatorDstAddress: "val1",
+            Amount:             sdk.NewCoin("stake", sdk.NewInt(500)),
+        },
+        expectError: false,
+    },
+    {
+        name: "valid cancel unbonding delegation",
+        auth: types.StakeAuthorization{
+            Validators: &types.StakeAuthorization_AllowList{
+                AllowList: &types.StakeAuthorization_Validators{
+                    Address: []string{"val1"},
+                },
+            },
+            MaxTokens:         sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))),
+            AuthorizationType: types.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION,
+        },
+        msg: &types.MsgCancelUnbondingDelegation{
+            DelegatorAddress: "delegator",
+            ValidatorAddress: "val1",
+            Amount:          sdk.NewCoin("stake", sdk.NewInt(500)),
+            CreationHeight:  1,
+        },
+        expectError: false,
+    },
+    {
+        name: "invalid - wrong message type",
+        auth: types.StakeAuthorization{
+            Validators: &types.StakeAuthorization_AllowList{
+                AllowList: &types.StakeAuthorization_Validators{
+                    Address: []string{"val1"},
+                },
+            },
+            MaxTokens:         sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))),
+            AuthorizationType: types.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
+        },
+        msg: &types.MsgUndelegate{
+            DelegatorAddress: "delegator",
+            ValidatorAddress: "val1",
+            Amount:          sdk.NewCoin("stake", sdk.NewInt(500)),
+        },
+        expectError: true,
+    },
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f2cebe1 and e19b587.

📒 Files selected for processing (1)
  • x/mstaking/types/authz_test.go (1 hunks)
🔇 Additional comments (1)
x/mstaking/types/authz_test.go (1)

226-274: LGTM!

The test cases are comprehensive, covering all authorization types and properly verifying the panic case for unspecified type.

}

func TestStakeAuthorization_Accept(t *testing.T) {
ctx := sdk.Context{}.WithGasMeter(sdk.NewInfiniteGasMeter())
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use a proper context with block time and height.

The current test uses an empty context. Consider using a proper context with block time and height for more realistic testing.

-ctx := sdk.Context{}.WithGasMeter(sdk.NewInfiniteGasMeter())
+ctx := sdk.Context{}.
+    WithBlockTime(time.Now()).
+    WithBlockHeight(1).
+    WithGasMeter(sdk.NewInfiniteGasMeter())
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ctx := sdk.Context{}.WithGasMeter(sdk.NewInfiniteGasMeter())
ctx := sdk.Context{}.
WithBlockTime(time.Now()).
WithBlockHeight(1).
WithGasMeter(sdk.NewInfiniteGasMeter())

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