Skip to content

MOSIP-25973 : Added testcases to improve coverage#804

Merged
anushasunkada merged 4 commits into
mosip:developfrom
GOKULRAJ136:dev-sonar
May 26, 2026
Merged

MOSIP-25973 : Added testcases to improve coverage#804
anushasunkada merged 4 commits into
mosip:developfrom
GOKULRAJ136:dev-sonar

Conversation

@GOKULRAJ136
Copy link
Copy Markdown

@GOKULRAJ136 GOKULRAJ136 commented May 25, 2026

Summary by CodeRabbit

  • Tests
    • Expanded unit coverage for biometric capture/auth, stream retrieval, quality/retry thresholds, and captured-biometrics logic with cleanup to avoid cross-test contamination.
    • Added comprehensive device-spec factory/helper/provider tests covering initialization, port/config handling, provider selection, availability, registry, and service probes.
    • New helper tests for JWT parsing/validation, payload/signature handling, HTTP responses, JPEG extraction, timeouts and transaction IDs.
    • Extended software-update tests for manifests, upgrades, backups, rollback and cleanup.
    • Refactored validator tests to control static state with lifecycle setup/teardown.

Review Change Stack

Signed-off-by: GOKULRAJ136 <110164849+GOKULRAJ136@users.noreply.github.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 25, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3c2bbbb8-d9c0-45f7-9ab3-f724e028a4fa

📥 Commits

Reviewing files that changed from the base of the PR and between 5e148ed and 64c245a.

📒 Files selected for processing (1)
  • registration/registration-services/src/test/java/io/mosip/registration/bio/service/test/BioServiceTest.java

Walkthrough

This PR adds extensive unit and reflection-based tests across BioService, MosipDeviceSpecificationFactory/Helper/Providers, and SoftwareUpdateHandler, including embedded HttpServer tests, ApplicationContext mutation helpers, and PowerMock/Whitebox-based private-method coverage.

Changes

MDM Biometric and Device Tests

Layer / File(s) Summary
BioService Capture and Configuration Tests
registration/registration-services/src/test/java/io/mosip/registration/bio/service/test/BioServiceTest.java
Mocks GlobalParamService, LocalConfigService, and MosipDeviceSpecificationProvider; injects config mocks into BioServiceImpl; adds ApplicationContext cleanup; tests modality/auth capture, stream retrieval/error paths, quality/retry/config lookups, supported attributes, and captured-biometric availability logic.
Factory Setup and Configuration Resolution
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java
Adds @BeforeAll/@AfterAll to initialize/clear ApplicationContext; tests initializeDeviceMap early-return, getPortFrom/getPortTo defaults and configured values, getLatestSpecVersion variants, and getMdsProvider lookup/exception paths.
Factory Device Availability and Registry Access
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java
Tests isDeviceAvailable provider-backed outcomes and IOException handling, unknown device-type handling, non-null registry/map getters, checkServiceAvailability with embedded HttpServer, and initializeDeviceMap port-range/threadpool branching.
Factory Private Method Testing
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java
Reflection-based tests for private getDeviceInfoResponse (local HTTP), addToDeviceInfoMap (insert/append), and initByPort (provider invocation and registry population); includes helpers to mutate ApplicationContext and inject mocked providers.
Helper JWT Parsing and Response Validation
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationHelperTest.java
NEW test class: tests JWT payload/signature extraction and error cases, validateJWTResponse success/failure, and getDeviceInfoDecoded SBI_1_0 vs non-SBI branches with mocked verification.
Helper Misc, Timing, and JPEG IO
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationHelperTest.java
Tests generateMDMTransactionId, buildUrl, getMapper, validateQualityScore, configuration-driven getMDMConnectionTimeout, validateResponseTimestamp, getJPEGByteArray extraction/timeout, and HTTP client response reading using an embedded HttpServer; includes private test helpers.
Provider 092 Private Methods and rCapture
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_092_ProviderImplTest.java
Updates @PrepareForTest to {CryptoUtil.class, Biometric.class}; adds Whitebox-invoked private-method tests (exception/device-type/sub-id mapping, getBioDevice null), decoding-failure path, READY-status availability test, and an rCapture happy-path with crypto/base64 and biometric attribute-name mocks.
Provider SBI_1_0 Stream and Capture Operations
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java
Adjusts imports and PowerMock targets; adds tests for stream null/content cases, rCapture exception-wrapping and happy-path yielding BiometricsDto, multiple isDeviceAvailable true-branches and failure branch, and getBioDevice field population from decoded payload.

Software Update and DB Upgrade Tests

Layer / File(s) Summary
SQL Execution and Manifest Handling
registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateHandlerTest.java
Extends @PowerMockIgnore/@PrepareForTest, adds AuditManagerService mock and @After cleanup; tests executeSqlFile multi-version ordering, full-sync entity handling, skipping older entries, and getJarChecksum null-manifest behavior.
Derby DB Version-Zero Update Scenarios
registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateHandlerTest.java
Covers updateDerbyDB version-zero cases: missing backup folder, existing backup without manifests, and backup with MANIFEST.MF; tests doSoftwareUpgrade backup-failure non-propagation.
Upgrade Download, Copy Suppression, and Rollback Flows
registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateHandlerTest.java
Tests hasUpdate with mocked download XML returning newer version, doSoftwareUpgrade manifest-entry download path with FileUtils.copyFile suppressed, updateDerbyDB rollback when SQL executions fail, and successful doSoftwareUpgrade when copy is suppressed but server manifest is pre-seeded.
ClientSetupValidator Reflection and Static Reset
registration/registration-services/src/test/java/io/mosip/registration/test/update/ClientSetupValidatorTest.java
Removes @InjectMocks use, instantiates ClientSetupValidator via Whitebox.newInstance, adds resetStaticFields() used in @Before/@After, and updates tests to set static configuration via ReflectionTestUtils for deterministic state.

🎯 3 (Moderate) | ⏱️ ~25 minutes

🐰 In burrows of tests, we hop with glee,
MockServers and Mocks dance wild and free,
Device specs and JWTs, all validated true,
Biometrics captured, updates pass through!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main objective: adding test cases to improve code coverage across multiple test files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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.

Copy link
Copy Markdown

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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@registration/registration-services/src/test/java/io/mosip/registration/bio/service/test/BioServiceTest.java`:
- Line 561: Tests in BioServiceTest mutate the global ApplicationContext.map()
(e.g., removal of RegistrationConstants.QUALITY_CHECK_WITH_SDK) which can leak
state across tests; update the test class to reset any keys it changes by adding
an `@After` (or `@AfterEach`) cleanup method that restores or clears those specific
keys, or wrap each mutation in a try-finally that restores the original value,
ensuring ApplicationContext.map() is returned to its prior state after each
test; reference the mutations around ApplicationContext.map() and keys like
RegistrationConstants.QUALITY_CHECK_WITH_SDK when implementing the cleanup.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java`:
- Line 678: The test constructs an MDMRequestDto with a modality typo
"FINGERPRINT_SLAB_LEFT" which should be the slap modality; update the
MDMRequestDto instantiation in MosipDeviceSpecification_SBI_1_0_ProviderImplTest
(the line creating new MDMRequestDto(...)) to use the correct modality string
"FINGERPRINT_SLAP_LEFT" so the rCapture happy-path maps to the intended slap
behavior.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java`:
- Around line 56-65: The test initializes the ApplicationContext singleton in
setupApplicationContext() by reflectively setting the private static field
applicationContext but never resets it, risking state leakage between tests; add
an `@AfterAll` teardown method (e.g., tearDownApplicationContext) that
reflectively clears or nulls the ApplicationContext.applicationContext field or
invokes a reset/clear method on ApplicationContext to restore clean state
between test classes so internal maps mutated by tests are cleared.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationHelperTest.java`:
- Around line 223-226: The test
getMDMConnectionTimeout_allNull_returnsDefault10000 is order-dependent because
it assumes ApplicationContext.applicationMap has no timeout keys; modify the
test to make it deterministic by explicitly clearing or resetting
ApplicationContext.applicationMap (or removing the specific timeout keys) before
calling MosipDeviceSpecificationHelper.getMDMConnectionTimeout("MOSIPDINFO"),
and if other tests rely on the map, save and restore the original map state
around the test so the global state is not mutated for other tests.
- Around line 364-379: withApplicationMap currently only removes the inserted
key on success and will skip cleanup if op.apply throws and will also clobber
any pre-existing value; change the contract so the op returns both the inserted
key and the previous value (e.g., have MapOp.apply return a
Map.Entry<String,Object> or a small KeyPrev record instead of String), then in
withApplicationMap always run a finally block that uses the returned previous
value to restore state: if previous==null remove(key) else put(key, previous).
Update the MapOp interface and all callers (tests) accordingly so cleanup always
runs and original values are restored even when op.apply throws.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateHandlerTest.java`:
- Around line 84-88: The tests delete and create files in the repository root
and src/test/resources/sql which makes them order-dependent and unsafe; change
the tests in SoftwareUpdateHandlerTest (the doSoftwareUpgrade test cases) to use
an isolated temporary directory per test (e.g., JUnit TemporaryFolder or
Files.createTempDirectory) for creating MANIFEST.MF and SQL artifacts and pass
that temp path into the code-under-test or mock the file-system access, and
update the cleanup() method to only remove files inside that temp directory (or
rely on TemporaryFolder to auto-clean) instead of deleting "MANIFEST.MF" in the
project root.
- Around line 273-283: The tests currently only assert "no exception" — update
each named test to verify the intended side effects: in
doSoftwareUpgrade_backupFails_doesNotPropagateException, after calling
softwareUpdateHandler.doSoftwareUpgrade() verify interactions such as
Mockito.verify(globalParamService).update(...) and that FileUtils.copyFile (the
static mock) was/was-not invoked as appropriate given the simulated backup
failure; in doSoftwareUpgrade_withManifestEntries_downloadsFiles assert
manifest.getMainAttributes() was used and verify the download/extract behavior
(verify the method that performs downloads or the static FileUtils.copyFile
calls); in updateDerbyDB_withAllSqlFailing_triggersDbRollback call
softwareUpdateHandler.updateDerbyDB(...) and verify a rollback on the DB
interaction (e.g., verify connection.rollback() or the transaction manager
rollback mock was invoked); and in
doSoftwareUpgrade_withSuppressedCopyFile_callsUpdate assert that
globalParamService.update(...) was called with expected args when
FileUtils.copyFile is suppressed. Use the existing mocks (manifest,
globalParamService, static FileUtils) and Mockito.verify calls to make the
asserted side effects explicit.
- Around line 202-217: The test
executeSqlFile_multipleVersions_executesAllInOrder currently only asserts
atLeast(2) calls to globalParamService.update but promises ordering; change the
assertion to verify call order by creating an InOrder for the mock
(Mockito.inOrder(globalParamService)) and then verify() the sequential update
calls against software version values (e.g., verify first update invoked with
RegistrationConstants.SERVICES_VERSION_KEY and a value containing "0.10.0", then
verify the next update with a value containing "0.11.0") so the test asserts the
updates happen in the expected order after calling
softwareUpdateHandler.executeSqlFile.
- Around line 213-214: The test uses Assert.assertSame to compare the SQL
success message constant and the actual message
(RegistrationConstants.SQL_EXECUTION_SUCCESS vs
response.getSuccessResponseDTO().getMessage()), which checks object identity;
change these to Assert.assertEquals for value equality at the three assertions
that compare RegistrationConstants.SQL_EXECUTION_SUCCESS with
response.getSuccessResponseDTO().getMessage() (occurrences around the assertions
currently using Assert.assertSame). Ensure all three instances (the assertions
comparing the constant and response message) are updated to Assert.assertEquals.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: cba1fbb9-0040-49a8-a438-9d4190ae7ec1

📥 Commits

Reviewing files that changed from the base of the PR and between ab362c1 and b0dc44e.

📒 Files selected for processing (6)
  • registration/registration-services/src/test/java/io/mosip/registration/bio/service/test/BioServiceTest.java
  • registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java
  • registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationHelperTest.java
  • registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_092_ProviderImplTest.java
  • registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java
  • registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateHandlerTest.java

Signed-off-by: GOKULRAJ136 <110164849+GOKULRAJ136@users.noreply.github.com>
Signed-off-by: GOKULRAJ136 <110164849+GOKULRAJ136@users.noreply.github.com>
Copy link
Copy Markdown

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
registration/registration-services/src/test/java/io/mosip/registration/test/update/ClientSetupValidatorTest.java (1)

152-153: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Consider updating existing tests to use the class-level pattern for static fields.

Lines 152–153, 169–170, and 185–186 set static fields (serverManifest, localManifest) using the instance form ReflectionTestUtils.setField(clientSetupValidator, ...). While this works, it is inconsistent with the new pattern introduced at lines 120 and 127–129, which correctly uses ReflectionTestUtils.setField(ClientSetupValidator.class, ...) for static fields.

For clarity and consistency, consider refactoring these older tests to use the class form.

♻️ Example refactor for consistency
 Manifest manifest = getManifest();
-ReflectionTestUtils.setField(clientSetupValidator, "serverManifest", manifest);
-ReflectionTestUtils.setField(clientSetupValidator, "localManifest", manifest);
+ReflectionTestUtils.setField(ClientSetupValidator.class, "serverManifest", manifest);
+ReflectionTestUtils.setField(ClientSetupValidator.class, "localManifest", manifest);

Apply similar changes at lines 169–170 and 185–186.

Also applies to: 169-170, 185-186

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/update/ClientSetupValidatorTest.java`
around lines 152 - 153, Update the tests to set static fields via the
class-level ReflectionTestUtils API: replace instance-based
ReflectionTestUtils.setField(clientSetupValidator, "serverManifest", manifest)
and ReflectionTestUtils.setField(clientSetupValidator, "localManifest",
manifest) with ReflectionTestUtils.setField(ClientSetupValidator.class,
"serverManifest", manifest) and
ReflectionTestUtils.setField(ClientSetupValidator.class, "localManifest",
manifest) (apply the same change for the occurrences around lines 169–170 and
185–186) so static fields on ClientSetupValidator are consistently modified via
the class reference.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@registration/registration-services/src/test/java/io/mosip/registration/test/update/ClientSetupValidatorTest.java`:
- Around line 87-96: The resetStaticFields() helper currently clears several
ClientSetupValidator static fields but omits the messages Stack<String>; update
resetStaticFields() to also reset the ClientSetupValidator.messages static field
(e.g., set it to a new empty Stack or null) so tests don’t see leftover entries
— locate the method resetStaticFields() in the test class and add a
ReflectionTestUtils.setField(ClientSetupValidator.class, "messages", <empty
Stack or null>) call to clear that static state.

---

Outside diff comments:
In
`@registration/registration-services/src/test/java/io/mosip/registration/test/update/ClientSetupValidatorTest.java`:
- Around line 152-153: Update the tests to set static fields via the class-level
ReflectionTestUtils API: replace instance-based
ReflectionTestUtils.setField(clientSetupValidator, "serverManifest", manifest)
and ReflectionTestUtils.setField(clientSetupValidator, "localManifest",
manifest) with ReflectionTestUtils.setField(ClientSetupValidator.class,
"serverManifest", manifest) and
ReflectionTestUtils.setField(ClientSetupValidator.class, "localManifest",
manifest) (apply the same change for the occurrences around lines 169–170 and
185–186) so static fields on ClientSetupValidator are consistently modified via
the class reference.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2aac2bd3-3f85-4797-b9de-2bd70cc7ff01

📥 Commits

Reviewing files that changed from the base of the PR and between 40f6aa4 and 5e148ed.

📒 Files selected for processing (1)
  • registration/registration-services/src/test/java/io/mosip/registration/test/update/ClientSetupValidatorTest.java

Signed-off-by: GOKULRAJ136 <110164849+GOKULRAJ136@users.noreply.github.com>
@anushasunkada anushasunkada merged commit e24aa60 into mosip:develop May 26, 2026
9 checks passed
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