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(accounts): fix integration tests #22418

Merged
merged 8 commits into from
Nov 11, 2024
Merged

Conversation

akhilkumarpilli
Copy link
Contributor

@akhilkumarpilli akhilkumarpilli commented Nov 4, 2024

Description

ref: #22364 (comment)

  • Fix accounts integration tests and remove build tag
  • Set AccountAbstractKeeper in Ante Handler

Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Enhanced account management capabilities with new dependencies for account abstraction and counters.
    • Introduced new functions for dependency injection to facilitate account creation.
  • Bug Fixes

    • Improved error handling in testing setup for account initialization and transaction signing.
  • Documentation

    • Updated test files to reflect changes in build constraints and imports for better clarity.
  • Chores

    • Cleaned up build constraints in test files to allow broader inclusion in builds.

Copy link
Contributor

coderabbitai bot commented Nov 4, 2024

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

📥 Commits

Reviewing files that changed from the base of the PR and between eeb9814 and a410360.

📒 Files selected for processing (1)
  • tests/integration/baseapp/block_gas_test.go (1 hunks)
 ____________________________________________________
< It's dangerous to go alone! Take this code review. >
 ----------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several enhancements to the account management capabilities within the SimApp. Key changes include the addition of new dependencies for account abstraction and a counter, modifications to the setCustomAnteHandler method, and updates to dependency injection in the NewSimApp function. Additionally, test files are updated to improve testing functionality, including new helper functions and the removal of build constraints. New functions are added in the account_abstraction and counter packages to facilitate account creation through dependency injection.

Changes

File Path Change Summary
simapp/app_di.go - Added imports for account_abstraction and counter.
- Updated setCustomAnteHandler to include AccountAbstractionKeeper.
- Modified depinject.Provide in NewSimApp to include new account providers.
tests/integration/accounts/base_account_test.go - Removed build constraint //go:build app_v1.
- Added global variables privKey and accCreator.
- Introduced functions coins and setupApp for better test setup.
tests/integration/accounts/wiring_test.go - Removed build constraint //go:build app_v1, allowing inclusion in builds without this tag.
x/accounts/testing/account_abstraction/minimal.go - Added ProvideAccount function for dependency injection of MinimalAbstractedAccount.
x/accounts/testing/counter/counter.go - Added ProvideAccount function for dependency injection of Account objects.
x/validate/depinject.go - Updated newAnteHandler to include AccountAbstractionKeeper.
- Modified ProvideModule to include AccountAbstractionKeeper in ModuleInputs.

Possibly related PRs

  • refactor(simapp): simplify simapp di #21718: The changes in this PR involve significant modifications to the simapp/app_di.go file, which is directly related to the updates made in the main PR regarding the SimApp structure and dependency injection.
  • test: x/accounts systemtests #22320: This PR introduces system tests for the x/accounts module, which aligns with the main PR's focus on enhancing account management capabilities within the SimApp, particularly in the context of testing and abstraction.

Suggested labels

C:CLI

Suggested reviewers

  • sontrinh16
  • tac0turtle
  • julienrbrt

Tip

CodeRabbit can approve the review once all CodeRabbit's comments are resolved.

Enable the reviews.request_changes_workflow setting in your project's settings in CodeRabbit to automatically approve the review once all CodeRabbit's comments are resolved.


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.

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
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

I think we should remove that go build tag instead. This was because x/account didn't support depinject, but now it does. Thanks for fixing this so fast btw <3

@akhilkumarpilli
Copy link
Contributor Author

I think we should remove that go build tag instead.

Still some tests are failing without build tag. Will try to fix them.

@akhilkumarpilli akhilkumarpilli changed the title test(accounts): fix integration tests and update ci test(accounts): fix integration tests Nov 5, 2024
@github-actions github-actions bot removed the Type: CI label Nov 5, 2024
@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Nov 11, 2024
@akhilkumarpilli akhilkumarpilli marked this pull request as ready for review November 11, 2024 13:02
FeegrantKeeper: in.FeeGrantKeeper,
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
UnorderedTxManager: in.UnorderedTxManager,
AccountAbstractionKeeper: in.AccountAbstractionKeeper,
Copy link
Member

Choose a reason for hiding this comment

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

nice catch!

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

🧹 Outside diff range and nitpick comments (5)
x/accounts/testing/account_abstraction/minimal.go (2)

78-80: LGTM! Clean dependency injection implementation.

The ProvideAccount function follows the dependency injection pattern correctly by registering the account constructor with a clear identifier.

