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

fix: increase validators list pagination in query #85

Merged
merged 2 commits into from
Dec 1, 2024

Conversation

freak12techno
Copy link
Collaborator

@freak12techno freak12techno commented Dec 1, 2024

Related: #84

Summary by CodeRabbit

  • New Features

    • Increased pagination limit for fetching validators from 1,000 to 10,000, allowing for more extensive data retrieval in a single request.
  • Bug Fixes

    • Improved handling of validator fetching errors while maintaining existing logic.
  • Refactor

    • Updated the Tokens field type in the Validator struct for better precision in token representation.
    • Modified test function signatures to indicate unused parameters, streamlining the test suite.

Copy link
Contributor

coderabbitai bot commented Dec 1, 2024

Walkthrough

The pull request introduces several modifications across multiple files, primarily focusing on increasing the pagination limit for fetching validators from the Cosmos API. The limit has been adjusted from 1000 to 10000 in various test functions and the GetAllValidators method, allowing for a larger dataset retrieval. Additionally, the Tokens field type in the Validator struct has been changed from string to math.LegacyDec to enhance numerical precision. The overall logic and control flow of the application remain unchanged.

Changes

File Change Summary
pkg/app_test.go Updated pagination limit in TestAppLoadConfigOk from 1000 to 10000 in the Cosmos API URL; modified signature of TestAppStopOperation.
pkg/fetchers/validators_test.go Altered pagination limit in TestValidatorsFetcherQueryError, TestValidatorsFetcherNodeError, and TestValidatorsFetcherQuerySuccess from 1000 to 10000.
pkg/tendermint/rpc.go Increased pagination limit in GetAllValidators method from 1000 to 10000.
pkg/types/tendermint.go Changed Tokens field type in Validator struct from string to math.LegacyDec.
cmd/cosmos-validators-exporter_test.go Removed assert.True(t, true) from multiple test functions; updated signatures of TestValidateConfigWithWarnings and TestValidateConfigValid.

Possibly related PRs

🐇 In the meadow, where the data flows,
A limit raised, as knowledge grows.
From thousand to ten thousand bright,
Fetching validators, a wondrous sight!
With tokens now precise and clear,
We hop along, spreading cheer! 🌼


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.

Copy link

codecov bot commented Dec 1, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (cd71323) to head (b3bb269).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##              main       #85    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           65        65            
  Lines         2736      3351   +615     
==========================================
+ Hits          2736      3351   +615     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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 (1)
cmd/cosmos-validators-exporter_test.go (1)

Line range hint 1-82: Consider restructuring tests for better maintainability and performance

The current test structure has several areas for improvement:

  1. Heavy reliance on panic recovery for validation could be replaced with more explicit error handling
  2. Tests are explicitly marked as non-parallel, which could impact test execution time
  3. Global state modifications (os.Args) make tests hard to parallelize

Consider these improvements:

  1. Instead of using os.Args and main(), create a testable function that accepts config path as parameter
  2. Use error returns instead of panics for validation failures
  3. Implement proper test cleanup to allow parallel execution

Example approach:

func validateConfig(configPath string) error {
    // Move validation logic here
    return nil
}

func TestValidateConfig(t *testing.T) {
    t.Parallel()
    
    tests := []struct {
        name       string
        configPath string
        wantErr    bool
        wantWarns  bool
    }{
        {"valid config", "../assets/config-valid.toml", false, false},
        {"config with warnings", "../assets/config-with-warnings.toml", false, true},
        {"invalid config", "../assets/config-invalid.toml", true, false},
    }
    
    for _, tt := range tests {
        tt := tt
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel()
            err := validateConfig(tt.configPath)
            if tt.wantErr {
                require.Error(t, err)
            } else {
                require.NoError(t, err)
            }
        })
    }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 20730ba and b3bb269.

📒 Files selected for processing (3)
  • .golangci.yml (0 hunks)
  • cmd/cosmos-validators-exporter_test.go (1 hunks)
  • pkg/app_test.go (2 hunks)
💤 Files with no reviewable changes (1)
  • .golangci.yml
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/app_test.go
🔇 Additional comments (1)
cmd/cosmos-validators-exporter_test.go (1)

47-56: Verify test configuration files

Since these tests rely on configuration files in the "../assets/" directory, we should verify their existence and content.

✅ Verification successful

Test configuration files are valid and sufficient

The test configuration files exist and contain appropriate validator configurations. While the files don't explicitly contain pagination settings (as these are handled in the code), the code search reveals that pagination is properly implemented in the codebase:

  • Validator queries use a limit of 10000 (pagination.limit=10000)
  • Delegation and unbonding queries use appropriate pagination
  • Test files properly mock these paginated endpoints

The test files config-valid.toml, config-with-warnings.toml, and config-invalid.toml are present and contain the necessary validator configurations to exercise these scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test configuration files exist and contain appropriate test data

# Check if config files exist
echo "Checking config files existence..."
for config in config-valid.toml config-with-warnings.toml config-invalid.toml; do
  if [ -f "assets/$config" ]; then
    echo "Found: assets/$config"
    # Check for pagination settings
    echo "Content of $config:"
    cat "assets/$config"
  else
    echo "Missing: assets/$config"
  fi
done

# Search for pagination-related settings in all TOML files
echo -e "\nChecking pagination settings in all TOML files..."
rg -l --type toml "pagination|limit|page" 

Length of output: 4311


Script:

#!/bin/bash
# Let's check the code for pagination-related changes and configurations

# Search for pagination-related code changes
echo "Searching for pagination-related code..."
rg -n "pagination|limit|page" --type go

# Look for validator-related configuration or constants
echo -e "\nSearching for validator-related constants or configurations..."
rg -n "validator.*limit|page.*size|max.*validator" --type go

# Check for any test files that might contain pagination tests
echo -e "\nSearching for pagination-related test cases..."
rg -n "Test.*Page|Test.*Limit|Test.*Pagination" --type go

Length of output: 6927

Comment on lines +47 to 50
func TestValidateConfigWithWarnings(_ *testing.T) {
os.Args = []string{"cmd", "validate-config", "--config", "../assets/config-with-warnings.toml"}
main()
assert.True(t, true)
}
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 test coverage with explicit assertions

Both TestValidateConfigWithWarnings and TestValidateConfigValid lack assertions to verify the expected behavior. Simply checking that the code doesn't panic might miss subtle bugs where the code runs but produces incorrect results.

Consider adding assertions to verify:

  1. The config is loaded correctly with expected values
  2. For TestValidateConfigWithWarnings, verify that appropriate warnings are logged
  3. For TestValidateConfigValid, verify the validation results

Example refactor:

func TestValidateConfigWithWarnings(t *testing.T) {
+    // Capture logs or use a mock logger
+    logs := captureTestLogs(t)
    os.Args = []string{"cmd", "validate-config", "--config", "../assets/config-with-warnings.toml"}
    main()
+    // Verify expected warnings were logged
+    require.Contains(t, logs, "expected warning message")
}

func TestValidateConfigValid(t *testing.T) {
+    // Setup test expectations
+    expectedConfig := Config{...}  // Add expected values
    os.Args = []string{"cmd", "validate-config", "--config", "../assets/config-valid.toml"}
    main()
+    // Verify config was loaded with correct values
+    require.Equal(t, expectedConfig, actualConfig)
}

Also applies to: 53-56

@freak12techno freak12techno merged commit dda85f0 into main Dec 1, 2024
8 checks passed
@freak12techno freak12techno deleted the increase-validators-pagination branch December 1, 2024 22:36
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