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: unify identity versioned cost coverage #2416

Merged
merged 5 commits into from
Jan 12, 2025

Conversation

QuantumExplorer
Copy link
Member

@QuantumExplorer QuantumExplorer commented Jan 12, 2025

Issue being fixed or feature implemented

This pull request enhances test coverage for identity operations by unifying and expanding the versioned cost tests. It adds both “apply” and “no apply” test scenarios for first/latest versions, eliminating repetitive code and ensuring comprehensive validation of fee calculations.

What was done?

•	Refactored existing tests to include both first and latest platform versions, as well as apply vs. no-apply scenarios.
•	Added new tests covering negative balances and debt deduction logic (e.g., partial coverage of negative amounts).
•	Introduced consistent patterns to reduce code duplication and improve maintainability.

How Has This Been Tested?

•	Local test runs and CI checks confirming that all scenarios (with/without apply, first/latest versions) pass successfully.
•	Verified fee calculations against expected results for both first and latest versions to ensure correctness.

Breaking Changes

No breaking changes introduced. Existing functionality remains intact, though tests have been significantly reorganized and expanded.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

  • Tests

    • Enhanced test suite for identity management and document insertion.
    • Added version-specific test cases for first and latest platform versions.
    • Improved test modularity by introducing helper functions.
    • Refined fee estimation and application testing across multiple scenarios.
    • Removed outdated test cases for identity insertion.
  • Refactor

    • Restructured test functions to improve clarity and maintainability.
    • Consolidated repeated test logic into reusable helper functions.
    • Updated test naming conventions to reflect version-specific contexts.

@QuantumExplorer QuantumExplorer added enhancement New feature or request cleanup A refactoring or something that tidies up the project. labels Jan 12, 2025
@QuantumExplorer QuantumExplorer added this to the v1.8.0 milestone Jan 12, 2025
Copy link
Contributor

coderabbitai bot commented Jan 12, 2025

Walkthrough

This pull request introduces comprehensive modifications to the test suites across multiple modules in the Rust Drive implementation. The changes primarily focus on enhancing test coverage by adding version-specific test cases for identity and document insertion, balance updates, and key management. A key pattern emerges where tests are now separated into first and latest platform version scenarios, with helper functions introduced to reduce code duplication and improve test modularity. The modifications aim to provide more granular testing of fee estimation and application processes across different platform versions.

Changes

File Change Summary
packages/rs-drive/src/drive/document/insert/mod.rs - Renamed test functions to specify platform versions
- Added new test for fee estimation
- Introduced do_test_add_dashpay_profile_with_fee helper function
packages/rs-drive/src/drive/identity/balance/update.rs - Renamed balance-related test functions
- Added helper functions for different balance operations
- Enhanced fee result assertions
packages/rs-drive/src/drive/identity/insert/add_new_identity/mod.rs - Added new test module with version-specific identity insertion tests
- Introduced helper function for common test logic
packages/rs-drive/src/drive/identity/insert/add_new_identity/v0/mod.rs - Removed existing test module for identity insertion
packages/rs-drive/src/drive/identity/update/mod.rs - Refactored tests for key management and identity updates
- Added version-specific test cases
- Introduced helper functions for applying and estimating changes

Possibly related PRs

Suggested reviewers

  • shumkov

Poem

🐰 Hopping through code with glee,
Tests now dance with clarity!
Versions first and latest shine,
Helper functions draw the line,
Rabbit's code review, oh so fine! 🧪


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

🧹 Nitpick comments (5)
packages/rs-drive/src/drive/identity/update/mod.rs (2)

Line range hint 73-142: Add parameter documentation to the helper function.

While the function is well-structured, consider adding documentation for the parameters to improve maintainability:

+ /// Helper function to test adding balance to an identity
+ /// 
+ /// # Arguments
+ /// * `apply` - If true, commits the transaction. If false, only estimates costs
+ /// * `platform_version` - The platform version to use for the test
+ /// * `expected_fee_result` - The expected fee calculation result
 fn do_should_add_to_balance(
     apply: bool,
     platform_version: &PlatformVersion,
     expected_fee_result: FeeResult,
 ) {

275-383: Enhance assertion messages for better debugging.

Consider adding more descriptive messages to assertions to make test failures more informative:

- assert_eq!(updated_balance.expect("balance should present"), 0);
+ assert_eq!(
+     updated_balance.expect("balance should be present after update"),
+     0,
+     "Balance should be zero after debt reduction"
+ );

- assert_eq!(updated_negative_balance, negative_amount - added_balance);
+ assert_eq!(
+     updated_negative_balance,
+     negative_amount - added_balance,
+     "Negative balance should be reduced by the added balance amount"
+ );
packages/rs-drive/src/drive/document/insert/mod.rs (2)

318-379: Document the fee calculation logic.

The tests show complex fee calculations with significant differences between apply and estimate scenarios. Consider adding documentation explaining:

  1. How storage fees are calculated using epoch-based costs
  2. Why processing fees vary so much between apply and estimate
  3. The business logic behind these fee structures

Add a doc comment explaining the fee calculation:

/// # Fee Calculation Logic
/// 
/// Storage fees are calculated as:
/// * Base storage cost (1305) * Epoch-specific cost per byte
/// 
/// Processing fees vary by operation:
/// * Apply: 900,400 credits
/// * Estimate: 73,253,660 credits
/// 
/// The higher estimation cost accounts for...

Line range hint 381-444: LGTM! Well-documented helper function.

The function is well-structured with clear documentation and logical separation of concerns. Consider extracting the document setup into a separate helper function for reuse in other tests.

/// Extract document setup into a reusable function
fn setup_dashpay_profile_document(
    drive: &Drive,
    random_owner_id: [u8; 32],
    platform_version: &PlatformVersion,
) -> (DataContract, Document) {
    let contract = setup_contract(
        drive,
        "tests/supporting_files/contract/dashpay/dashpay-contract.json",
        None,
        None,
    );

    let document_type = contract
        .document_type_for_name("profile")
        .expect("expected to get document type");

    let document = json_document_to_document(
        "tests/supporting_files/contract/dashpay/profile0.json",
        Some(random_owner_id.into()),
        document_type,
        platform_version,
    )
    .expect("expected to get cbor document");

    (contract, document)
}
packages/rs-drive/src/drive/identity/balance/update.rs (1)

24-71: Consider documenting the fee estimation pattern.

This file follows the same pattern seen across other files where estimation costs are significantly higher than apply costs. This appears to be a consistent design decision across the codebase.

Consider adding a central documentation (e.g., in a README or module-level doc) explaining:

  1. Why estimation costs are consistently higher
  2. The rationale behind this design decision
  3. How these values were determined
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d637fe and 23cf69b.

📒 Files selected for processing (5)
  • packages/rs-drive/src/drive/document/insert/mod.rs (4 hunks)
  • packages/rs-drive/src/drive/identity/balance/update.rs (7 hunks)
  • packages/rs-drive/src/drive/identity/insert/add_new_identity/mod.rs (1 hunks)
  • packages/rs-drive/src/drive/identity/insert/add_new_identity/v0/mod.rs (0 hunks)
  • packages/rs-drive/src/drive/identity/update/mod.rs (9 hunks)
💤 Files with no reviewable changes (1)
  • packages/rs-drive/src/drive/identity/insert/add_new_identity/v0/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Rust packages (drive) / Unused dependencies
  • GitHub Check: Rust packages (drive) / Tests
  • GitHub Check: Rust packages (drive) / Linting
  • GitHub Check: Rust packages (drive-abci) / Check each feature
  • GitHub Check: Rust packages (dash-sdk) / Unused dependencies
  • GitHub Check: Rust packages (dash-sdk) / Tests
  • GitHub Check: Rust packages (dash-sdk) / Linting
  • GitHub Check: Rust packages (dash-sdk) / Check each feature
  • GitHub Check: Rust packages (drive-abci) / Unused dependencies
  • GitHub Check: Rust packages (drive-abci) / Tests
  • GitHub Check: Rust packages (drive-abci) / Linting
  • GitHub Check: Build Docker images (Dashmate helper, dashmate-helper, dashmate-helper) / Build Dashmate helper image
  • GitHub Check: Build Docker images (Drive, drive, drive-abci) / Build Drive image
  • GitHub Check: Build Docker images (DAPI, dapi, dapi) / Build DAPI image
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: Rust crates security audit
🔇 Additional comments (4)
packages/rs-drive/src/drive/identity/insert/add_new_identity/mod.rs (3)

136-146: LGTM! Well-structured test for first platform version.

The test effectively validates both storage and processing fees for identity insertion.


148-158: Verify if fee values should be identical across versions.

The test uses identical fee values for both first and latest platform versions. Please confirm if this is intentional or if the latest version should have different fee calculations.


184-223: LGTM! Well-designed helper function.

The helper function effectively:

  • Encapsulates common test logic
  • Handles both apply and non-apply scenarios
  • Includes proper transaction management
  • Has appropriate assertions
packages/rs-drive/src/drive/identity/update/mod.rs (1)

24-77: Clarify the significant difference in processing fees.

The processing fees show a large variance between apply and estimate scenarios:

  • Apply: 174,660
  • Estimate: 4,278,840

Please explain why estimation costs are significantly higher (~24x) than actual application costs.

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

🧹 Nitpick comments (4)
packages/rs-drive/src/drive/identity/update/mod.rs (4)

134-141: Complete the root hash verification.

The code calculates the root hash but doesn't verify it. Consider adding an assertion to ensure the state remains unchanged when apply is false.

-                // Not applying -> no commit. We can check root hash if we want
-                let app_hash_after = drive
-                    .grove
-                    .root_hash(None, &platform_version.drive.grove_version)
-                    .unwrap()
-                    .expect("should return app hash");
-                // Or any other logic to ensure no state changes actually took effect
-                let _ = app_hash_after;
+                // Verify state remains unchanged when not applying
+                let app_hash_before = drive
+                    .grove
+                    .root_hash(None, &platform_version.drive.grove_version)
+                    .unwrap()
+                    .expect("should return app hash");
+                drive.grove.rollback_transaction(db_transaction).unwrap();
+                let app_hash_after = drive
+                    .grove
+                    .root_hash(None, &platform_version.drive.grove_version)
+                    .unwrap()
+                    .expect("should return app hash");
+                assert_eq!(app_hash_before, app_hash_after, "State should remain unchanged when not applying");

703-704: Consider testing intermediate revision values.

The test jumps from revision 0 to 2 directly. Consider adding test cases for:

  • Incrementing revision by 1
  • Attempting to decrease revision
  • Attempting to skip multiple revisions

739-741: Enhance the comment for clarity.

The comment could be more descriptive about the expected state.

-                // No commit => no changes
+                // When not applying changes:
+                // 1. Transaction should be rolled back
+                // 2. Identity revision should remain at 0
+                // 3. State should be unchanged

Line range hint 1-742: Overall excellent test structure and coverage!

The implementation demonstrates:

  • Consistent test patterns across different operations
  • Effective use of helper functions to reduce duplication
  • Comprehensive coverage of platform versions and scenarios

Consider adding error case tests for:

  • Invalid identity IDs
  • Unauthorized key operations
  • Concurrent modifications
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 23cf69b and 05c14b6.

📒 Files selected for processing (1)
  • packages/rs-drive/src/drive/identity/update/mod.rs (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: Rust packages (dash-sdk) / Tests
  • GitHub Check: Rust packages (dash-sdk) / Check each feature
  • GitHub Check: Rust packages (drive-abci) / Check each feature
  • GitHub Check: Rust packages (dash-sdk) / Linting
  • GitHub Check: Rust packages (dash-sdk) / Formatting
  • GitHub Check: Rust packages (drive-abci) / Unused dependencies
  • GitHub Check: Rust packages (drive-abci) / Tests
  • GitHub Check: Rust packages (drive) / Tests
  • GitHub Check: Rust packages (drive-abci) / Linting
  • GitHub Check: Rust packages (drive-abci) / Formatting
  • GitHub Check: Rust packages (drive) / Unused dependencies
  • GitHub Check: Rust packages (drive) / Linting
  • GitHub Check: Build Docker images (Drive, drive, drive-abci) / Build Drive image
  • GitHub Check: Build JS packages / Build JS
🔇 Additional comments (2)
packages/rs-drive/src/drive/identity/update/mod.rs (2)

Line range hint 1-25: Well-structured module organization!

The code follows Rust best practices with clear separation of concerns and logical grouping of imports.


Line range hint 400-614: Excellent test coverage for key disabling functionality!

The tests thoroughly cover:

  • Both first and latest platform versions
  • Both apply and estimate scenarios
  • Fee consistency verification

@QuantumExplorer
Copy link
Member Author

Merging this in as it's only test improvements with no regressions. @shumkov if you wish to review you may though on Monday.

@QuantumExplorer QuantumExplorer merged commit a809df7 into v1.8-dev Jan 12, 2025
40 of 41 checks passed
@QuantumExplorer QuantumExplorer deleted the test/improveVersionedCostTests branch January 12, 2025 02:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cleanup A refactoring or something that tidies up the project. enhancement New feature or request
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

1 participant