Consider documenting the "aa_minimal" identifier's significance in the function comment to help other developers understand its purpose in the DI container.


Missing test coverage for minimal account abstraction implementation

The MinimalAbstractedAccount implementation lacks dedicated test coverage. While it's used in simapp and there are general authentication tests in the base package, this testing utility requires its own test suite to ensure:

  • Proper initialization and dependency injection via ProvideAccount
  • Authentication flow with sequence increment
  • Event emission during authentication
  • Handler registration functionality

Key areas needing tests:

  • x/accounts/testing/account_abstraction/minimal_test.go should be created
  • Integration tests for aa_minimal account type in simapp
  • Verification of interface compliance beyond the compile-time check
🔗 Analysis chain

Line range hint 1-80: Verify test coverage for the minimal implementation.

Since this is a testing utility, it's crucial to ensure it has proper test coverage, especially for the new dependency injection functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for test files and coverage
# Test 1: Look for corresponding test files
echo "Checking for test files..."
fd -e go --full-path ".*minimal_test\.go$" x/accounts/testing/account_abstraction/

# Test 2: Check if the new ProvideAccount function is tested
echo "Checking for ProvideAccount tests..."
rg -l "TestProvideAccount|TestMinimalAbstractedAccount.*Provide" x/accounts/testing/account_abstraction/

Length of output: 337


Script:

#!/bin/bash
# Let's try a broader search to understand the testing context

# Check for any test files in the directory
echo "All test files in account_abstraction directory:"
fd -e go "test" x/accounts/testing/account_abstraction/

# Look for any tests that might reference MinimalAbstractedAccount
echo -e "\nReferences to MinimalAbstractedAccount in test files:"
rg "MinimalAbstractedAccount" --type go -C 2 x/accounts/testing/account_abstraction/

# Check if this is used in integration tests elsewhere
echo -e "\nUsage in other test files:"
rg "aa_minimal" --type go -C 2

Length of output: 6060


Script:

#!/bin/bash
# Let's check for integration tests in simapp since we found usage there
echo "Checking simapp tests for MinimalAbstractedAccount usage:"
rg -C 3 "aa_minimal|MinimalAbstractedAccount" simapp/**/*_test.go

# Let's also check for any test files that might test the account interface implementation
echo -e "\nChecking for account interface tests:"
rg -C 3 "TestAccount.*Interface|account\.Interface" --type go x/accounts/

# Check for any authentication related tests
echo -e "\nChecking for authentication related tests:"
rg -C 3 "TestAuthenticate|authentication.*test" --type go x/accounts/

Length of output: 1000

tests/integration/accounts/base_account_test.go (2)

103-114: LGTM: Helper functions are well-structured.

The helper functions follow good testing practices with proper error handling and test helper marking. However, consider enhancing setupApp to support different test scenarios.

Consider making setupApp more flexible:

-func setupApp(t *testing.T) *simapp.SimApp {
+func setupApp(t *testing.T, opts ...func(*simapp.SimApp)) *simapp.SimApp {
 	t.Helper()
 	app := simapp.Setup(t, false)
+	for _, opt := range opts {
+		opt(app)
+	}
 	return app
 }

This would allow tests to customize the app setup as needed:

// Example usage:
app := setupApp(t, func(app *simapp.SimApp) {
    // Custom setup logic
})

Test coverage needs improvement for base account functionality

The current test implementation only covers the basic happy path scenario. Critical test cases are missing:

  • No validation of error cases (e.g., invalid public key format, insufficient funds)
  • No tests for edge cases (e.g., zero amount transfers, sequence number overflow)
  • No tests for account reinitialization attempts
  • No tests for invalid message handling or signature verification failures
  • No tests for account state queries and validation

Suggested locations to add tests:

  • tests/integration/accounts/base_account_test.go: Add new test functions for each scenario
  • Consider splitting into multiple test files for better organization of different test categories
🔗 Analysis chain

Line range hint 28-48: Enhance test coverage with additional scenarios.

While the current test covers the happy path, consider adding test cases for:

  1. Error scenarios (invalid public key, insufficient funds)
  2. Edge cases (zero amounts, max uint64 sequence numbers)
  3. Account reinitialization attempts
  4. Invalid message handling

Let's check the current test coverage:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check test coverage for account-related functionality
fd -e go . | grep -i "account.*test" | xargs -I {} sh -c 'echo "Coverage for {}:"; go test -coverprofile=coverage.out {} && go tool cover -func=coverage.out'

Length of output: 4209


Script:

#!/bin/bash
# Let's check the test files content to analyze coverage
rg -A 5 "func Test.*Account" tests/integration/accounts/base_account_test.go

# Check for error test cases
rg -l "require\.Error|assert\.Error" tests/integration/accounts/

# Look for edge case tests
rg "TestBaseAccount.*Edge|TestBaseAccount.*Invalid" tests/integration/accounts/

# Check for reinitialization tests
rg "reinit|reinitialization" tests/integration/accounts/base_account_test.go

Length of output: 543


Script:

#!/bin/bash
# Let's check the entire base_account_test.go content
cat tests/integration/accounts/base_account_test.go

# Also check for any other test files that might test base account functionality
rg -l "baseaccountv1" tests/integration/accounts/

Length of output: 3438

x/accounts/testing/counter/counter.go (1)

Line range hint 1-155: Consider adding package documentation.

While the implementation is solid, the package would benefit from a package-level documentation comment (doc.go or at the top of this file) explaining:

  • The purpose of this test package
  • Usage examples
  • Relationship with the account abstraction system

Example addition:

// Package counter implements a test account type that maintains
// a simple counter value. It serves as an example implementation
// of the accountstd.Interface and demonstrates proper usage of
// account abstraction patterns.
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 606544c and eeb9814.

📒 Files selected for processing (6)
  • simapp/app_di.go (3 hunks)
  • tests/integration/accounts/base_account_test.go (2 hunks)
  • tests/integration/accounts/wiring_test.go (0 hunks)
  • x/accounts/testing/account_abstraction/minimal.go (1 hunks)
  • x/accounts/testing/counter/counter.go (1 hunks)
  • x/validate/depinject.go (1 hunks)
💤 Files with no reviewable changes (1)
  • tests/integration/accounts/wiring_test.go
🧰 Additional context used
📓 Path-based instructions (5)
simapp/app_di.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

tests/integration/accounts/base_account_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

x/accounts/testing/account_abstraction/minimal.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/accounts/testing/counter/counter.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/validate/depinject.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (6)
tests/integration/accounts/base_account_test.go (1)

16-16: LGTM: Import addition is appropriate.

The secp256k1 import is necessary for private key generation used in the test setup.

x/accounts/testing/counter/counter.go (1)

153-155: LGTM! Clean implementation of the dependency injection provider.

The ProvideAccount function follows good practices by:

  • Providing a clear, single responsibility
  • Using the standard account dependency injection pattern
  • Maintaining consistency with the existing codebase structure
x/validate/depinject.go (1)

141-149: Verify the impact on existing transactions.

The addition of AccountAbstractionKeeper to the ante handler options looks good, but we should ensure this change doesn't affect the processing of regular transactions when account abstraction is not in use.

Let's verify the ante handler behavior:

✅ Verification successful

The AccountAbstractionKeeper integration is safely handled

The verification shows that the ante handler properly handles cases when AccountAbstractionKeeper is nil:

  • The SigVerificationDecorator explicitly checks if svd.aaKeeper != nil before attempting to use it
  • Regular transaction processing continues unaffected when AccountAbstractionKeeper is nil
  • The keeper is properly initialized as an optional dependency with optional:"true" tag

This confirms that the addition of AccountAbstractionKeeper won't affect existing transaction processing when account abstraction is not in use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any conditional handling of regular transactions when AccountAbstractionKeeper is nil

# Search for any special handling of nil AccountAbstractionKeeper in ante handler
ast-grep --pattern 'if $keeper == nil {
  $$$
}'

# Look for any related test cases
rg -l "TestAnteHandler.*AccountAbstraction" 

Length of output: 96


Script:

#!/bin/bash
# Let's check the ante handler implementation to understand how AccountAbstractionKeeper is used

# Search for AccountAbstractionKeeper usage in ante handler
rg -A 5 "AccountAbstractionKeeper" 

# Check for any special handling or validation in ante decorators
ast-grep --pattern 'func ($decorator $_) AnteHandle($ctx $_,$tx $_,$simulate bool) (sdk.Context, error) {
  $$$
}'

# Look for test files related to ante handler
fd -e go test.*ante

Length of output: 4247


Script:

#!/bin/bash
# Let's check how the SigVerificationDecorator handles nil AccountAbstractionKeeper

# Search for IsAbstractedAccount usage in signature verification
rg -B 5 -A 10 "IsAbstractedAccount"

