Skip to content

test(drive): address review comments on identity test coverage#3334

Closed
QuantumExplorer wants to merge 1 commit into
v3.1-devfrom
test/drive-identity-review-fixes
Closed

test(drive): address review comments on identity test coverage#3334
QuantumExplorer wants to merge 1 commit into
v3.1-devfrom
test/drive-identity-review-fixes

Conversation

@QuantumExplorer
Copy link
Copy Markdown
Member

@QuantumExplorer QuantumExplorer commented Mar 16, 2026

Issue being fixed or feature implemented

Addresses review comments from the drive identity test coverage PR (#3330) on test/drive-identity-coverage.

What was done?

Fixed all 10 review comments:

  1. HIGH: BTreeMap ordering assertion is tautological — Replaced the tautological windows(2).all(|w| w[0] <= w[1]) assertion on BTreeMap keys (which is always sorted) with verification that every inserted identity appears in the result with the correct balance.

  2. MEDIUM: Weak nonce assertion — Replaced assert!(nonce > 0) with assert_eq!(nonce, 1) since the exact value is deterministic when merging nonce=1 onto an identity with initial nonce=0.

  3. MEDIUM: Masternode re-insertion test doesn't verify key re-enablement — Rewrote the test to first disable all keys, then re-insert the masternode identity, then verify all keys have is_disabled() == false.

  4. MEDIUM: Missing edge case — combined positive balance + negative credit — Added test that sets both a positive balance and negative credit on the same identity, verifying that fetch_identity_balance_include_debt returns the positive balance (negative credit is not consulted when balance > 0).

  5. LOW: .unwrap() without context — Replaced bare .unwrap() calls with .expect("descriptive message").

  6. LOW: Estimated-mode test asserts hardcoded placeholder — Enhanced the comment to clearly document that Some(0) is expected placeholder behavior in stateless/estimated mode, not a real balance. Added descriptive assertion message.

  7. LOW: assert!(result.is_err()) without checking error type — Replaced generic is_err() with a matches! assertion on Error::GroveDB(e) if matches!(e.as_ref(), grovedb::Error::PathParentLayerNotFound(_)).

  8. LOW: Missing test for partial results — Added fetch_identities_balances_partial test module where one identity exists and one doesn't, verifying only the existing one appears in results.

  9. NIT: Path tests skip root tree byte verification — Added assert_eq!(path[0], &[RootTree::Identities as u8]) (or the vec equivalent) to all path function tests.

  10. NIT: Incomplete enum conversion coverage — Extended should_convert_to_u8, should_convert_to_u8_array, and should_convert_to_static_u8_array_ref tests to cover all 6 IdentityRootStructure variants.

How Has This Been Tested?

cargo fmt --package drive -- --check   # passes
cargo test --package drive -- drive::identity  # 131 tests pass

Breaking Changes

None.

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

Summary by CodeRabbit

  • Tests
    • Expanded test coverage for identity management operations including balance, fetch, nonce, and revision handling.

- Fix tautological BTreeMap ordering assertion by verifying actual
  returned identity data instead of relying on BTreeMap's inherent
  sort order (fetch/mod.rs)
- Assert exact nonce value (1) after merge instead of weak nonzero
  check, since the value is deterministic for revision=0, nonce=0
  (fetch/nonce/mod.rs)
- Verify key re-enablement in masternode re-insertion test by first
  disabling keys, re-inserting, then asserting all keys are no longer
  disabled (insert/add_new_identity/mod.rs)
- Add edge-case test for identity with both positive balance and
  negative credit to verify the combined return value
  (fetch/balance/mod.rs)
- Replace .unwrap() with .expect("descriptive message") for optional
  balance lookups (fetch/mod.rs)
- Document that estimated-mode balance returns Some(0) as expected
  placeholder behavior, not real balance (fetch/balance/mod.rs)
- Match on specific PathParentLayerNotFound error variant instead of
  generic is_err() (fetch/balance/mod.rs)
- Add partial-results test for fetch_identities_balances where some
  identities exist and others don't (fetch/mod.rs)
- Add root tree byte verification (assert path[0] == Identities) to
  all path function tests (mod.rs)
- Cover all 6 IdentityRootStructure variants in TryFrom, u8 array,
  and static u8 array conversion tests (mod.rs)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@github-actions github-actions Bot added this to the v3.1.0 milestone Mar 16, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 16, 2026

Warning

Rate limit exceeded

@QuantumExplorer has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 19 minutes and 46 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 09fddd1b-75eb-4101-9ffc-656c742c2d41

📥 Commits

Reviewing files that changed from the base of the PR and between f6d3680 and 19e8df4.

📒 Files selected for processing (8)
  • packages/rs-drive/src/drive/identity/balance/update.rs
  • packages/rs-drive/src/drive/identity/fetch/balance/mod.rs
  • packages/rs-drive/src/drive/identity/fetch/mod.rs
  • packages/rs-drive/src/drive/identity/fetch/nonce/mod.rs
  • packages/rs-drive/src/drive/identity/fetch/partial_identity/mod.rs
  • packages/rs-drive/src/drive/identity/fetch/revision/mod.rs
  • packages/rs-drive/src/drive/identity/insert/add_new_identity/mod.rs
  • packages/rs-drive/src/drive/identity/mod.rs
📝 Walkthrough

Walkthrough

This PR adds comprehensive unit test coverage across the identity module, including tests for balance operations, identity fetching, nonce management, revision tracking, and insertion logic. All changes are test-only additions with no modifications to production code or public APIs.

Changes

Cohort / File(s) Summary
Balance Operations
packages/rs-drive/src/drive/identity/balance/update.rs
Adds two error-path tests for balance removal: attempting to remove more than available balance and removing from non-existent identity.
Balance Fetching
packages/rs-drive/src/drive/identity/fetch/balance/mod.rs
Introduces extensive tests for balance fetch operations, including scenarios with no balance, existing balance, costs, and debt calculations.
Identity Core Fetching
packages/rs-drive/src/drive/identity/fetch/mod.rs
Adds comprehensive test suite covering verification of identity existence, balance retrieval, optional balance fetching, and range-based balance queries.
Nonce Operations
packages/rs-drive/src/drive/identity/fetch/nonce/mod.rs
Adds tests exercising nonce retrieval for existing and non-existent identities, initial nonce values, updates, and fee calculations.
Partial Identity Fetching
packages/rs-drive/src/drive/identity/fetch/partial_identity/mod.rs
Adds server-feature gated tests for partial identity fetch operations across multiple identity path scenarios.
Revision Management
packages/rs-drive/src/drive/identity/fetch/revision/mod.rs
Introduces tests for identity revision retrieval, including initial revision, updated revision, and fee calculations.
Identity Insertion
packages/rs-drive/src/drive/identity/insert/add_new_identity/mod.rs
Adds two tests: one verifying duplicate non-masternode identity rejection and one verifying successful masternode re-insertion with key re-enabling.
Identity Path Helpers
packages/rs-drive/src/drive/identity/mod.rs
Adds unit tests for IdentityRootStructure conversions, display names, and identity/contract path construction functions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Hoppy tests are now in place,
Identity paths we boldly trace,
Balance, nonce, and revision clear,
Error cases we hold dear,
Coverage hops from file to file—complete! 🎯

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch test/drive-identity-review-fixes
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@QuantumExplorer
Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 16, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@QuantumExplorer
Copy link
Copy Markdown
Member Author

Closing due to merge conflicts. Will recreate on latest v3.1-dev.

@QuantumExplorer
Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 16, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@QuantumExplorer
Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 16, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Collaborator

@thepastaclaw thepastaclaw left a comment

Choose a reason for hiding this comment

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

Code Review

Clean test-improvement PR that addresses all 10 review comments from #3330. Two confirmed gaps: contract-info path tests omit the distinguishing path[2] assertion, and the ascending-range test doesn't actually verify ordering. Both are minor test-completeness issues, not correctness bugs.

Reviewed commit: 19e8df4

🟡 2 suggestion(s)

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-drive/src/drive/identity/mod.rs`:
- [SUGGESTION] lines 586-603: Contract-info path tests never assert path[2] (the IdentityContractInfo segment)
  Both `should_create_correct_contract_info_root_path` (line 586) and `should_create_correct_contract_info_group_path` (line 594) skip asserting `path[2]`. The function shows `path[2]` is `IdentityRootStructure::IdentityContractInfo` — the most semantically important segment that distinguishes these paths from other identity paths. Without this assertion, a bug that used the wrong `IdentityRootStructure` variant in position [2] would pass both tests.

In `packages/rs-drive/src/drive/identity/fetch/mod.rs`:
- [SUGGESTION] lines 480-519: should_fetch_balances_by_range_ascending doesn't verify ascending order
  The test fetches into a `BTreeMap<[u8; 32], u64>` which inherently sorts by key regardless of the DB ordering. The test asserts all 5 identities are present with correct balances, but never verifies that the `ascending: true` parameter actually produced ascending-ordered results. If the underlying query ignored the ascending flag, this test would still pass. Consider collecting into a `Vec` first and asserting the keys are sorted.

Comment on lines +586 to +603
fn should_create_correct_contract_info_root_path() {
let id = [5u8; 32];
let path = identity_contract_info_root_path(&id);
assert_eq!(path.len(), 3);
assert_eq!(path[0], &[RootTree::Identities as u8]);
assert_eq!(path[1], &id);
}

#[test]
fn should_create_correct_contract_info_group_path() {
let id = [6u8; 32];
let group_id = [7u8; 32];
let path = identity_contract_info_group_path(&id, &group_id);
assert_eq!(path.len(), 4);
assert_eq!(path[0], &[RootTree::Identities as u8]);
assert_eq!(path[1], &id);
assert_eq!(path[3], &group_id);
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Suggestion: Contract-info path tests never assert path[2] (the IdentityContractInfo segment)

Both should_create_correct_contract_info_root_path (line 586) and should_create_correct_contract_info_group_path (line 594) skip asserting path[2]. The function shows path[2] is IdentityRootStructure::IdentityContractInfo — the most semantically important segment that distinguishes these paths from other identity paths. Without this assertion, a bug that used the wrong IdentityRootStructure variant in position [2] would pass both tests.

Suggested change
fn should_create_correct_contract_info_root_path() {
let id = [5u8; 32];
let path = identity_contract_info_root_path(&id);
assert_eq!(path.len(), 3);
assert_eq!(path[0], &[RootTree::Identities as u8]);
assert_eq!(path[1], &id);
}
#[test]
fn should_create_correct_contract_info_group_path() {
let id = [6u8; 32];
let group_id = [7u8; 32];
let path = identity_contract_info_group_path(&id, &group_id);
assert_eq!(path.len(), 4);
assert_eq!(path[0], &[RootTree::Identities as u8]);
assert_eq!(path[1], &id);
assert_eq!(path[3], &group_id);
}
// In should_create_correct_contract_info_root_path (after line 591):
assert_eq!(path[2], Into::<&[u8; 1]>::into(IdentityRootStructure::IdentityContractInfo));
// In should_create_correct_contract_info_group_path (after line 601):
assert_eq!(path[2], Into::<&[u8; 1]>::into(IdentityRootStructure::IdentityContractInfo));

source: ['claude', 'codex']

🤖 Fix this with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-drive/src/drive/identity/mod.rs`:
- [SUGGESTION] lines 586-603: Contract-info path tests never assert path[2] (the IdentityContractInfo segment)
  Both `should_create_correct_contract_info_root_path` (line 586) and `should_create_correct_contract_info_group_path` (line 594) skip asserting `path[2]`. The function shows `path[2]` is `IdentityRootStructure::IdentityContractInfo` — the most semantically important segment that distinguishes these paths from other identity paths. Without this assertion, a bug that used the wrong `IdentityRootStructure` variant in position [2] would pass both tests.

Comment on lines +480 to +519
fn should_fetch_balances_by_range_ascending() {
let drive = setup_drive_with_initial_state_structure(None);
let platform_version = PlatformVersion::latest();

let identities: Vec<Identity> =
Identity::random_identities(5, 3, Some(42), platform_version)
.expect("expected random identities");

for identity in &identities {
drive
.add_new_identity(
identity.clone(),
false,
&BlockInfo::default(),
true,
None,
platform_version,
)
.expect("expected to add identity");
}

let balances: BTreeMap<[u8; 32], u64> = drive
.fetch_many_identity_balances_by_range::<BTreeMap<[u8; 32], u64>>(
None,
true,
10,
None,
platform_version,
)
.expect("should fetch balances by range");

assert_eq!(balances.len(), 5);

// Verify every inserted identity appears in the result with the correct balance
for identity in &identities {
let balance = balances
.get(&identity.id().to_buffer())
.expect("should have balance for inserted identity");
assert_eq!(*balance, identity.balance());
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Suggestion: should_fetch_balances_by_range_ascending doesn't verify ascending order

The test fetches into a BTreeMap<[u8; 32], u64> which inherently sorts by key regardless of the DB ordering. The test asserts all 5 identities are present with correct balances, but never verifies that the ascending: true parameter actually produced ascending-ordered results. If the underlying query ignored the ascending flag, this test would still pass. Consider collecting into a Vec first and asserting the keys are sorted.

source: ['codex']

🤖 Fix this with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-drive/src/drive/identity/fetch/mod.rs`:
- [SUGGESTION] lines 480-519: should_fetch_balances_by_range_ascending doesn't verify ascending order
  The test fetches into a `BTreeMap<[u8; 32], u64>` which inherently sorts by key regardless of the DB ordering. The test asserts all 5 identities are present with correct balances, but never verifies that the `ascending: true` parameter actually produced ascending-ordered results. If the underlying query ignored the ascending flag, this test would still pass. Consider collecting into a `Vec` first and asserting the keys are sorted.

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