# Look for signature verification implementation
ast-grep --pattern 'func ($d SigVerificationDecorator) AnteHandle($ctx $_,$tx $_,$simulate bool) (sdk.Context, error) {
  $$$
}'

# Check for any nil checks on AccountAbstractionKeeper
rg "if.*aaKeeper.*nil|if.*AccountAbstractionKeeper.*nil"

Length of output: 3708

simapp/app_di.go (3)

24-25: LGTM! Note testing-specific imports.

The new imports are correctly placed and properly grouped with other account-related imports. These are specifically for testing purposes, which aligns with the PR's objective of fixing integration tests.


188-191: LGTM! Testing-only account providers properly isolated.

The new account providers are correctly added and properly marked with a clear comment indicating their testing-only nature. This isolation helps prevent accidental use in production code.


308-316: LGTM! Verify AccountAbstractionKeeper integration.

The AccountAbstractionKeeper is properly added to HandlerOptions and correctly initialized. Let's verify its integration with the ante handler chain.

Comment on lines +23 to +26
var (
privKey = secp256k1.GenPrivKey()
accCreator = []byte("creator")
)
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 improving test determinism and maintainability.

The current implementation has several potential issues:

  1. Using GenPrivKey() at the package level could lead to non-deterministic tests. Consider moving key generation into a test setup function with a fixed seed.
  2. The magic string "creator" should be documented or defined as a named constant.
  3. Global variables can make tests harder to maintain and understand. Consider using a test fixture struct.

Here's a suggested refactor:

-var (
-    privKey    = secp256k1.GenPrivKey()
-    accCreator = []byte("creator")
-)

+const (
+    testCreatorID = "creator"
+)
+
+type testFixture struct {
+    privKey    cryptotypes.PrivKey
+    accCreator []byte
+}
+
+func setupTestFixture(t *testing.T) *testFixture {
+    t.Helper()
+    return &testFixture{
+        privKey:    secp256k1.GenPrivKeyFromSecret([]byte("fixed_test_seed")),
+        accCreator: []byte(testCreatorID),
+    }
+}
📝 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
var (
privKey = secp256k1.GenPrivKey()
accCreator = []byte("creator")
)
const (
testCreatorID = "creator"
)
type testFixture struct {
privKey cryptotypes.PrivKey
accCreator []byte
}
func setupTestFixture(t *testing.T) *testFixture {
t.Helper()
return &testFixture{
privKey: secp256k1.GenPrivKeyFromSecret([]byte("fixed_test_seed")),
accCreator: []byte(testCreatorID),
}
}

@akhilkumarpilli akhilkumarpilli added this pull request to the merge queue Nov 11, 2024
Merged via the queue into main with commit 78f08e8 Nov 11, 2024
75 of 76 checks passed
@akhilkumarpilli akhilkumarpilli deleted the akhil/fix-appv1-build branch November 11, 2024 15:17
mergify bot pushed a commit that referenced this pull request Nov 11, 2024
alpe added a commit that referenced this pull request Nov 13, 2024
* main: (31 commits)
  docs: update links for https security protocol (#22514)
  build(deps): Bump github.com/bytedance/sonic from 1.12.3 to 1.12.4 in /log (#22513)
  feat(x/protocolpool)!: allow any coins in continuous funds (#21916)
  docs: Update protobuf  tx signing message format outer link (#22510)
  test(accounts): fix integration tests (#22418)
  chore(x): fix some typos in comment (#22508)
  build(deps): Bump cosmossdk.io/log from 1.4.1 to 1.5.0 (#22487)
  build(deps): Bump cosmossdk.io/core from 1.0.0-alpha.5 to 1.0.0-alpha.6 (#22502)
  build(deps): Bump golang.org/x/crypto from 0.28.0 to 0.29.0 (#22480)
  docs(adr75): server v2 (#21069)
  fix(server/v2): improve server stop (#22455)
  chore: prepare core changelog (#22495)
  refactor(store/v2): simplify genesis flow (#22435)
  build(deps): Bump google.golang.org/grpc from 1.67.1 to 1.68.0 (#22486)
  build(deps): Bump golang.org/x/sync from 0.8.0 to 0.9.0 (#22482)
  feat(x/circuit): Allow msg Reset with empty msgURL (#22459)
  build(deps): Bump actions/xxx-artifact from v3 to v4 (#22468)
  feat(stf/branch): simplify merged iterator (#22131)
  refactor(log): disable coloring in testing logger (#22466)
  chore(x/tx): update changelog to alpha.2 (#22465)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:x/accounts C:x/validate
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants