diff --git a/android/clientmanager/src/main/java/io/mosip/registration/clientmanager/service/RegistrationServiceImpl.java b/android/clientmanager/src/main/java/io/mosip/registration/clientmanager/service/RegistrationServiceImpl.java index 3b33c4983..f2a8e7b8f 100644 --- a/android/clientmanager/src/main/java/io/mosip/registration/clientmanager/service/RegistrationServiceImpl.java +++ b/android/clientmanager/src/main/java/io/mosip/registration/clientmanager/service/RegistrationServiceImpl.java @@ -125,19 +125,19 @@ public class RegistrationServiceImpl implements RegistrationService { @Inject public RegistrationServiceImpl(Context context, PacketWriterService packetWriterService, - RegistrationRepository registrationRepository, - MasterDataService masterDataService, - IdentitySchemaRepository identitySchemaRepository, - ClientCryptoManagerService clientCryptoManagerService, - KeyStoreRepository keyStoreRepository, - GlobalParamRepository globalParamRepository, - AuditManagerService auditManagerService, - RegistrationCenterRepository registrationCenterRepository, - LocationValidationService locationValidationService, - Provider preRegistrationDataSyncServiceProvider, - Biometrics095Service biometricService, - PacketService packetService, - PreCheckValidatorService preCheckValidatorService) { + RegistrationRepository registrationRepository, + MasterDataService masterDataService, + IdentitySchemaRepository identitySchemaRepository, + ClientCryptoManagerService clientCryptoManagerService, + KeyStoreRepository keyStoreRepository, + GlobalParamRepository globalParamRepository, + AuditManagerService auditManagerService, + RegistrationCenterRepository registrationCenterRepository, + LocationValidationService locationValidationService, + Provider preRegistrationDataSyncServiceProvider, + Biometrics095Service biometricService, + PacketService packetService, + PreCheckValidatorService preCheckValidatorService) { this.context = context; this.registrationDto = null; this.packetWriterService = packetWriterService; @@ -158,16 +158,17 @@ public RegistrationServiceImpl(Context context, PacketWriterService packetWriter @Override public void approveRegistration(Registration registration) { - //TODO + // TODO } @Override public void rejectRegistration(Registration registration) { - //TODO + // TODO } @Override - public RegistrationDto startRegistration(@NonNull List languages, String flowType, String process, Double latitude, Double longitude) throws Exception { + public RegistrationDto startRegistration(@NonNull List languages, String flowType, String process, + Double latitude, Double longitude) throws Exception { if (registrationDto != null) { registrationDto.cleanup(); } @@ -192,10 +193,11 @@ public RegistrationDto startRegistration(@NonNull List languages, String String timestamp = DateUtils.formatToISOStringWithoutMillis(LocalDateTime.now(ZoneOffset.UTC)); timestamp = timestamp.replaceAll(":|T|Z|-", ""); - String rid = String.format("%s%s10031%s", centerMachineDto.getCenterId(), centerMachineDto.getMachineId(), timestamp); + String rid = String.format("%s%s10031%s", centerMachineDto.getCenterId(), centerMachineDto.getMachineId(), + timestamp); Map bioThresholds = new HashMap<>(); - for(Modality modality : Modality.values()) { + for (Modality modality : Modality.values()) { bioThresholds.put(modality, getAttemptsCount(modality)); } this.registrationDto = new RegistrationDto(rid, flowType, process, version, languages, bioThresholds, rid); @@ -204,10 +206,12 @@ public RegistrationDto startRegistration(@NonNull List languages, String // Validate GPS location if flag is enabled (even if coordinates are null) try { + if (preCheckValidatorService != null) { preCheckValidatorService.validateCenterToMachineDistance(longitude, latitude); - } catch (ClientCheckedException e) { - Log.e(TAG, "Location validation failed", e); - throw e; + } + } catch (ClientCheckedException e) { + Log.e(TAG, "Location validation failed", e); + throw e; } SharedPreferences.Editor editor = this.context.getSharedPreferences(this.context.getString(R.string.app_name), @@ -238,47 +242,54 @@ public void submitRegistrationDto(String makerName) throws Exception { this.registrationDto.setRId(newAppId); } List selectedHandles = this.globalParamRepository.getSelectedHandles(); - if(selectedHandles != null) { + if (selectedHandles != null) { if (this.registrationDto.getFlowType().equals("NEW") || this.registrationDto.getFlowType().equals("Update")) { this.registrationDto.getDemographics().put("selectedHandles", selectedHandles); } } -// try { - String individualBiometricsFieldId = this.globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.INDIVIDUAL_BIOMETRICS_ID); - String serverVersion = this.globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION); + // try { + String individualBiometricsFieldId = this.globalParamRepository + .getCachedStringGlobalParam(RegistrationConstants.INDIVIDUAL_BIOMETRICS_ID); + String serverVersion = this.globalParamRepository + .getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION); for (String fieldName : this.registrationDto.getDemographics().keySet()) { switch (this.registrationDto.getFlowType()) { case "Update": - if (this.registrationDto.getDemographics().get(fieldName) != null && (this.registrationDto.getUpdatableFields().contains(fieldName) || - fieldName.equals("UIN"))) - packetWriterService.setField(this.registrationDto.getRId(), fieldName, this.registrationDto.getDemographics().get(fieldName)); + if (this.registrationDto.getDemographics().get(fieldName) != null + && (this.registrationDto.getUpdatableFields().contains(fieldName) || + fieldName.equals("UIN"))) + packetWriterService.setField(this.registrationDto.getRId(), fieldName, + this.registrationDto.getDemographics().get(fieldName)); break; case "Correction": case "Lost": case "NEW": if (this.registrationDto.getDemographics().get(fieldName) != null) - packetWriterService.setField(this.registrationDto.getRId(), fieldName, this.registrationDto.getDemographics().get(fieldName)); + packetWriterService.setField(this.registrationDto.getRId(), fieldName, + this.registrationDto.getDemographics().get(fieldName)); break; } } - String format = globalParamRepository.getCachedStringDocType(); - String formatToCheck = format != null ? format : "pdf"; - this.registrationDto.getAllDocumentFields().forEach(entry -> { - Document document = new Document(); - document.setType(entry.getValue().getType()); - document.setFormat(entry.getValue().getFormat()); - document.setRefNumber(entry.getValue().getRefNumber()); - document.setDocument((formatToCheck.equalsIgnoreCase(entry.getValue().getFormat()))?combineByteArray(entry.getValue().getContent()):convertImageToPDF(entry.getValue().getContent())); - packetWriterService.setDocument(this.registrationDto.getRId(), entry.getKey(), document); - packetWriterService.addMetaInfo(this.registrationDto.getRId(),"documents", document); - }); + String format = globalParamRepository.getCachedStringDocType(); + String formatToCheck = format != null ? format : "pdf"; + this.registrationDto.getAllDocumentFields().forEach(entry -> { + Document document = new Document(); + document.setType(entry.getValue().getType()); + document.setFormat(entry.getValue().getFormat()); + document.setRefNumber(entry.getValue().getRefNumber()); + document.setDocument((formatToCheck.equalsIgnoreCase(entry.getValue().getFormat())) + ? combineByteArray(entry.getValue().getContent()) + : convertImageToPDF(entry.getValue().getContent())); + packetWriterService.setDocument(this.registrationDto.getRId(), entry.getKey(), document); + packetWriterService.addMetaInfo(this.registrationDto.getRId(), "documents", document); + }); - if (serverVersion!=null && serverVersion.startsWith("1.1.5")) { - this.registrationDto.getBestBiometrics(individualBiometricsFieldId, Modality.EXCEPTION_PHOTO).forEach( b -> { + if (serverVersion != null && serverVersion.startsWith("1.1.5")) { + this.registrationDto.getBestBiometrics(individualBiometricsFieldId, Modality.EXCEPTION_PHOTO).forEach(b -> { Document document = new Document(); document.setType("EOP"); document.setFormat("jpg"); @@ -289,7 +300,7 @@ public void submitRegistrationDto(String makerName) throws Exception { } // Process biometrics and add metadata to packet - setBiometrics(this.registrationDto); + setBiometrics(this.registrationDto); CenterMachineDto centerMachineDto = this.masterDataService.getRegistrationCenterMachineDetails(); @@ -303,20 +314,18 @@ public void submitRegistrationDto(String makerName) throws Exception { this.registrationDto.getProcess(), true, centerMachineDto.getMachineRefId()); - - if (containerPath != null || !containerPath.trim().isEmpty()) { String packetId = containerPath.substring(containerPath.lastIndexOf("/") + 1); - packetId = packetId.replace(".zip", ""); - this.registrationDto.setPacketId(packetId); + packetId = packetId.replace(".zip", ""); + this.registrationDto.setPacketId(packetId); } JSONObject additionalInfo = new JSONObject(); additionalInfo.put("langCode", this.registrationDto.getSelectedLanguages().get(0)); - //TODO add name, phone and email in additional info + // TODO add name, phone and email in additional info List fullName = new ArrayList<>(); String fullNameKey = getKey(this.registrationDto, RegistrationConstants.UI_SCHEMA_SUBTYPE_FULL_NAME); - if(fullNameKey != null) { + if (fullNameKey != null) { List fullNameKeys = Arrays.asList(fullNameKey.split(RegistrationConstants.COMMA)); for (String key : fullNameKeys) { Object fullNameObj = this.registrationDto.getDemographics().get(key); @@ -324,20 +333,25 @@ public void submitRegistrationDto(String makerName) throws Exception { } } - Object emailObj = this.registrationDto.getDemographics().get(getKey(this.registrationDto, RegistrationConstants.UI_SCHEMA_SUBTYPE_EMAIL)); - Object phoneObj = this.registrationDto.getDemographics().get(getKey(this.registrationDto, RegistrationConstants.UI_SCHEMA_SUBTYPE_PHONE)); + Object emailObj = this.registrationDto.getDemographics() + .get(getKey(this.registrationDto, RegistrationConstants.UI_SCHEMA_SUBTYPE_EMAIL)); + Object phoneObj = this.registrationDto.getDemographics() + .get(getKey(this.registrationDto, RegistrationConstants.UI_SCHEMA_SUBTYPE_PHONE)); additionalInfo.put("name", String.join(" ", fullName)); additionalInfo.put("email", getAdditionalInfo(emailObj)); additionalInfo.put("phone", getAdditionalInfo(phoneObj)); registrationRepository.insertRegistration(this.registrationDto.getPacketId(), containerPath, - centerMachineDto.getCenterId(), this.registrationDto.getProcess(), additionalInfo, this.registrationDto.getAdditionalInfoRequestId(), this.registrationDto.getRId(), this.registrationDto.getApplicationId()); + centerMachineDto.getCenterId(), this.registrationDto.getProcess(), additionalInfo, + this.registrationDto.getAdditionalInfoRequestId(), this.registrationDto.getRId(), + this.registrationDto.getApplicationId()); // Auto-approve when supervisor approval is disabled (flag not "Y") String supervisorApprovalFlag = globalParamRepository.getCachedStringGlobalParam( RegistrationConstants.SUPERVISOR_APPROVAL_CONFIG_FLAG); - if (supervisorApprovalFlag != null && !RegistrationConstants.ENABLE.equalsIgnoreCase(supervisorApprovalFlag.trim())) { + if (supervisorApprovalFlag != null + && !RegistrationConstants.ENABLE.equalsIgnoreCase(supervisorApprovalFlag.trim())) { registrationRepository.updateStatus(this.registrationDto.getPacketId(), null, PacketClientStatus.APPROVED.name()); } @@ -355,14 +369,15 @@ public void submitRegistrationDto(String makerName) throws Exception { preRegistrationDataSyncServiceProvider.get().deletePreRegRecords(responseDTO, preRegistrationLists); } -// } finally { + // } finally { clearRegistration(); -// } + // } } private String getKey(RegistrationDto registrationDTO, String subType) throws Exception { List key = new ArrayList<>(); - List schemaFields = identitySchemaRepository.getProcessSpecFields(context, registrationDTO.getProcess()); + List schemaFields = identitySchemaRepository.getProcessSpecFields(context, + registrationDTO.getProcess()); for (FieldSpecDto schemaField : schemaFields) { if (schemaField.getSubType() != null && schemaField.getSubType().equalsIgnoreCase(subType)) { if (subType.equalsIgnoreCase(RegistrationConstants.UI_SCHEMA_SUBTYPE_FULL_NAME)) { @@ -388,11 +403,15 @@ private byte[] combineByteArray(List byteList) { } private String getAdditionalInfo(Object fieldValue) { - if(fieldValue == null) { return null; } + if (fieldValue == null) { + return null; + } if (fieldValue instanceof List) { Optional demoValueInRequiredLang = ((List) fieldValue).stream() - .filter(valueDTO -> valueDTO.getLanguage().equals(this.registrationDto.getSelectedLanguages().get(0))).findFirst(); + .filter(valueDTO -> valueDTO.getLanguage() + .equals(this.registrationDto.getSelectedLanguages().get(0))) + .findFirst(); if (demoValueInRequiredLang.isPresent()) { return demoValueInRequiredLang.get().getValue(); @@ -431,23 +450,23 @@ public void clearRegistration() { private BiometricRecord getBiometricRecord(String fieldId, String serverVersion) { BiometricRecord biometricRecord = new BiometricRecord(); - this.registrationDto.getBestBiometrics(fieldId, Modality.FINGERPRINT_SLAB_LEFT).forEach( b -> { + this.registrationDto.getBestBiometrics(fieldId, Modality.FINGERPRINT_SLAB_LEFT).forEach(b -> { biometricRecord.getSegments().add(buildBIR(b)); }); - this.registrationDto.getBestBiometrics(fieldId, Modality.FINGERPRINT_SLAB_RIGHT).forEach( b -> { + this.registrationDto.getBestBiometrics(fieldId, Modality.FINGERPRINT_SLAB_RIGHT).forEach(b -> { biometricRecord.getSegments().add(buildBIR(b)); }); - this.registrationDto.getBestBiometrics(fieldId, Modality.FINGERPRINT_SLAB_THUMBS).forEach( b -> { + this.registrationDto.getBestBiometrics(fieldId, Modality.FINGERPRINT_SLAB_THUMBS).forEach(b -> { biometricRecord.getSegments().add(buildBIR(b)); }); - this.registrationDto.getBestBiometrics(fieldId, Modality.IRIS_DOUBLE).forEach( b -> { + this.registrationDto.getBestBiometrics(fieldId, Modality.IRIS_DOUBLE).forEach(b -> { biometricRecord.getSegments().add(buildBIR(b)); }); - this.registrationDto.getBestBiometrics(fieldId, Modality.FACE).forEach( b -> { + this.registrationDto.getBestBiometrics(fieldId, Modality.FACE).forEach(b -> { biometricRecord.getSegments().add(buildBIR(b)); }); if (!serverVersion.startsWith("1.1.5")) { - this.registrationDto.getBestBiometrics(fieldId, Modality.EXCEPTION_PHOTO).forEach( b -> { + this.registrationDto.getBestBiometrics(fieldId, Modality.EXCEPTION_PHOTO).forEach(b -> { biometricRecord.getSegments().add(buildBIR(b)); }); this.registrationDto.EXCEPTIONS.forEach((key, value) -> { @@ -463,8 +482,9 @@ private BiometricRecord getBiometricRecord(String fieldId, String serverVersion) int numOfRetries = 0; double sdkScore = 0; float qualityScore = 0; - BiometricsDto exceptionBiometricDto = - new BiometricsDto(modality.getSingleType().value(), bioSubtype, bioValue, specVersion, isException, decodedBioResponse, signature, isForceCaptured, numOfRetries, sdkScore, qualityScore); + BiometricsDto exceptionBiometricDto = new BiometricsDto(modality.getSingleType().value(), + bioSubtype, bioValue, specVersion, isException, decodedBioResponse, signature, + isForceCaptured, numOfRetries, sdkScore, qualityScore); biometricRecord.getSegments().add(buildBIR(exceptionBiometricDto)); }); }); @@ -474,24 +494,27 @@ private BiometricRecord getBiometricRecord(String fieldId, String serverVersion) private void addMetaInfoMap(String centerId, String machineId, String makerId) throws Exception { String rid = this.registrationDto.getRId(); - //machine metaInfo + // machine metaInfo Map metaData = new LinkedHashMap<>(); metaData.put(PacketManagerConstant.META_MACHINE_ID, machineId); metaData.put(PacketManagerConstant.META_CENTER_ID, centerId); metaData.put(PacketManagerConstant.META_KEYINDEX, this.clientCryptoManagerService.getClientKeyIndex()); metaData.put(PacketManagerConstant.META_REGISTRATION_ID, rid); - String appIdForMeta = this.registrationDto.getApplicationId() == null || this.registrationDto.getApplicationId().trim().isEmpty() - ? rid : this.registrationDto.getApplicationId(); + String appIdForMeta = this.registrationDto.getApplicationId() == null + || this.registrationDto.getApplicationId().trim().isEmpty() + ? rid + : this.registrationDto.getApplicationId(); metaData.put(PacketManagerConstant.META_APPLICATION_ID, appIdForMeta); metaData.put(PacketManagerConstant.META_CREATION_DATE, DateUtils.formatToISOString(LocalDateTime.now(ZoneOffset.UTC))); metaData.put(PacketManagerConstant.META_CLIENT_VERSION, BuildConfig.CLIENT_VERSION); metaData.put(PacketManagerConstant.META_REGISTRATION_TYPE, this.registrationDto.getProcess().toUpperCase()); metaData.put(PacketManagerConstant.META_PRE_REGISTRATION_ID, null); - metaData.put("langCodes", String.join(RegistrationConstants.COMMA, this.registrationDto.getSelectedLanguages())); + metaData.put("langCodes", + String.join(RegistrationConstants.COMMA, this.registrationDto.getSelectedLanguages())); packetWriterService.addMetaInfo(rid, "metaData", getLabelValueDTOListString(metaData)); - //Operators metaInfo + // Operators metaInfo metaData = new LinkedHashMap<>(); metaData.put(PacketManagerConstant.META_OFFICER_ID, makerId); metaData.put(PacketManagerConstant.META_OFFICER_BIOMETRIC_FILE, null); @@ -503,20 +526,21 @@ private void addMetaInfoMap(String centerId, String machineId, String makerId) t metaData.put(PacketManagerConstant.META_OFFICER_PIN, BOOLEAN_FALSE); metaData.put(PacketManagerConstant.META_SUPERVISOR_OTP, BOOLEAN_FALSE); metaData.put(PacketManagerConstant.META_OFFICER_OTP, BOOLEAN_FALSE); - packetWriterService.addMetaInfo(rid, PacketManagerConstant.META_INFO_OPERATIONS_DATA, getLabelValueDTOListString(metaData)); + packetWriterService.addMetaInfo(rid, PacketManagerConstant.META_INFO_OPERATIONS_DATA, + getLabelValueDTOListString(metaData)); - //other metaInfo + // other metaInfo GeoLocationDto geoLocation = this.registrationDto.getGeoLocationDto(); packetWriterService.addMetaInfo(rid, PacketManagerConstant.META_LATITUDE, - geoLocation != null ? String.valueOf(geoLocation.getLatitude()) : "null"); + geoLocation != null ? String.valueOf(geoLocation.getLatitude()) : "null"); packetWriterService.addMetaInfo(rid, PacketManagerConstant.META_LONGITUDE, - geoLocation != null ? String.valueOf(geoLocation.getLongitude()) : "null"); + geoLocation != null ? String.valueOf(geoLocation.getLongitude()) : "null"); packetWriterService.addMetaInfo(rid, "checkSum", "{}"); packetWriterService.addMetaInfo(rid, PacketManagerConstant.REGISTRATIONID, rid); - //biometric device details + // biometric device details List> capturedRegisteredDevices = new ArrayList<>(); - for(Modality modality : this.biometricService.BIO_DEVICES.keySet()) { + for (Modality modality : this.biometricService.BIO_DEVICES.keySet()) { Map deviceInfo = (Map) this.biometricService.BIO_DEVICES.get(modality); if (deviceInfo != null) { capturedRegisteredDevices.add(deviceInfo); @@ -525,7 +549,6 @@ private void addMetaInfoMap(String centerId, String machineId, String makerId) t } } - packetWriterService.addMetaInfo(rid, "capturedRegisteredDevices", capturedRegisteredDevices); } @@ -540,12 +563,11 @@ private List> getLabelValueDTOListString(Map return labelValueMap; } - public List> getAudits() { List> audits = new ArrayList<>(); String savedPoint = globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.AUDIT_EXPORTED_TILL); - List list = auditManagerService.getAuditLogs(savedPoint==null ? 0 : Long.parseLong(savedPoint)); - for(Audit audit : list) { + List list = auditManagerService.getAuditLogs(savedPoint == null ? 0 : Long.parseLong(savedPoint)); + for (Audit audit : list) { Map auditMap = new HashMap<>(); auditMap.put("uuid", String.valueOf(audit.getUuid())); auditMap.put("createdAt", DateUtils.parseEpochToISOString(audit.getCreatedAt())); @@ -568,22 +590,25 @@ public List> getAudits() { audits.add(auditMap); } globalParamRepository.saveGlobalParam(RegistrationConstants.AUDIT_EXPORTED_TILL, - list.isEmpty() ? null : String.valueOf(list.get(list.size()-1).getActionTimeStamp())); + list.isEmpty() ? null : String.valueOf(list.get(list.size() - 1).getActionTimeStamp())); return audits; } private void doPreChecksBeforeRegistration(CenterMachineDto centerMachineDto) throws Exception { - //free space validation + // free space validation if (validatingDiskSpace()) { throw new ClientCheckedException("PAK_DISK_SPACE_LOW"); } - //is machine and center active + // is machine and center active if (centerMachineDto == null || !centerMachineDto.getCenterStatus() || !centerMachineDto.getMachineStatus()) throw new ClientCheckedException(context, R.string.err_007); - // validate sync status - checks if all sync jobs ran within configured time limits - preCheckValidatorService.validateSyncStatus(); + // validate sync status - checks if all sync jobs ran within configured time + // limits + if (preCheckValidatorService != null) { + preCheckValidatorService.validateSyncStatus(); + } // registered packet approval time breach check if (packetService != null && packetService.isRegisteredPacketApprovalTimeBreached()) { @@ -633,11 +658,9 @@ private boolean validatingDiskSpace() { return usableSpace < allowedDiskSpaceSizeInBytes; } - - private byte[] convertImageToPDF(List images) { try (PDDocument pdDocument = new PDDocument(); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { for (byte[] image : images) { PDPage pdPage = new PDPage(); Log.i(TAG, "image size after compression :" + image.length); @@ -660,39 +683,40 @@ private byte[] convertImageToPDF(List images) { } private byte[] getCompressedImage(byte[] image, Float compressionQuality) { - //TODO compress image + // TODO compress image return image; } private static int[] getScaledDimension(int originalWidth, int originalHeight, int boundWidth, - int boundHeight) { + int boundHeight) { int new_width = originalWidth; int new_height = originalHeight; // first check if we need to scale width if (originalWidth > boundWidth) { - //scale width to fit + // scale width to fit new_width = boundWidth; - //scale height to maintain aspect ratio + // scale height to maintain aspect ratio new_height = (new_width * originalHeight) / originalWidth; } // then check if we need to scale even with the new height if (new_height > boundHeight) { - //scale height to fit instead + // scale height to fit instead new_height = boundHeight; - //scale width to maintain aspect ratio + // scale width to maintain aspect ratio new_width = (new_height * originalWidth) / originalHeight; } - return new int[]{new_width, new_height}; + return new int[] { new_width, new_height }; } public BIR buildBIR(BiometricsDto biometricsDto) { - if(biometricsDto == null) + if (biometricsDto == null) return null; SingleType singleType = SingleType.fromValue(biometricsDto.getModality()); - byte[] iso = biometricsDto.getBioValue() == null ? null : CryptoUtil.base64decoder.decode(biometricsDto.getBioValue()); + byte[] iso = biometricsDto.getBioValue() == null ? null + : CryptoUtil.base64decoder.decode(biometricsDto.getBioValue()); // Format RegistryIDType birFormat = new RegistryIDType(); birFormat.setOrganization(PacketManagerConstant.CBEFF_DEFAULT_FORMAT_ORG); @@ -710,17 +734,19 @@ public BIR buildBIR(BiometricsDto biometricsDto) { qualityType.setScore((long) biometricsDto.getQualityScore()); VersionType versionType = new VersionType(1, 1); - String payLoad = null; if (iso != null) { - int bioValueKeyIndex = biometricsDto.getDecodedBioResponse().indexOf(PacketManagerConstant.BIOVALUE_KEY) + (PacketManagerConstant.BIOVALUE_KEY.length() + 1); + int bioValueKeyIndex = biometricsDto.getDecodedBioResponse().indexOf(PacketManagerConstant.BIOVALUE_KEY) + + (PacketManagerConstant.BIOVALUE_KEY.length() + 1); int bioValueStartIndex = biometricsDto.getDecodedBioResponse().indexOf('"', bioValueKeyIndex); int bioValueEndIndex = biometricsDto.getDecodedBioResponse().indexOf('"', (bioValueStartIndex + 1)); - String bioValue = biometricsDto.getDecodedBioResponse().substring(bioValueStartIndex, (bioValueEndIndex + 1)); - payLoad = biometricsDto.getDecodedBioResponse().replace(bioValue, PacketManagerConstant.BIOVALUE_PLACEHOLDER); + String bioValue = biometricsDto.getDecodedBioResponse().substring(bioValueStartIndex, + (bioValueEndIndex + 1)); + payLoad = biometricsDto.getDecodedBioResponse().replace(bioValue, + PacketManagerConstant.BIOVALUE_PLACEHOLDER); } - if(singleType == SingleType.FACE || singleType == SingleType.EXCEPTION_PHOTO) + if (singleType == SingleType.FACE || singleType == SingleType.EXCEPTION_PHOTO) biometricsDto.setBioSubType(EMPTY); return new BIR.BIRBuilder().withBdb(iso == null ? new byte[0] : iso) @@ -732,13 +758,15 @@ public BIR buildBIR(BiometricsDto biometricsDto) { .withPurpose(PurposeType.ENROLL).withLevel(ProcessedLevelType.RAW) .withCreationDate(LocalDateTime.now(ZoneId.of("UTC"))).withIndex(UUID.randomUUID().toString()) .build()) - .withSb(biometricsDto.getSignature() == null ? new byte[0] : biometricsDto.getSignature().getBytes(StandardCharsets.UTF_8)) + .withSb(biometricsDto.getSignature() == null ? new byte[0] + : biometricsDto.getSignature().getBytes(StandardCharsets.UTF_8)) .withOthers(OTHER_KEY_EXCEPTION, iso == null ? "true" : BOOLEAN_FALSE) .withOthers(OTHER_KEY_RETRIES, biometricsDto.getNumOfRetries() + EMPTY) .withOthers(OTHER_KEY_SDK_SCORE, biometricsDto.getSdkScore() + EMPTY) .withOthers(OTHER_KEY_FORCE_CAPTURED, biometricsDto.isForceCaptured() + EMPTY) .withOthers(OTHER_KEY_PAYLOAD, payLoad == null ? EMPTY : payLoad) - .withOthers(OTHER_KEY_SPEC_VERSION, biometricsDto.getSpecVersion() == null ? EMPTY : biometricsDto.getSpecVersion()) + .withOthers(OTHER_KEY_SPEC_VERSION, + biometricsDto.getSpecVersion() == null ? EMPTY : biometricsDto.getSpecVersion()) .build(); } @@ -763,7 +791,7 @@ private void setBiometrics(RegistrationDto registrationDto) throws RegBaseChecke Map> capturedMetaInfo = new LinkedHashMap<>(); Map> exceptionMetaInfo = new LinkedHashMap<>(); - for(String key : registrationDto.getBiometrics().keySet()) { + for (String key : registrationDto.getBiometrics().keySet()) { String fieldId = key.split("_")[0]; String bioAttribute = key.split("_")[1]; BIR bir = buildBIR(registrationDto.getBiometrics().get(key)); @@ -781,7 +809,7 @@ private void setBiometrics(RegistrationDto registrationDto) throws RegBaseChecke capturedMetaInfo.get(fieldId).put(bioAttribute, metaInfo); } - for(String key : registrationDto.EXCEPTIONS.keySet()) { + for (String key : registrationDto.EXCEPTIONS.keySet()) { String fieldId = key.split("_")[0]; String bioAttribute = key.split("_")[1]; registrationDto.EXCEPTIONS.get(key).forEach((v) -> { @@ -801,7 +829,8 @@ private void setBiometrics(RegistrationDto registrationDto) throws RegBaseChecke BiometricRecord biometricRecord = new BiometricRecord(); biometricRecord.setOthers(new HashMap<>()); biometricRecord.getOthers().put(OTHER_KEY_CONFIGURED, String.join(",", - registrationDto.CAPTURED_BIO_FIELDS.contains(fieldId) ? Collections.singletonList(fieldId) : Collections.EMPTY_LIST)); + registrationDto.CAPTURED_BIO_FIELDS.contains(fieldId) ? Collections.singletonList(fieldId) + : Collections.EMPTY_LIST)); biometricRecord.setSegments(capturedBiometrics.get(fieldId)); Log.d(TAG, "Adding biometric to packet manager for field : " + fieldId); packetWriterService.setBiometric(registrationDto.getRId(), fieldId, biometricRecord); diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/config/AppModuleTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/config/AppModuleTest.java index 074a92f43..3d60a831c 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/config/AppModuleTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/config/AppModuleTest.java @@ -50,63 +50,118 @@ import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.*; - public class AppModuleTest { - @Mock Application mockApplication; - @Mock Context mockContext; - @Mock CertificateManagerService certificateManagerService; - @Mock ClientCryptoManagerService clientCryptoManagerService; - @Mock CryptoManagerService cryptoManagerService; - @Mock IPacketCryptoService iPacketCryptoService; - @Mock ObjectMapper objectMapper; - @Mock ObjectAdapterService objectAdapterService; - @Mock PacketKeeper packetKeeper; - @Mock PacketManagerHelper packetManagerHelper; - @Mock PacketWriterService packetWriterService; - @Mock SyncRestService syncRestService; - @Mock MachineRepository machineRepository; - @Mock ReasonListRepository reasonListRepository; - @Mock RegistrationCenterRepository registrationCenterRepository; - @Mock DocumentTypeRepository documentTypeRepository; - @Mock ApplicantValidDocRepository applicantValidDocRepository; - @Mock TemplateRepository templateRepository; - @Mock DynamicFieldRepository dynamicFieldRepository; - @Mock LocationRepository locationRepository; - @Mock GlobalParamRepository globalParamRepository; - @Mock IdentitySchemaRepository identitySchemaRepository; - @Mock BlocklistedWordRepository blocklistedWordRepository; - @Mock SyncJobDefRepository syncJobDefRepository; - @Mock UserDetailRepository userDetailRepository; - @Mock LanguageRepository languageRepository; - @Mock UserRoleRepository userRoleRepository; - @Mock JobManagerService jobManagerService; - @Mock FileSignatureDao fileSignatureDao; - @Mock UserBiometricRepository userBiometricRepository; - @Mock RegistrationRepository registrationRepository; - @Mock KeyStoreRepository keyStoreRepository; - @Mock AuditManagerService auditManagerService; - @Mock AuditRepository auditRepository; - @Mock JobTransactionRepository jobTransactionRepository; - @Mock CertificateDBHelper certificateDBHelper; - @Mock CACertificateStoreRepository caCertificateStoreRepository; - @Mock DateUtil dateUtil; - @Mock PreRegistrationDataSyncDao preRegistrationDataSyncDao; - @Mock PreRegistrationDataSyncRepositoryDao preRegistrationDataSyncRepositoryDao; - @Mock PreRegZipHandlingService preRegZipHandlingService; - @Mock PreRegistrationList preRegistrationList; + @Mock + Application mockApplication; + @Mock + Context mockContext; + @Mock + CertificateManagerService certificateManagerService; + @Mock + ClientCryptoManagerService clientCryptoManagerService; + @Mock + CryptoManagerService cryptoManagerService; + @Mock + IPacketCryptoService iPacketCryptoService; + @Mock + ObjectMapper objectMapper; + @Mock + ObjectAdapterService objectAdapterService; + @Mock + PacketKeeper packetKeeper; + @Mock + PacketManagerHelper packetManagerHelper; + @Mock + PacketWriterService packetWriterService; + @Mock + SyncRestService syncRestService; + @Mock + MachineRepository machineRepository; + @Mock + ReasonListRepository reasonListRepository; + @Mock + RegistrationCenterRepository registrationCenterRepository; + @Mock + DocumentTypeRepository documentTypeRepository; + @Mock + ApplicantValidDocRepository applicantValidDocRepository; + @Mock + TemplateRepository templateRepository; + @Mock + DynamicFieldRepository dynamicFieldRepository; + @Mock + LocationRepository locationRepository; + @Mock + GlobalParamRepository globalParamRepository; + @Mock + IdentitySchemaRepository identitySchemaRepository; + @Mock + BlocklistedWordRepository blocklistedWordRepository; + @Mock + SyncJobDefRepository syncJobDefRepository; + @Mock + UserDetailRepository userDetailRepository; + @Mock + LanguageRepository languageRepository; + @Mock + UserRoleRepository userRoleRepository; + @Mock + JobManagerService jobManagerService; + @Mock + FileSignatureDao fileSignatureDao; + @Mock + UserBiometricRepository userBiometricRepository; + @Mock + RegistrationRepository registrationRepository; + @Mock + KeyStoreRepository keyStoreRepository; + @Mock + AuditManagerService auditManagerService; + @Mock + AuditRepository auditRepository; + @Mock + JobTransactionRepository jobTransactionRepository; + @Mock + CertificateDBHelper certificateDBHelper; + @Mock + CACertificateStoreRepository caCertificateStoreRepository; + @Mock + DateUtil dateUtil; + @Mock + PreRegistrationDataSyncDao preRegistrationDataSyncDao; + @Mock + PreRegistrationDataSyncRepositoryDao preRegistrationDataSyncRepositoryDao; + @Mock + PreRegZipHandlingService preRegZipHandlingService; + @Mock + PreRegistrationList preRegistrationList; @Mock Provider preRegistrationDataSyncServiceProvider; - @Mock Biometrics095Service biometricService; + @Mock + Biometrics095Service biometricService; - @Mock JobTransactionService jobTransactionService; + @Mock + JobTransactionService jobTransactionService; - @Mock PermittedLocalConfigRepository permittedLocalConfigRepository; + @Mock + PermittedLocalConfigRepository permittedLocalConfigRepository; - @Mock LocalConfigDAO localConfigDAO; + @Mock + LocalConfigDAO localConfigDAO; - @Mock LocationValidationService locationValidationService; + @Mock + LocalConfigService localConfigService; + + @Mock + LocationValidationService locationValidationService; + + @Mock + PacketService packetService; + + @Mock + PreCheckValidatorService preCheckValidatorService; private AppModule appModule; private MockedStatic configServiceMock; @@ -153,7 +208,8 @@ public void testProvideClientCryptoManagerService() { @Test public void testProvideIPacketCryptoService() { - IPacketCryptoService service = appModule.provideIPacketCryptoService(clientCryptoManagerService, cryptoManagerService); + IPacketCryptoService service = appModule.provideIPacketCryptoService(clientCryptoManagerService, + cryptoManagerService); assertNotNull(service); assertTrue(service instanceof PacketCryptoServiceImpl); } @@ -179,8 +235,8 @@ public void testProvideMasterDataService() { registrationCenterRepository, documentTypeRepository, applicantValidDocRepository, templateRepository, dynamicFieldRepository, locationRepository, globalParamRepository, identitySchemaRepository, blocklistedWordRepository, syncJobDefRepository, userDetailRepository, certificateManagerService, - languageRepository, jobManagerService, fileSignatureDao, jobTransactionService, permittedLocalConfigRepository, localConfigDAO - ); + languageRepository, jobManagerService, fileSignatureDao, jobTransactionService, + permittedLocalConfigRepository, localConfigDAO); assertNotNull(service); assertTrue(service instanceof MasterDataServiceImpl); } @@ -193,7 +249,8 @@ public void testProvideSyncRestFactory() { @Test public void testProvideLoginService() { - LoginService service = appModule.provideLoginService(clientCryptoManagerService, userDetailRepository,userRoleRepository); + LoginService service = appModule.provideLoginService(clientCryptoManagerService, userDetailRepository, + userRoleRepository); assertNotNull(service); } @@ -201,8 +258,9 @@ public void testProvideLoginService() { public void testProvideRegistrationService() { RegistrationService service = appModule.provideRegistrationService( packetWriterService, registrationRepository, mock(MasterDataService.class), identitySchemaRepository, - clientCryptoManagerService, keyStoreRepository, globalParamRepository, auditManagerService,registrationCenterRepository,locationValidationService, preRegistrationDataSyncServiceProvider,biometricService - ); + clientCryptoManagerService, keyStoreRepository, globalParamRepository, auditManagerService, + registrationCenterRepository, locationValidationService, preRegistrationDataSyncServiceProvider, + biometricService, packetService, preCheckValidatorService); assertNotNull(service); assertTrue(service instanceof RegistrationServiceImpl); } @@ -216,8 +274,8 @@ public void testProvideUserInterfaceHelperService() { @Test public void testProvidePacketService() { PacketService service = appModule.providePacketService( - registrationRepository, iPacketCryptoService, syncRestService, mock(MasterDataService.class), globalParamRepository - ); + registrationRepository, iPacketCryptoService, syncRestService, mock(MasterDataService.class), + globalParamRepository); assertNotNull(service); assertTrue(service instanceof PacketServiceImpl); } @@ -244,7 +302,8 @@ public void testProvideAuditManagerService() { @Test public void testProvideJobManagerService() { - JobManagerService service = appModule.provideJobManagerService(syncJobDefRepository, mock(JobTransactionService.class), dateUtil); + JobManagerService service = appModule.provideJobManagerService(syncJobDefRepository, + mock(JobTransactionService.class), dateUtil, localConfigService); assertNotNull(service); assertTrue(service instanceof JobManagerServiceImpl); } @@ -252,8 +311,8 @@ public void testProvideJobManagerService() { @Test public void testProvideBiometrics095Service() { Biometrics095Service service = appModule.provideBiometrics095Service( - objectMapper, auditManagerService, globalParamRepository, clientCryptoManagerService, userBiometricRepository - ); + objectMapper, auditManagerService, globalParamRepository, clientCryptoManagerService, + userBiometricRepository); assertNotNull(service); assertTrue(service instanceof Biometrics095Service); } @@ -262,8 +321,8 @@ public void testProvideBiometrics095Service() { public void testProvideUserOnboardService() { UserOnboardService service = appModule.provideUserOnboardService( objectMapper, auditManagerService, certificateManagerService, syncRestService, cryptoManagerService, - mock(RegistrationService.class), userBiometricRepository, clientCryptoManagerService, userDetailRepository, globalParamRepository - ); + mock(RegistrationService.class), userBiometricRepository, clientCryptoManagerService, + userDetailRepository, globalParamRepository); assertNotNull(service); assertTrue(service instanceof UserOnboardService); } @@ -271,8 +330,7 @@ public void testProvideUserOnboardService() { @Test public void testTemplateService() { TemplateService service = appModule.TemplateService( - mock(MasterDataService.class), identitySchemaRepository, globalParamRepository - ); + mock(MasterDataService.class), identitySchemaRepository, globalParamRepository); assertNotNull(service); } @@ -280,8 +338,7 @@ public void testTemplateService() { public void testPreRegistrationDataSyncService() { PreRegistrationDataSyncService service = appModule.PreRegistrationDataSyncService( preRegistrationDataSyncDao, mock(MasterDataService.class), syncRestService, preRegZipHandlingService, - preRegistrationList, globalParamRepository, mock(RegistrationService.class) - ); + preRegistrationList, globalParamRepository, mock(RegistrationService.class)); assertNotNull(service); } @@ -296,8 +353,7 @@ public void testPreRegZipHandlingService() { PreRegZipHandlingService service = appModule.PreRegZipHandlingService( mock(ApplicantValidDocumentDao.class), identitySchemaRepository, clientCryptoManagerService, mock(RegistrationService.class), cryptoManagerService, packetKeeper, iPacketCryptoService, - mock(MasterDataService.class), globalParamRepository - ); + mock(MasterDataService.class), globalParamRepository); assertNotNull(service); } @@ -338,5 +394,4 @@ public void test_provide_packet_manager_helper_with_null_context() { }); } - } \ No newline at end of file diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/jobs/RegistrationDeletionJobTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/jobs/RegistrationDeletionJobTest.java new file mode 100644 index 000000000..a4ce8300a --- /dev/null +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/jobs/RegistrationDeletionJobTest.java @@ -0,0 +1,69 @@ +package io.mosip.registration.clientmanager.jobs; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.concurrent.TimeUnit; + +import io.mosip.registration.clientmanager.spi.PacketService; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; + +@RunWith(MockitoJUnitRunner.class) +public class RegistrationDeletionJobTest { + + @Spy + private RegistrationDeletionJob registrationDeletionJob = new RegistrationDeletionJob(); + + @Mock + private PacketService packetService; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + + registrationDeletionJob.packetService = packetService; + } + + @Test + public void testTriggerJob_SuccessfulDeletion_ReturnsTrue() { + int jobId = 1; + long currentTimeMillis = System.currentTimeMillis(); + + boolean result = registrationDeletionJob.triggerJob(jobId); + + assertTrue(result); + verify(packetService).deleteRegistrationPackets(); + verify(registrationDeletionJob).logJobTransaction(jobId, TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis)); + } + + @Test + public void testTriggerJob_DeletionThrowsException_ReturnsFalse() { + int jobId = 1; + doThrow(new RuntimeException("Deletion failed")) + .when(packetService).deleteRegistrationPackets(); + + boolean result = registrationDeletionJob.triggerJob(jobId); + + assertFalse(result); + verify(packetService).deleteRegistrationPackets(); + } + + @Test + public void testTriggerJob_LogsStartAndCompletion() { + int jobId = 1; + + registrationDeletionJob.triggerJob(jobId); + + verify(packetService).deleteRegistrationPackets(); + } +} + diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/Biometrics095ServiceTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/Biometrics095ServiceTest.java index 5b01a2a85..1710f4151 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/Biometrics095ServiceTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/Biometrics095ServiceTest.java @@ -71,6 +71,9 @@ public void setUp() { @Test public void testGetRCaptureRequest() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_ACTIVE_PROFILE)) + .thenReturn("Developer"); + Modality modality = Modality.FACE; String deviceId = "testDevice"; List exceptionAttributes = new ArrayList<>(); @@ -169,6 +172,8 @@ public void testValidateJWTResponse_invalidSignature() throws Exception { public void test_creates_capture_request_with_standard_environment_settings() { when(mockContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mockSharedPreferences); when(mockContext.getString(anyInt())).thenReturn("app_name"); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_ACTIVE_PROFILE)) + .thenReturn("Developer"); Biometrics095Service biometrics095Service = new Biometrics095Service( mockContext, mockObjectMapper, mockAuditManagerService, diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/JobManagerServiceImplTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/JobManagerServiceImplTest.java index 2bb854ddd..cafbc7df0 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/JobManagerServiceImplTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/JobManagerServiceImplTest.java @@ -17,6 +17,7 @@ import io.mosip.registration.clientmanager.repository.SyncJobDefRepository; import io.mosip.registration.clientmanager.spi.JobTransactionService; +import io.mosip.registration.clientmanager.spi.LocalConfigService; import io.mosip.registration.clientmanager.util.CronExpressionParser; import io.mosip.registration.clientmanager.util.DateUtil; @@ -42,6 +43,9 @@ public class JobManagerServiceImplTest { @Mock private DateUtil mockDateUtil; + @Mock + private LocalConfigService mockLocalConfigService; + private JobManagerServiceImpl jobManagerService; private static final String JOB_ID = "mosip.syncJobId"; @@ -56,7 +60,7 @@ public class JobManagerServiceImplTest { @Before public void setUp() { MockitoAnnotations.openMocks(this); - jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); when(mockContext.getSystemService(JOB_SCHEDULER_SERVICE)).thenReturn(mockJobScheduler); mockJobInfoBuilder = mock(JobInfo.Builder.class); @@ -120,7 +124,8 @@ public void test_constructor_throws_exception_when_context_is_null() { nullContext, mockSyncJobDefRepository, mockJobTransactionService, - mockDateUtil + mockDateUtil, + mockLocalConfigService ); }); } @@ -138,7 +143,7 @@ public void test_refresh_all_jobs_fetches_all_sync_job_defs() { when(mockSyncJobDefRepository.getAllSyncJobDefList()).thenReturn(mockJobDefList); JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl( - mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); jobManagerService.refreshAllJobs(); @@ -153,7 +158,7 @@ public void test_refresh_all_jobs_with_empty_list() { when(mockSyncJobDefRepository.getAllSyncJobDefList()).thenReturn(emptyJobDefList); JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl( - mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); jobManagerService.refreshAllJobs(); @@ -168,7 +173,7 @@ public void test_schedule_job_when_active_implemented_and_not_scheduled() { when(mockContext.getSystemService(JOB_SCHEDULER_SERVICE)).thenReturn(mockJobScheduler); JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, - mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); SyncJobDef jobDef = new SyncJobDef("12345"); jobDef.setId("12345"); @@ -198,7 +203,7 @@ public void test_cancel_job_when_is_active_null() { when(mockContext.getSystemService(JOB_SCHEDULER_SERVICE)).thenReturn(mockJobScheduler); JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, - mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); SyncJobDef jobDef = new SyncJobDef("12345"); jobDef.setId("12345"); @@ -227,7 +232,8 @@ public void test_schedule_job_with_unimplemented_api_name_throws_exception() { mockContext, mockSyncJobDefRepository, mockJobTransactionService, - mockDateUtil); + mockDateUtil, + mockLocalConfigService); int jobId = 12345; String invalidApiName = "nonExistentJobService"; @@ -248,7 +254,7 @@ public void test_when_job_not_scheduled_schedule_job_called_with_null_sync_freq( when(mockJobScheduler.getPendingJob(anyInt())).thenReturn(null); JobManagerServiceImpl triggerJobService = new JobManagerServiceImpl(mockContext, - mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); JobManagerServiceImpl spyTriggerJobService = spy(triggerJobService); doReturn(JobScheduler.RESULT_SUCCESS).when(spyTriggerJobService).scheduleJob(anyInt(), anyString(), isNull()); @@ -270,7 +276,7 @@ public void test_when_job_exists_reschedule_job() { when(mockJobScheduler.schedule(any(JobInfo.class))).thenReturn(JobScheduler.RESULT_SUCCESS); JobManagerServiceImpl triggerJobService = new JobManagerServiceImpl(mockContext, - mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); int jobId = 12345; String apiName = "packetSyncStatusJob"; @@ -285,7 +291,7 @@ public void test_when_job_exists_reschedule_job() { @Test public void test_job_already_scheduled() { when(mockJobScheduler.getPendingJob(anyInt())).thenReturn(mockJobInfo); - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); jobManagerService.jobScheduler = mockJobScheduler; boolean result = jobManagerService.triggerJobService(1, "packetSyncStatusJob"); @@ -297,7 +303,7 @@ public void test_job_already_scheduled() { @Test public void test_job_already_scheduled_always_returns_true() { when(mockJobScheduler.getPendingJob(anyInt())).thenReturn(mockJobInfo); - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); jobManagerService.jobScheduler = mockJobScheduler; boolean result = jobManagerService.triggerJobService(1, "packetSyncStatusJob"); @@ -313,7 +319,8 @@ public void test_cancel_job_with_valid_job_id() { mockContext, mockSyncJobDefRepository, mockJobTransactionService, - mockDateUtil + mockDateUtil, + mockLocalConfigService ); int validJobId = 12345; @@ -331,7 +338,8 @@ public void test_cancel_job_with_negative_job_id() { mockContext, mockSyncJobDefRepository, mockJobTransactionService, - mockDateUtil + mockDateUtil, + mockLocalConfigService ); int negativeJobId = -123; @@ -345,7 +353,7 @@ public void test_cancel_job_with_negative_job_id() { public void test_cancel_existing_scheduled_job() { when(mockContext.getSystemService(JOB_SCHEDULER_SERVICE)).thenReturn(mockJobScheduler); - JobManagerServiceImpl jobManager = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManager = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); int jobId = 123; jobManager.cancelJob(jobId); @@ -357,7 +365,7 @@ public void test_cancel_existing_scheduled_job() { public void test_cancel_inactive_job_in_refresh_status() { when(mockContext.getSystemService(JOB_SCHEDULER_SERVICE)).thenReturn(mockJobScheduler); - JobManagerServiceImpl jobManager = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManager = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); SyncJobDef inactiveJobDef = new SyncJobDef("inactive12345"); inactiveJobDef.setIsActive(false); @@ -370,7 +378,7 @@ public void test_cancel_inactive_job_in_refresh_status() { @Test public void test_returns_true_for_packet_sync_status_job() { - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); boolean result = jobManagerService.isJobImplementedOnRegClient("packetSyncStatusJob"); @@ -379,7 +387,7 @@ public void test_returns_true_for_packet_sync_status_job() { @Test (expected = NullPointerException.class) public void test_returns_false_for_null_job_api_name() { - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); boolean result = jobManagerService.isJobImplementedOnRegClient(null); assertFalse(result); @@ -387,7 +395,7 @@ public void test_returns_false_for_null_job_api_name() { @Test public void test_returns_true_for_synchConfigDataJob() { - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); boolean result = jobManagerService.isJobImplementedOnRegClient("synchConfigDataJob"); assertTrue(result); @@ -395,7 +403,7 @@ public void test_returns_true_for_synchConfigDataJob() { @Test public void test_identifies_implemented_job_services() { - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); boolean result = jobManagerService.isJobImplementedOnRegClient("packetSyncStatusJob"); @@ -404,7 +412,7 @@ public void test_identifies_implemented_job_services() { @Test public void test_method_returns_boolean_value() { - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); boolean resultForImplementedJob = jobManagerService.isJobImplementedOnRegClient("packetSyncStatusJob"); boolean resultForNonImplementedJob = jobManagerService.isJobImplementedOnRegClient("nonExistentJob"); @@ -426,7 +434,8 @@ public void test_returns_formatted_datetime_when_last_sync_time_greater_than_zer mockContext, mockSyncJobDefRepository, mockJobTransactionService, - mockDateUtil); + mockDateUtil, + mockLocalConfigService); String result = jobManagerService.getLastSyncTime(jobId); @@ -448,7 +457,8 @@ public void test_returns_na_when_last_sync_time_is_zero() { mockContext, mockSyncJobDefRepository, mockJobTransactionService, - mockDateUtil); + mockDateUtil, + mockLocalConfigService); String result = jobManagerService.getLastSyncTime(jobId); @@ -463,7 +473,7 @@ public void test_returns_na_when_last_sync_time_is_zero_or_negative() { when(mockContext.getString(R.string.NA)).thenReturn("N/A"); when(mockJobTransactionService.getLastSyncTime(anyInt())).thenReturn(0L); - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); String result = jobManagerService.getLastSyncTime(1); @@ -478,7 +488,7 @@ public void test_correctly_formats_timestamp_using_date_util() { when(mockJobTransactionService.getLastSyncTime(anyInt())).thenReturn(lastSyncTimeSeconds); when(mockDateUtil.getDateTime(lastSyncTimeSeconds)).thenReturn(expectedFormattedDate); - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); String result = jobManagerService.getLastSyncTime(1); @@ -493,7 +503,7 @@ public void test_retrieves_last_sync_time_seconds_from_service() { when(mockJobTransactionService.getLastSyncTime(anyInt())).thenReturn(lastSyncTimeSeconds); when(mockDateUtil.getDateTime(lastSyncTimeSeconds)).thenReturn("01 Jun 2021 12:00 PM"); - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); String result = jobManagerService.getLastSyncTime(1); @@ -504,7 +514,7 @@ public void test_retrieves_last_sync_time_seconds_from_service() { @Test public void test_extract_last_five_chars_and_convert_to_int() { - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); String syncJobDefId = "JOB_12345"; int result = jobManagerService.generateJobServiceId(syncJobDefId); @@ -514,7 +524,7 @@ public void test_extract_last_five_chars_and_convert_to_int() { @Test public void test_throws_exception_when_sync_job_def_id_is_null() { - JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); assertThrows(NullPointerException.class, () -> jobManagerService.generateJobServiceId(null)); } @@ -523,7 +533,7 @@ public void test_throws_exception_when_sync_job_def_id_is_null() { public void test_isJobScheduled_returnsTrueWhenPendingJobExists() { when(mockJobScheduler.getPendingJob(42)).thenReturn(mockJobInfo); - JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); assertTrue(service.isJobScheduled(42)); verify(mockJobScheduler).getPendingJob(42); @@ -533,7 +543,7 @@ public void test_isJobScheduled_returnsTrueWhenPendingJobExists() { public void test_isJobScheduled_returnsFalseWhenNoPendingJob() { when(mockJobScheduler.getPendingJob(77)).thenReturn(null); - JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); assertFalse(service.isJobScheduled(77)); verify(mockJobScheduler).getPendingJob(77); @@ -544,7 +554,7 @@ public void test_getAllSyncJobDefList_delegatesToRepository() { List expected = Collections.singletonList(new SyncJobDef("job00123")); when(mockSyncJobDefRepository.getAllSyncJobDefList()).thenReturn(expected); - JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); assertSame(expected, service.getAllSyncJobDefList()); verify(mockSyncJobDefRepository).getAllSyncJobDefList(); @@ -565,7 +575,7 @@ public void test_getNextSyncTime_usesCronExpressionWhenValid() { long nextExecutionMillis = nextExecution.toEpochMilli(); when(mockDateUtil.getDateTime(nextExecutionMillis)).thenReturn("formatted-time"); - JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); String result = service.getNextSyncTime(1); @@ -578,7 +588,7 @@ public void test_getNextSyncTime_usesCronExpressionWhenValid() { public void test_getNextSyncTime_returnsNAWhenJobDefMissing() { when(mockSyncJobDefRepository.getAllSyncJobDefList()).thenReturn(Collections.emptyList()); - JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil); + JobManagerServiceImpl service = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil, mockLocalConfigService); String result = service.getNextSyncTime(999); diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/LocalConfigServiceImplTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/LocalConfigServiceImplTest.java index afe529272..f04701dee 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/LocalConfigServiceImplTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/LocalConfigServiceImplTest.java @@ -1,9 +1,13 @@ package io.mosip.registration.clientmanager.service; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.Arrays; import java.util.List; import java.util.Map; @@ -59,4 +63,131 @@ public void testGetPermittedConfiguration_usesRegistrationConstant() { assertEquals(permitted, result); verify(localConfigDAO).getPermittedConfigurations(RegistrationConstants.PERMITTED_CONFIG_TYPE); } + + @Test + public void testGetValue_delegatesToDao() { + String name = "test.name"; + String configType = "CONFIG"; + String expectedValue = "testValue"; + when(localConfigDAO.getValue(name, configType)).thenReturn(expectedValue); + + String result = localConfigService.getValue(name, configType); + + assertEquals(expectedValue, result); + verify(localConfigDAO).getValue(name, configType); + } + + @Test + public void testGetPermittedJobs_delegatesToDao() { + List permittedJobs = Arrays.asList("job1", "job2", "job3"); + when(localConfigDAO.getPermittedConfigurations(RegistrationConstants.PERMITTED_JOB_TYPE)) + .thenReturn(permittedJobs); + + List result = localConfigService.getPermittedJobs(); + + assertEquals(permittedJobs, result); + verify(localConfigDAO).getPermittedConfigurations(RegistrationConstants.PERMITTED_JOB_TYPE); + } + + @Test + public void testModifyJob_nullName_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + localConfigService.modifyJob(null, "0 0 12 * * ?"); + }); + + verify(localConfigDAO, never()).modifyJob(anyString(), anyString()); + } + + @Test + public void testModifyJob_emptyName_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + localConfigService.modifyJob("", "0 0 12 * * ?"); + }); + + verify(localConfigDAO, never()).modifyJob(anyString(), anyString()); + } + + @Test + public void testModifyJob_blankName_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + localConfigService.modifyJob(" ", "0 0 12 * * ?"); + }); + + verify(localConfigDAO, never()).modifyJob(anyString(), anyString()); + } + + @Test + public void testModifyJob_nullValue_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + localConfigService.modifyJob("job1", null); + }); + + verify(localConfigDAO, never()).modifyJob(anyString(), anyString()); + } + + @Test + public void testModifyJob_emptyValue_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + localConfigService.modifyJob("job1", ""); + }); + + verify(localConfigDAO, never()).modifyJob(anyString(), anyString()); + } + + @Test + public void testModifyJob_blankValue_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + localConfigService.modifyJob("job1", " "); + }); + + verify(localConfigDAO, never()).modifyJob(anyString(), anyString()); + } + + @Test + public void testModifyJob_invalidCronExpression_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + localConfigService.modifyJob("job1", "invalid cron"); + }); + + verify(localConfigDAO, never()).modifyJob(anyString(), anyString()); + } + + @Test + public void testModifyJob_jobNotPermitted_throwsIllegalArgumentException() { + List permittedJobs = Arrays.asList("job1"); + when(localConfigDAO.getPermittedConfigurations(RegistrationConstants.PERMITTED_JOB_TYPE)) + .thenReturn(permittedJobs); + + assertThrows(IllegalArgumentException.class, () -> { + localConfigService.modifyJob("unauthorizedJob", "0 0 12 * * ?"); + }); + + verify(localConfigDAO, never()).modifyJob(anyString(), anyString()); + } + + @Test + public void testModifyJob_validInput_delegatesToDao() { + String jobName = "job1"; + String cronExpression = "0 0 12 * * ?"; + List permittedJobs = Arrays.asList(jobName); + when(localConfigDAO.getPermittedConfigurations(RegistrationConstants.PERMITTED_JOB_TYPE)) + .thenReturn(permittedJobs); + + localConfigService.modifyJob(jobName, cronExpression); + + verify(localConfigDAO).modifyJob(jobName, cronExpression); + } + + @Test + public void testModifyJob_validInputWithWhitespace_delegatesToDao() { + String jobName = "job1"; + String cronExpression = " 0 0 12 * * ? "; + List permittedJobs = Arrays.asList(jobName); + when(localConfigDAO.getPermittedConfigurations(RegistrationConstants.PERMITTED_JOB_TYPE)) + .thenReturn(permittedJobs); + + localConfigService.modifyJob(jobName, cronExpression); + + verify(localConfigDAO).modifyJob(jobName, cronExpression); + } } \ No newline at end of file diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/MasterDataServiceImplTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/MasterDataServiceImplTest.java index 811cb9d3c..ad5d60808 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/MasterDataServiceImplTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/MasterDataServiceImplTest.java @@ -20,7 +20,7 @@ import io.mosip.registration.clientmanager.spi.JobManagerService; import io.mosip.registration.clientmanager.spi.JobTransactionService; import io.mosip.registration.keymanager.dto.*; -import io.mosip.registration.keymanager.dto.CACertificateResponseDto; +import io.mosip.registration.clientmanager.dto.http.CACertificateResponseDto; import io.mosip.registration.keymanager.exception.KeymanagerServiceException; import io.mosip.registration.keymanager.spi.CertificateManagerService; import io.mosip.registration.keymanager.util.CryptoUtil; @@ -48,6 +48,9 @@ import io.mosip.registration.keymanager.spi.ClientCryptoManagerService; import org.springframework.test.util.ReflectionTestUtils; +import okhttp3.Headers; +import okhttp3.Protocol; +import okhttp3.Request; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; @@ -1329,9 +1332,8 @@ public void test_save_ca_certificates_with_non_empty_list() { certificateDto.setCreatedtimes(LocalDateTime.now()); caCertificateDtos.add(certificateDto); - CACertificateResponseDto responseDto = new CACertificateResponseDto(); - responseDto.setStatus("success"); - responseDto.setTimestamp(LocalDateTime.now()); + io.mosip.registration.keymanager.dto.CACertificateResponseDto responseDto = mock(io.mosip.registration.keymanager.dto.CACertificateResponseDto.class); + when(responseDto.getStatus()).thenReturn("success"); when(mockCertificateManagerService.uploadCACertificate(any(CACertificateRequestDto.class))).thenReturn(responseDto); @@ -1750,8 +1752,6 @@ public void test_syncCertificate_failure() { public void test_syncMasterData_success() { MasterDataServiceImpl spyService = org.mockito.Mockito.spy(masterDataService); doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); - when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) - .thenReturn("v1.2.0"); when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) .thenReturn("key"); doReturn(mockMasterCall).when(mockSyncRestService).fetchMasterData(any()); @@ -1777,8 +1777,6 @@ public void test_syncMasterData_success() { public void test_syncMasterData_error() { MasterDataServiceImpl spyService = org.mockito.Mockito.spy(masterDataService); doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); - when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) - .thenReturn("v1.2.0"); when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) .thenReturn("key"); doReturn(mockMasterCall).when(mockSyncRestService).fetchMasterData(any()); @@ -1801,8 +1799,6 @@ public void test_syncMasterData_error() { public void test_syncMasterData_failure() { MasterDataServiceImpl spyService = org.mockito.Mockito.spy(masterDataService); doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); - when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) - .thenReturn("v1.2.0"); when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) .thenReturn("key"); doReturn(mockMasterCall).when(mockSyncRestService).fetchMasterData(any()); @@ -2425,4 +2421,1602 @@ public void test_saveProcessSpec_handlesIOException() throws Exception { // Expected } } + + /** + * Tests that getRegistrationParams returns a map of registration parameters from the repository. + */ + @Test + public void test_getRegistrationParams_returnsRepositoryMap() { + Map expectedParams = new HashMap<>(); + expectedParams.put("mosip.registration.idle_time", "300"); + expectedParams.put("mosip.registration.theme", "dark"); + + when(mockGlobalParamRepository.getGlobalParamsByPattern("mosip.registration%")) + .thenReturn(expectedParams); + + Map result = masterDataService.getRegistrationParams(); + + assertEquals(expectedParams, result); + verify(mockGlobalParamRepository).getGlobalParamsByPattern("mosip.registration%"); + } + + /** + * Tests that getCachedStringOnboardYourselfUrl returns the URL from the repository. + */ + @Test + public void test_getCachedStringOnboardYourselfUrl_returnsValue() { + String expectedUrl = "https://example.com/onboard"; + when(mockGlobalParamRepository.getCachedStringOnboardYourselfUrl()).thenReturn(expectedUrl); + + String result = masterDataService.getCachedStringOnboardYourselfUrl(); + + assertEquals(expectedUrl, result); + verify(mockGlobalParamRepository).getCachedStringOnboardYourselfUrl(); + } + + /** + * Tests that getCachedStringOnboardYourselfUrl returns empty string when URL is null. + */ + @Test + public void test_getCachedStringOnboardYourselfUrl_returnsEmptyWhenNull() { + when(mockGlobalParamRepository.getCachedStringOnboardYourselfUrl()).thenReturn(null); + + String result = masterDataService.getCachedStringOnboardYourselfUrl(); + + assertEquals("", result); + verify(mockGlobalParamRepository).getCachedStringOnboardYourselfUrl(); + } + + /** + * Tests that getCachedStringRegisteringIndividualUrl returns the URL from the repository. + */ + @Test + public void test_getCachedStringRegisteringIndividualUrl_returnsValue() { + String expectedUrl = "https://example.com/register"; + when(mockGlobalParamRepository.getCachedStringRegisteringIndividualUrl()).thenReturn(expectedUrl); + + String result = masterDataService.getCachedStringRegisteringIndividualUrl(); + + assertEquals(expectedUrl, result); + verify(mockGlobalParamRepository).getCachedStringRegisteringIndividualUrl(); + } + + /** + * Tests that getCachedStringRegisteringIndividualUrl returns empty string when URL is null. + */ + @Test + public void test_getCachedStringRegisteringIndividualUrl_returnsEmptyWhenNull() { + when(mockGlobalParamRepository.getCachedStringRegisteringIndividualUrl()).thenReturn(null); + + String result = masterDataService.getCachedStringRegisteringIndividualUrl(); + + assertEquals("", result); + verify(mockGlobalParamRepository).getCachedStringRegisteringIndividualUrl(); + } + + /** + * Tests that getCachedStringSyncDataUrl returns the URL from the repository. + */ + @Test + public void test_getCachedStringSyncDataUrl_returnsValue() { + String expectedUrl = "https://example.com/sync"; + when(mockGlobalParamRepository.getCachedStringSyncDataUrl()).thenReturn(expectedUrl); + + String result = masterDataService.getCachedStringSyncDataUrl(); + + assertEquals(expectedUrl, result); + verify(mockGlobalParamRepository).getCachedStringSyncDataUrl(); + } + + /** + * Tests that getCachedStringSyncDataUrl returns empty string when URL is null. + */ + @Test + public void test_getCachedStringSyncDataUrl_returnsEmptyWhenNull() { + when(mockGlobalParamRepository.getCachedStringSyncDataUrl()).thenReturn(null); + + String result = masterDataService.getCachedStringSyncDataUrl(); + + assertEquals("", result); + verify(mockGlobalParamRepository).getCachedStringSyncDataUrl(); + } + + /** + * Tests that getCachedStringMappingDevicesUrl returns the URL from the repository. + */ + @Test + public void test_getCachedStringMappingDevicesUrl_returnsValue() { + String expectedUrl = "https://example.com/mapping"; + when(mockGlobalParamRepository.getCachedStringMappingDevicesUrl()).thenReturn(expectedUrl); + + String result = masterDataService.getCachedStringMappingDevicesUrl(); + + assertEquals(expectedUrl, result); + verify(mockGlobalParamRepository).getCachedStringMappingDevicesUrl(); + } + + /** + * Tests that getCachedStringMappingDevicesUrl returns empty string when URL is null. + */ + @Test + public void test_getCachedStringMappingDevicesUrl_returnsEmptyWhenNull() { + when(mockGlobalParamRepository.getCachedStringMappingDevicesUrl()).thenReturn(null); + + String result = masterDataService.getCachedStringMappingDevicesUrl(); + + assertEquals("", result); + verify(mockGlobalParamRepository).getCachedStringMappingDevicesUrl(); + } + + /** + * Tests that getCachedStringUploadingDataUrl returns the URL from the repository. + */ + @Test + public void test_getCachedStringUploadingDataUrl_returnsValue() { + String expectedUrl = "https://example.com/upload"; + when(mockGlobalParamRepository.getCachedStringUploadingDataUrl()).thenReturn(expectedUrl); + + String result = masterDataService.getCachedStringUploadingDataUrl(); + + assertEquals(expectedUrl, result); + verify(mockGlobalParamRepository).getCachedStringUploadingDataUrl(); + } + + /** + * Tests that getCachedStringUploadingDataUrl returns empty string when URL is null. + */ + @Test + public void test_getCachedStringUploadingDataUrl_returnsEmptyWhenNull() { + when(mockGlobalParamRepository.getCachedStringUploadingDataUrl()).thenReturn(null); + + String result = masterDataService.getCachedStringUploadingDataUrl(); + + assertEquals("", result); + verify(mockGlobalParamRepository).getCachedStringUploadingDataUrl(); + } + + /** + * Tests that getCachedStringUpdatingBiometricsUrl returns the URL from the repository. + */ + @Test + public void test_getCachedStringUpdatingBiometricsUrl_returnsValue() { + String expectedUrl = "https://example.com/update"; + when(mockGlobalParamRepository.getCachedStringUpdatingBiometricsUrl()).thenReturn(expectedUrl); + + String result = masterDataService.getCachedStringUpdatingBiometricsUrl(); + + assertEquals(expectedUrl, result); + verify(mockGlobalParamRepository).getCachedStringUpdatingBiometricsUrl(); + } + + /** + * Tests that getCachedStringUpdatingBiometricsUrl returns empty string when URL is null. + */ + @Test + public void test_getCachedStringUpdatingBiometricsUrl_returnsEmptyWhenNull() { + when(mockGlobalParamRepository.getCachedStringUpdatingBiometricsUrl()).thenReturn(null); + + String result = masterDataService.getCachedStringUpdatingBiometricsUrl(); + + assertEquals("", result); + verify(mockGlobalParamRepository).getCachedStringUpdatingBiometricsUrl(); + } + + /** + * Tests that saveStructuredData saves ReasonList entities correctly. + */ + @Test + public void test_saveStructuredData_ReasonList() throws Exception { + ReflectionTestUtils.setField(masterDataService, "reasonListRepository", mockReasonListRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray reasons = new JSONArray(); + reasons.put("{\"code\":\"R001\",\"name\":\"Reason1\",\"langCode\":\"eng\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(reasons.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "ReasonList", encryptedData, false); + + verify(mockReasonListRepository).saveReasonList(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves Machine entities correctly. + */ + @Test + public void test_saveStructuredData_Machine() throws Exception { + ReflectionTestUtils.setField(masterDataService, "machineRepository", mockMachineRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray machines = new JSONArray(); + machines.put("{\"id\":\"M001\",\"name\":\"Machine1\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(machines.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "Machine", encryptedData, false); + + verify(mockMachineRepository).saveMachineMaster(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves RegistrationCenter entities correctly. + */ + @Test + public void test_saveStructuredData_RegistrationCenter() throws Exception { + ReflectionTestUtils.setField(masterDataService, "registrationCenterRepository", mockRegistrationCenterRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray centers = new JSONArray(); + centers.put("{\"id\":\"C001\",\"name\":\"Center1\",\"langCode\":\"eng\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(centers.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "RegistrationCenter", encryptedData, false); + + verify(mockRegistrationCenterRepository).saveRegistrationCenter(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves DocumentType entities correctly. + */ + @Test + public void test_saveStructuredData_DocumentType() throws Exception { + ReflectionTestUtils.setField(masterDataService, "documentTypeRepository", mockDocumentTypeRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray doctypes = new JSONArray(); + doctypes.put("{\"code\":\"DOC001\",\"name\":\"Document1\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(doctypes.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "DocumentType", encryptedData, false); + + verify(mockDocumentTypeRepository).saveDocumentType(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves ApplicantValidDocument entities correctly. + */ + @Test + public void test_saveStructuredData_ApplicantValidDocument() throws Exception { + ReflectionTestUtils.setField(masterDataService, "applicantValidDocRepository", mockApplicantValidDocRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.DEFAULT_APP_TYPE_CODE)) + .thenReturn("APP_TYPE"); + + String encryptedData = "encrypted"; + JSONArray appValidDocs = new JSONArray(); + appValidDocs.put("{\"code\":\"DOC001\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(appValidDocs.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "ApplicantValidDocument", encryptedData, false); + + verify(mockApplicantValidDocRepository).saveApplicantValidDocument(any(JSONObject.class), eq("APP_TYPE")); + } + + /** + * Tests that saveStructuredData saves Template entities correctly. + */ + @Test + public void test_saveStructuredData_Template() throws Exception { + ReflectionTestUtils.setField(masterDataService, "templateRepository", mockTemplateRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray templates = new JSONArray(); + templates.put("{\"id\":\"T001\",\"name\":\"Template1\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(templates.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "Template", encryptedData, false); + + verify(mockTemplateRepository).saveTemplate(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves Location entities with fullSync true and isActive true. + */ + @Test + public void test_saveStructuredData_Location_fullSync_active() throws Exception { + ReflectionTestUtils.setField(masterDataService, "locationRepository", mockLocationRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + + String encryptedData = "encrypted"; + JSONArray locations = new JSONArray(); + locations.put("{\"code\":\"LOC001\",\"isActive\":true}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(locations.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "Location", encryptedData, false); + + verify(mockLocationRepository).saveLocationData(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves Location entities with fullSync true and isActive false. + */ + @Test + public void test_saveStructuredData_Location_fullSync_inactive() throws Exception { + ReflectionTestUtils.setField(masterDataService, "locationRepository", mockLocationRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + + String encryptedData = "encrypted"; + JSONArray locations = new JSONArray(); + locations.put("{\"code\":\"LOC001\",\"isActive\":false}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(locations.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "Location", encryptedData, false); + + verify(mockLocationRepository, never()).saveLocationData(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves Location entities with fullSync false. + */ + @Test + public void test_saveStructuredData_Location_notFullSync() throws Exception { + ReflectionTestUtils.setField(masterDataService, "locationRepository", mockLocationRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn("2023-01-01"); + + String encryptedData = "encrypted"; + JSONArray locations = new JSONArray(); + locations.put("{\"code\":\"LOC001\",\"isActive\":false}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(locations.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "Location", encryptedData, false); + + verify(mockLocationRepository).saveLocationData(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves LocationHierarchy entities correctly. + */ + @Test + public void test_saveStructuredData_LocationHierarchy() throws Exception { + ReflectionTestUtils.setField(masterDataService, "locationRepository", mockLocationRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray hierarchies = new JSONArray(); + hierarchies.put("{\"hierarchyLevel\":1,\"hierarchyName\":\"Country\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(hierarchies.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "LocationHierarchy", encryptedData, false); + + verify(mockLocationRepository).saveLocationHierarchyData(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves BlocklistedWords entities correctly. + */ + @Test + public void test_saveStructuredData_BlocklistedWords() throws Exception { + ReflectionTestUtils.setField(masterDataService, "blocklistedWordRepository", mockBlocklistedWordRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray words = new JSONArray(); + words.put("{\"word\":\"badword\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(words.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "BlocklistedWords", encryptedData, false); + + verify(mockBlocklistedWordRepository).saveBlocklistedWord(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves BlacklistedWords entities correctly. + */ + @Test + public void test_saveStructuredData_BlacklistedWords() throws Exception { + ReflectionTestUtils.setField(masterDataService, "blocklistedWordRepository", mockBlocklistedWordRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray words = new JSONArray(); + words.put("{\"word\":\"badword\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(words.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "BlacklistedWords", encryptedData, false); + + verify(mockBlocklistedWordRepository).saveBlocklistedWord(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves SyncJobDef entities correctly. + */ + @Test + public void test_saveStructuredData_SyncJobDef() throws Exception { + ReflectionTestUtils.setField(masterDataService, "syncJobDefRepository", mockSyncJobDefRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray syncJobDefs = new JSONArray(); + syncJobDefs.put("{\"id\":\"JOB001\",\"name\":\"Job1\",\"apiName\":\"api1\",\"syncFreq\":\"0 0 12 * * ?\",\"parentSyncJobId\":\"\",\"langCode\":\"eng\",\"lockDuration\":\"0\",\"isActive\":true,\"isDeleted\":false}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(syncJobDefs.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "SyncJobDef", encryptedData, false); + + verify(mockSyncJobDefRepository).saveSyncJobDef(any(SyncJobDef.class)); + } + + /** + * Tests that saveStructuredData saves Language entities correctly. + */ + @Test + public void test_saveStructuredData_Language() throws Exception { + ReflectionTestUtils.setField(masterDataService, "languageRepository", mockLanguageRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray languages = new JSONArray(); + languages.put("{\"code\":\"eng\",\"name\":\"English\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(languages.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "Language", encryptedData, false); + + verify(mockLanguageRepository).saveLanguage(any(JSONObject.class)); + } + + /** + * Tests that saveStructuredData saves RegistrationCenterUser entities when server version is 1.1.5. + */ + @Test + public void test_saveStructuredData_RegistrationCenterUser_version115() throws Exception { + ReflectionTestUtils.setField(masterDataService, "userDetailRepository", mockUserDetailRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.1.5"); + + String encryptedData = "encrypted"; + JSONArray users = new JSONArray(); + users.put("{\"userId\":\"U001\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(users.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "RegistrationCenterUser", encryptedData, false); + + verify(mockUserDetailRepository).saveUserDetail(any(JSONArray.class)); + } + + /** + * Tests that saveStructuredData does not save RegistrationCenterUser entities when server version is not 1.1.5. + */ + @Test + public void test_saveStructuredData_RegistrationCenterUser_notVersion115() throws Exception { + ReflectionTestUtils.setField(masterDataService, "userDetailRepository", mockUserDetailRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + + String encryptedData = "encrypted"; + JSONArray users = new JSONArray(); + users.put("{\"userId\":\"U001\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(users.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "RegistrationCenterUser", encryptedData, false); + + verify(mockUserDetailRepository, never()).saveUserDetail(any(JSONArray.class)); + } + + /** + * Tests that saveStructuredData saves RegistrationCenterMachine entities and sets regCenterId. + */ + @Test + public void test_saveStructuredData_RegistrationCenterMachine() throws Exception { + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray machines = new JSONArray(); + machines.put("{\"regCenterId\":\"CENTER001\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(machines.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "RegistrationCenterMachine", encryptedData, false); + + // Verify regCenterId was set (we can't directly verify, but the method should complete without exception) + assertNotNull(ReflectionTestUtils.getField(masterDataService, "regCenterId")); + } + + /** + * Tests that saveStructuredData saves ValidDocument entities when applicantValidDocPresent is false. + */ + @Test + public void test_saveStructuredData_ValidDocument_notPresent() throws Exception { + ReflectionTestUtils.setField(masterDataService, "applicantValidDocRepository", mockApplicantValidDocRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.DEFAULT_APP_TYPE_CODE)) + .thenReturn("APP_TYPE"); + + String encryptedData = "encrypted"; + JSONArray validDocs = new JSONArray(); + validDocs.put("{\"code\":\"DOC001\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(validDocs.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "ValidDocument", encryptedData, false); + + verify(mockApplicantValidDocRepository).saveApplicantValidDocument(any(JSONObject.class), eq("APP_TYPE")); + } + + /** + * Tests that saveStructuredData does not save ValidDocument entities when applicantValidDocPresent is true. + */ + @Test + public void test_saveStructuredData_ValidDocument_present() throws Exception { + ReflectionTestUtils.setField(masterDataService, "applicantValidDocRepository", mockApplicantValidDocRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray validDocs = new JSONArray(); + validDocs.put("{\"code\":\"DOC001\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(validDocs.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "ValidDocument", encryptedData, true); + + verify(mockApplicantValidDocRepository, never()).saveApplicantValidDocument(any(JSONObject.class), anyString()); + } + + /** + * Tests that saveStructuredData saves PermittedLocalConfig entities and calls cleanUpLocalPreferences when localConfigDAO is not null. + */ + @Test + public void test_saveStructuredData_PermittedLocalConfig_withLocalConfigDAO() throws Exception { + ReflectionTestUtils.setField(masterDataService, "permittedLocalConfigRepository", mockPermittedLocalConfigRepository); + ReflectionTestUtils.setField(masterDataService, "localConfigDAO", mockLocalConfigDao); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray configs = new JSONArray(); + configs.put("{\"code\":\"CONFIG001\",\"name\":\"Config1\",\"type\":\"CONFIGURATION\",\"isActive\":true,\"isDeleted\":false}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(configs.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "PermittedLocalConfig", encryptedData, false); + + verify(mockPermittedLocalConfigRepository).savePermittedConfigs(anyList()); + verify(mockLocalConfigDao).cleanUpLocalPreferences(); + } + + /** + * Tests that saveStructuredData saves PermittedLocalConfig entities and does not call cleanUpLocalPreferences when localConfigDAO is null. + */ + @Test + public void test_saveStructuredData_PermittedLocalConfig_withoutLocalConfigDAO() throws Exception { + ReflectionTestUtils.setField(masterDataService, "permittedLocalConfigRepository", mockPermittedLocalConfigRepository); + ReflectionTestUtils.setField(masterDataService, "localConfigDAO", null); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + String encryptedData = "encrypted"; + JSONArray configs = new JSONArray(); + configs.put("{\"code\":\"CONFIG001\",\"name\":\"Config1\",\"type\":\"CONFIGURATION\",\"isActive\":true,\"isDeleted\":false}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(configs.toString().getBytes()); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveStructuredData", "PermittedLocalConfig", encryptedData, false); + + verify(mockPermittedLocalConfigRepository).savePermittedConfigs(anyList()); + } + + /** + * Tests that saveMasterData processes structured entity type correctly. + */ + @Test + public void test_saveMasterData_structuredEntity() throws Exception { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "reasonListRepository", mockReasonListRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + + ClientSettingDto clientSettingDto = new ClientSettingDto(); + clientSettingDto.setLastSyncTime("2023-01-01"); + + MasterData masterData = new MasterData(); + masterData.setEntityName("ReasonList"); + masterData.setEntityType("structured"); + masterData.setData("encrypted"); + + clientSettingDto.setDataToSync(Collections.singletonList(masterData)); + + String decryptedData = CryptoUtil.base64encoder.encodeToString("[\"{\\\"code\\\":\\\"R001\\\"}\"]".getBytes()); + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveMasterData", clientSettingDto, false); + + verify(mockReasonListRepository).saveReasonList(any(JSONObject.class)); + verify(mockGlobalParamRepository).saveGlobalParam(eq("masterdata.lastupdated"), eq("2023-01-01")); + } + + /** + * Tests that saveMasterData processes dynamic entity type correctly. + */ + @Test + public void test_saveMasterData_dynamicEntity() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "dynamicFieldRepository", mockDynamicFieldRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + ClientSettingDto clientSettingDto = new ClientSettingDto(); + clientSettingDto.setLastSyncTime("2023-01-01"); + + MasterData masterData = new MasterData(); + masterData.setEntityName("DynamicField"); + masterData.setEntityType("dynamic"); + masterData.setData("encrypted"); + + clientSettingDto.setDataToSync(Collections.singletonList(masterData)); + + JSONArray fields = new JSONArray(); + fields.put("{\"fieldName\":\"field1\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(fields.toString().getBytes()); + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveMasterData", clientSettingDto, false); + + verify(mockDynamicFieldRepository).saveDynamicField(any(JSONObject.class)); + verify(mockGlobalParamRepository).saveGlobalParam(eq("masterdata.lastupdated"), eq("2023-01-01")); + } + + /** + * Tests that saveMasterData processes script entity type correctly. + */ + @Test + public void test_saveMasterData_scriptEntity() throws Exception { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "syncRestService", mockSyncRestService); + ReflectionTestUtils.setField(masterDataService, "fileSignatureDao", mockFileSignatureDao); + + File mockFilesDir = new File("test"); + when(mockContext.getFilesDir()).thenReturn(mockFilesDir); + + ClientSettingDto clientSettingDto = new ClientSettingDto(); + clientSettingDto.setLastSyncTime("2023-01-01"); + + MasterData masterData = new MasterData(); + masterData.setEntityName("script.mvel"); + masterData.setEntityType("script"); + String scriptJson = "{\"headers\":\"\",\"encrypted\":false,\"url\":\"http://test.com\"}"; + String encryptedScript = CryptoUtil.base64encoder.encodeToString(scriptJson.getBytes()); + masterData.setData(encryptedScript); + + clientSettingDto.setDataToSync(Collections.singletonList(masterData)); + + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(CryptoUtil.base64encoder.encodeToString(scriptJson.getBytes())); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveMasterData", clientSettingDto, false); + + verify(mockGlobalParamRepository).saveGlobalParam(eq("masterdata.lastupdated"), eq("2023-01-01")); + } + + /** + * Tests that saveMasterData handles exceptions in entity processing gracefully. + */ + @Test + public void test_saveMasterData_handlesException() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + + ClientSettingDto clientSettingDto = new ClientSettingDto(); + clientSettingDto.setLastSyncTime("2023-01-01"); + + MasterData masterData = new MasterData(); + masterData.setEntityName("ReasonList"); + masterData.setEntityType("structured"); + masterData.setData("encrypted"); + + clientSettingDto.setDataToSync(Collections.singletonList(masterData)); + + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))) + .thenThrow(new RuntimeException("Decryption failed")); + + ReflectionTestUtils.invokeMethod(masterDataService, "saveMasterData", clientSettingDto, false); + + // Should still save the last sync time even if entity processing fails + verify(mockGlobalParamRepository).saveGlobalParam(eq("masterdata.lastupdated"), eq("2023-01-01")); + } + + /** + * Tests that syncScript handles successful response with null body. + */ + @Test + public void test_syncScript_successfulResponse_nullBody() throws Exception { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + ReflectionTestUtils.setField(masterDataService, "syncRestService", mockSyncRestService); + ReflectionTestUtils.setField(masterDataService, "fileSignatureDao", mockFileSignatureDao); + + Path path = Paths.get("test.txt"); + Map headers = new HashMap<>(); + Call mockCall = mock(Call.class); + + when(mockSyncRestService.downloadScript(anyString(), anyMap(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback cb = invocation.getArgument(0); + Response response = Response.success(null); + cb.onResponse(mockCall, response); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + ReflectionTestUtils.invokeMethod(masterDataService, "syncScript", onFinish, path, false, "http://test.com", headers, "keyIndex", false); + + verify(mockCall).enqueue(any()); + } + + /** + * Tests that syncScript handles unsuccessful response. + */ + @Test + public void test_syncScript_unsuccessfulResponse() throws Exception { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + ReflectionTestUtils.setField(masterDataService, "syncRestService", mockSyncRestService); + + Path path = Paths.get("test.txt"); + Map headers = new HashMap<>(); + Call mockCall = mock(Call.class); + + when(mockSyncRestService.downloadScript(anyString(), anyMap(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback cb = invocation.getArgument(0); + ResponseBody errorBody = mock(ResponseBody.class); + Response response = Response.error(404, errorBody); + cb.onResponse(mockCall, response); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + ReflectionTestUtils.invokeMethod(masterDataService, "syncScript", onFinish, path, false, "http://test.com", headers, "keyIndex", false); + + verify(mockCall).enqueue(any()); + } + + /** + * Tests that syncScript handles onFailure callback. + */ + @Test + public void test_syncScript_onFailure() throws Exception { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + ReflectionTestUtils.setField(masterDataService, "syncRestService", mockSyncRestService); + + Path path = Paths.get("test.txt"); + Map headers = new HashMap<>(); + Call mockCall = mock(Call.class); + + when(mockSyncRestService.downloadScript(anyString(), anyMap(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback cb = invocation.getArgument(0); + cb.onFailure(mockCall, new IOException("Network error")); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + ReflectionTestUtils.invokeMethod(masterDataService, "syncScript", onFinish, path, false, "http://test.com", headers, "keyIndex", false); + + verify(mockCall).enqueue(any()); + } + + /** + * Tests that syncCertificate handles successful response with error in body. + */ + @Test + public void test_syncCertificate_successfulResponse_withError() { + MasterDataServiceImpl spyService = spy(masterDataService); + doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.getPolicyKey(anyString(), anyString(), anyString())).thenReturn(mockCall); + + ServiceError error = new ServiceError(); + error.setErrorCode("ERROR_CODE"); + error.setMessage("Error message"); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + wrapper.setErrors(Collections.singletonList(error)); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + spyService.syncCertificate(onFinish, "appid", "refid", "setappid", "setrefid", false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncCertificate handles unsuccessful response. + */ + @Test + public void test_syncCertificate_unsuccessfulResponse() { + MasterDataServiceImpl spyService = spy(masterDataService); + doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.getPolicyKey(anyString(), anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + cb.onResponse(mockCall, Response.error(500, mock(okhttp3.ResponseBody.class))); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + spyService.syncCertificate(onFinish, "appid", "refid", "setappid", "setrefid", false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncCertificate handles exception during certificate upload. + */ + @Test + public void test_syncCertificate_exceptionDuringUpload() { + MasterDataServiceImpl spyService = spy(masterDataService); + doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.getPolicyKey(anyString(), anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + CertificateResponse certResponse = new CertificateResponse(); + certResponse.setCertificate("certData"); + wrapper.setResponse(certResponse); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + doThrow(new RuntimeException("Upload failed")) + .when(mockCertificateManagerService).uploadOtherDomainCertificate(any(CertificateRequestDto.class)); + + Runnable onFinish = mock(Runnable.class); + spyService.syncCertificate(onFinish, "appid", "refid", "setappid", "setrefid", false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncMasterData handles exception getting client key index. + */ + @Test + public void test_syncMasterData_exceptionGettingKeyIndex() throws Exception { + MasterDataServiceImpl spyService = spy(masterDataService); + doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); + + when(mockClientCryptoManagerService.getClientKeyIndex()) + .thenThrow(new RuntimeException("Key index error")); + + Runnable onFinish = mock(Runnable.class); + spyService.syncMasterData(onFinish, 0, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncMasterData handles null centerMachineDto with retry. + */ + @Test + public void test_syncMasterData_nullCenterMachineDto_withRetry() throws Exception { + MasterDataServiceImpl spyService = spy(masterDataService); + doReturn(null).when(spyService).getRegistrationCenterMachineDetails(); + + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchMasterData(any())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + ClientSettingDto dto = new ClientSettingDto(); + dto.setDataToSync(Collections.emptyList()); + dto.setLastSyncTime("now"); + wrapper.setResponse(dto); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + spyService.syncMasterData(onFinish, 0, false, "jobId"); + + verify(onFinish, atLeastOnce()).run(); + } + + /** + * Tests that syncMasterData handles null centerMachineDto without retry (max retries reached). + */ + @Test + public void test_syncMasterData_nullCenterMachineDto_maxRetries() throws Exception { + MasterDataServiceImpl spyService = spy(masterDataService); + doReturn(null).when(spyService).getRegistrationCenterMachineDetails(); + + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchMasterData(any())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + ClientSettingDto dto = new ClientSettingDto(); + dto.setDataToSync(Collections.emptyList()); + dto.setLastSyncTime("now"); + wrapper.setResponse(dto); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + spyService.syncMasterData(onFinish, 3, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncMasterData handles regCenterId not null and updates machine. + */ + @Test + public void test_syncMasterData_withRegCenterId() throws Exception { + MasterDataServiceImpl spyService = spy(masterDataService); + ReflectionTestUtils.setField(spyService, "machineRepository", mockMachineRepository); + ReflectionTestUtils.setField(spyService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(spyService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(spyService, "syncRestService", mockSyncRestService); + ReflectionTestUtils.setField(spyService, "context", mockContext); + CenterMachineDto centerMachineDto = new CenterMachineDto(); + doReturn(centerMachineDto).when(spyService).getRegistrationCenterMachineDetails(); + + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + when(mockClientCryptoManagerService.getMachineName()).thenReturn("machine1"); + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchMasterData(any())).thenReturn(mockCall); + + ReflectionTestUtils.setField(spyService, "globalParamRepository", mockGlobalParamRepository); + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + ClientSettingDto dto = new ClientSettingDto(); + MasterData machineData = new MasterData(); + machineData.setEntityName("RegistrationCenterMachine"); + machineData.setEntityType("structured"); + machineData.setData("encrypted"); + dto.setDataToSync(Collections.singletonList(machineData)); + dto.setLastSyncTime("now"); + wrapper.setResponse(dto); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + JSONArray machines = new JSONArray(); + machines.put("{\"regCenterId\":\"CENTER001\"}"); + String decryptedData = CryptoUtil.base64encoder.encodeToString(machines.toString().getBytes()); + CryptoResponseDto cryptoResponseDto = new CryptoResponseDto(); + cryptoResponseDto.setValue(decryptedData); + when(mockClientCryptoManagerService.decrypt(any(CryptoRequestDto.class))).thenReturn(cryptoResponseDto); + + Runnable onFinish = mock(Runnable.class); + spyService.syncMasterData(onFinish, 0, false, "jobId"); + + verify(mockMachineRepository).updateMachine(eq("machine1"), eq("CENTER001")); + verify(onFinish).run(); + } + + /** + * Tests that syncGlobalParamsData handles successful response with error. + */ + @Test + public void test_syncGlobalParamsData_successfulResponse_withError() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + + Call>> mockCall = mock(Call.class); + when(mockSyncRestService.getGlobalConfigs(anyString(), anyString())).thenReturn(mockCall); + + ServiceError error = new ServiceError(); + error.setErrorCode("ERROR_CODE"); + error.setMessage("Error message"); + + doAnswer(invocation -> { + Callback>> cb = invocation.getArgument(0); + ResponseWrapper> wrapper = new ResponseWrapper<>(); + wrapper.setErrors(Collections.singletonList(error)); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncGlobalParamsData(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncGlobalParamsData handles unsuccessful response. + */ + @Test + public void test_syncGlobalParamsData_unsuccessfulResponse() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + + Call>> mockCall = mock(Call.class); + when(mockSyncRestService.getGlobalConfigs(anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback>> cb = invocation.getArgument(0); + cb.onResponse(mockCall, Response.error(500, mock(okhttp3.ResponseBody.class))); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncGlobalParamsData(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncGlobalParamsData handles onFailure callback. + */ + @Test + public void test_syncGlobalParamsData_onFailure() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + + Call>> mockCall = mock(Call.class); + when(mockSyncRestService.getGlobalConfigs(anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback>> cb = invocation.getArgument(0); + cb.onFailure(mockCall, new IOException("Network error")); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncGlobalParamsData(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncGlobalParamsData uses V1 API when server version is 1.1.5. + */ + @Test + public void test_syncGlobalParamsData_version115() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.1.5"); + when(mockClientCryptoManagerService.getMachineName()).thenReturn("machine1"); + + Call>> mockCall = mock(Call.class); + when(mockSyncRestService.getV1GlobalConfigs(anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback>> cb = invocation.getArgument(0); + ResponseWrapper> wrapper = new ResponseWrapper<>(); + wrapper.setResponse(new HashMap<>()); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncGlobalParamsData(onFinish, false, "jobId"); + + verify(mockSyncRestService).getV1GlobalConfigs(anyString(), anyString()); + verify(onFinish).run(); + } + + + /** + * Tests that syncLatestIdSchema handles unsuccessful response. + */ + @Test + public void test_syncLatestIdSchema_unsuccessfulResponse() { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + Call mockCall = mock(Call.class); + when(mockSyncRestService.getLatestIdSchema(anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback cb = invocation.getArgument(0); + cb.onResponse(mockCall, Response.error(500, mock(okhttp3.ResponseBody.class))); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncLatestIdSchema(onFinish, false); + + verify(onFinish).run(); + } + + /** + * Tests that syncLatestIdSchema handles onFailure callback. + */ + @Test + public void test_syncLatestIdSchema_onFailure() { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + Call mockCall = mock(Call.class); + when(mockSyncRestService.getLatestIdSchema(anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback cb = invocation.getArgument(0); + cb.onFailure(mockCall, new IOException("Network error")); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncLatestIdSchema(onFinish, false); + + verify(onFinish).run(); + } + + /** + * Tests that syncLatestIdSchema handles exception during save. + */ + @Test + public void test_syncLatestIdSchema_exceptionDuringSave() { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + ReflectionTestUtils.setField(masterDataService, "identitySchemaRepository", mockIdentitySchemaRepository); + + Call mockCall = mock(Call.class); + when(mockSyncRestService.getLatestIdSchema(anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback cb = invocation.getArgument(0); + ResponseBody mockBody = mock(ResponseBody.class); + try { + when(mockBody.string()).thenReturn("invalid json"); + } catch (IOException e) { + fail("Mock setup failed"); + } + cb.onResponse(mockCall, Response.success(mockBody)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncLatestIdSchema(onFinish, false); + + verify(onFinish).run(); + } + + /** + * Tests that syncUserDetails handles successful response with error. + */ + @Test + public void test_syncUserDetails_successfulResponse_withError() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchCenterUserDetails(anyString(), anyString())).thenReturn(mockCall); + + ServiceError error = new ServiceError(); + error.setErrorCode("ERROR_CODE"); + error.setMessage("Error message"); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + wrapper.setErrors(Collections.singletonList(error)); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncUserDetails(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncUserDetails handles unsuccessful response. + */ + @Test + public void test_syncUserDetails_unsuccessfulResponse() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchCenterUserDetails(anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + cb.onResponse(mockCall, Response.error(500, mock(okhttp3.ResponseBody.class))); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncUserDetails(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncUserDetails handles onFailure callback. + */ + @Test + public void test_syncUserDetails_onFailure() throws Exception { + ReflectionTestUtils.setField(masterDataService, "globalParamRepository", mockGlobalParamRepository); + ReflectionTestUtils.setField(masterDataService, "clientCryptoManagerService", mockClientCryptoManagerService); + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchCenterUserDetails(anyString(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + cb.onFailure(mockCall, new IOException("Network error")); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncUserDetails(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncCACertificates handles successful response with error. + */ + @Test + public void test_syncCACertificates_successfulResponse_withError() { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + ReflectionTestUtils.setField(masterDataService, "certificateManagerService", mockCertificateManagerService); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.getCACertificates(any(), anyString())).thenReturn(mockCall); + + ServiceError error = new ServiceError(); + error.setErrorCode("ERROR_CODE"); + error.setMessage("Error message"); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + wrapper.setErrors(Collections.singletonList(error)); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncCACertificates(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncCACertificates handles unsuccessful response. + */ + @Test + public void test_syncCACertificates_unsuccessfulResponse() { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.getCACertificates(any(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + cb.onResponse(mockCall, Response.error(500, mock(okhttp3.ResponseBody.class))); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncCACertificates(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncCACertificates handles onFailure callback. + */ + @Test + public void test_syncCACertificates_onFailure() { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.getCACertificates(any(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + cb.onFailure(mockCall, new IOException("Network error")); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncCACertificates(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncCACertificates handles exception during save. + */ + @Test + public void test_syncCACertificates_exceptionDuringSave() { + ReflectionTestUtils.setField(masterDataService, "context", mockContext); + ReflectionTestUtils.setField(masterDataService, "certificateManagerService", mockCertificateManagerService); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.getCACertificates(any(), anyString())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + CACertificateResponseDto response = new CACertificateResponseDto(); + CACertificateDto cert = new CACertificateDto(); + cert.setCertId("CERT001"); + cert.setCertData("certData"); + cert.setPartnerDomain("DEVICE"); + cert.setCreatedtimes(LocalDateTime.now()); + response.setCertificateDTOList(Collections.singletonList(cert)); + wrapper.setResponse(response); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + when(mockCertificateManagerService.uploadCACertificate(any(CACertificateRequestDto.class))) + .thenThrow(new RuntimeException("Save failed")); + + Runnable onFinish = mock(Runnable.class); + masterDataService.syncCACertificates(onFinish, false, "jobId"); + + verify(onFinish).run(); + } + + /** + * Tests that syncMasterData uses V1 API when server version is 1.1.5. + */ + @Test + public void test_syncMasterData_version115() throws Exception { + MasterDataServiceImpl spyService = spy(masterDataService); + doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); + + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.1.5"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchV1MasterData(any())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + ClientSettingDto dto = new ClientSettingDto(); + dto.setDataToSync(Collections.emptyList()); + dto.setLastSyncTime("now"); + wrapper.setResponse(dto); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + spyService.syncMasterData(onFinish, 0, false, ""); + + verify(mockSyncRestService).fetchV1MasterData(any()); + verify(onFinish).run(); + } + + /** + * Tests that syncMasterData includes delta parameter when lastUpdated is not null. + */ + @Test + public void test_syncMasterData_withDelta() throws Exception { + MasterDataServiceImpl spyService = spy(masterDataService); + doReturn(new CenterMachineDto()).when(spyService).getRegistrationCenterMachineDetails(); + + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn("2023-01-01"); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchMasterData(any())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + ClientSettingDto dto = new ClientSettingDto(); + dto.setDataToSync(Collections.emptyList()); + dto.setLastSyncTime("now"); + wrapper.setResponse(dto); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + spyService.syncMasterData(onFinish, 0, false, ""); + + verify(mockSyncRestService).fetchMasterData(any()); + verify(onFinish).run(); + } + + /** + * Tests that syncMasterData includes regCenterId when centerMachineDto is not null. + */ + @Test + public void test_syncMasterData_withRegCenterIdInQuery() throws Exception { + MasterDataServiceImpl spyService = spy(masterDataService); + CenterMachineDto centerMachineDto = new CenterMachineDto(); + centerMachineDto.setCenterId("CENTER001"); + doReturn(centerMachineDto).when(spyService).getRegistrationCenterMachineDetails(); + + when(mockClientCryptoManagerService.getClientKeyIndex()).thenReturn("keyIndex"); + when(mockGlobalParamRepository.getGlobalParamValue("masterdata.lastupdated")).thenReturn(null); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("1.2.0"); + + Call> mockCall = mock(Call.class); + when(mockSyncRestService.fetchMasterData(any())).thenReturn(mockCall); + + doAnswer(invocation -> { + Callback> cb = invocation.getArgument(0); + ResponseWrapper wrapper = new ResponseWrapper<>(); + ClientSettingDto dto = new ClientSettingDto(); + dto.setDataToSync(Collections.emptyList()); + dto.setLastSyncTime("now"); + wrapper.setResponse(dto); + cb.onResponse(mockCall, Response.success(wrapper)); + return null; + }).when(mockCall).enqueue(any()); + + Runnable onFinish = mock(Runnable.class); + spyService.syncMasterData(onFinish, 0, false, ""); + + verify(mockSyncRestService).fetchMasterData(any()); + verify(onFinish).run(); + } } \ No newline at end of file diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PacketServiceImplTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PacketServiceImplTest.java index 1e01fb474..45f30dd09 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PacketServiceImplTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PacketServiceImplTest.java @@ -436,10 +436,10 @@ public void test_sync_all_packet_status_success() { callback.onResponse(mockCall, httpResponse); - Mockito.verify(mockRegistrationRepository).updateStatus( + Mockito.verify(mockRegistrationRepository).updateServerStatusWithTimestamp( Mockito.eq("reg123"), - Mockito.anyString(), - Mockito.eq(PacketClientStatus.UPLOADED.name()) + Mockito.eq("UPLOADED"), + Mockito.anyLong() ); } } @@ -947,4 +947,331 @@ public void test_getPacketStatus_serverStatusNull() { assertEquals(PacketClientStatus.APPROVED.name(), status); } + @Test + public void test_isRegisteredPacketApprovalTimeBreached_nullLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_TIME_APPRV_LIMIT)) + .thenReturn(null); + + boolean result = packetService.isRegisteredPacketApprovalTimeBreached(); + + assertFalse(result); + } + + @Test + public void test_isRegisteredPacketApprovalTimeBreached_emptyLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_TIME_APPRV_LIMIT)) + .thenReturn(""); + + boolean result = packetService.isRegisteredPacketApprovalTimeBreached(); + + assertFalse(result); + } + + @Test + public void test_isRegisteredPacketApprovalTimeBreached_invalidLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_TIME_APPRV_LIMIT)) + .thenReturn("invalid"); + + boolean result = packetService.isRegisteredPacketApprovalTimeBreached(); + + assertFalse(result); + } + + @Test + public void test_isRegisteredPacketApprovalTimeBreached_zeroLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_TIME_APPRV_LIMIT)) + .thenReturn("0"); + + boolean result = packetService.isRegisteredPacketApprovalTimeBreached(); + + assertFalse(result); + } + + @Test + public void test_isRegisteredPacketApprovalTimeBreached_negativeLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_TIME_APPRV_LIMIT)) + .thenReturn("-5"); + + boolean result = packetService.isRegisteredPacketApprovalTimeBreached(); + + assertFalse(result); + } + + @Test + public void test_isRegisteredPacketApprovalTimeBreached_noOldestRegistration_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_TIME_APPRV_LIMIT)) + .thenReturn("5"); + when(mockRegistrationRepository.getOldestRegistrationByStatus(PacketClientStatus.CREATED.name())) + .thenReturn(null); + + boolean result = packetService.isRegisteredPacketApprovalTimeBreached(); + + assertFalse(result); + } + + @Test + public void test_isRegisteredPacketApprovalTimeBreached_timeNotBreached_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_TIME_APPRV_LIMIT)) + .thenReturn("30"); + Registration reg = new Registration("id"); + reg.setCrDtime(System.currentTimeMillis() - (10L * 24 * 60 * 60 * 1000)); // 10 days ago + when(mockRegistrationRepository.getOldestRegistrationByStatus(PacketClientStatus.CREATED.name())) + .thenReturn(reg); + + boolean result = packetService.isRegisteredPacketApprovalTimeBreached(); + + assertFalse(result); + } + + @Test + public void test_isRegisteredPacketApprovalTimeBreached_timeBreached_returnsTrue() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_TIME_APPRV_LIMIT)) + .thenReturn("5"); + Registration reg = new Registration("id"); + reg.setCrDtime(System.currentTimeMillis() - (10L * 24 * 60 * 60 * 1000)); // 10 days ago + when(mockRegistrationRepository.getOldestRegistrationByStatus(PacketClientStatus.CREATED.name())) + .thenReturn(reg); + + boolean result = packetService.isRegisteredPacketApprovalTimeBreached(); + + assertTrue(result); + } + + @Test + public void test_validatingLastExportDuration_nullLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.OPT_TO_REG_LAST_EXPORT_REG_PKTS_TIME)) + .thenReturn(null); + + boolean result = packetService.validatingLastExportDuration(); + + assertFalse(result); + } + + @Test + public void test_validatingLastExportDuration_emptyLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.OPT_TO_REG_LAST_EXPORT_REG_PKTS_TIME)) + .thenReturn(""); + + boolean result = packetService.validatingLastExportDuration(); + + assertFalse(result); + } + + @Test + public void test_validatingLastExportDuration_invalidLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.OPT_TO_REG_LAST_EXPORT_REG_PKTS_TIME)) + .thenReturn("invalid"); + + boolean result = packetService.validatingLastExportDuration(); + + assertFalse(result); + } + + @Test + public void test_validatingLastExportDuration_zeroLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.OPT_TO_REG_LAST_EXPORT_REG_PKTS_TIME)) + .thenReturn("0"); + + boolean result = packetService.validatingLastExportDuration(); + + assertFalse(result); + } + + @Test + public void test_validatingLastExportDuration_noOldestRegistration_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.OPT_TO_REG_LAST_EXPORT_REG_PKTS_TIME)) + .thenReturn("5"); + when(mockRegistrationRepository.getOldestRegistrationByStatus(PacketClientStatus.APPROVED.name())) + .thenReturn(null); + + boolean result = packetService.validatingLastExportDuration(); + + assertFalse(result); + } + + @Test + public void test_validatingLastExportDuration_nullCreationTime_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.OPT_TO_REG_LAST_EXPORT_REG_PKTS_TIME)) + .thenReturn("5"); + Registration reg = new Registration("id"); + reg.setCrDtime(null); + when(mockRegistrationRepository.getOldestRegistrationByStatus(PacketClientStatus.APPROVED.name())) + .thenReturn(reg); + + boolean result = packetService.validatingLastExportDuration(); + + assertFalse(result); + } + + @Test + public void test_validatingLastExportDuration_timeNotBreached_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.OPT_TO_REG_LAST_EXPORT_REG_PKTS_TIME)) + .thenReturn("30"); + Registration reg = new Registration("id"); + reg.setCrDtime(System.currentTimeMillis() - (10L * 24 * 60 * 60 * 1000)); // 10 days ago + when(mockRegistrationRepository.getOldestRegistrationByStatus(PacketClientStatus.APPROVED.name())) + .thenReturn(reg); + + boolean result = packetService.validatingLastExportDuration(); + + assertFalse(result); + } + + @Test + public void test_validatingLastExportDuration_timeBreached_returnsTrue() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.OPT_TO_REG_LAST_EXPORT_REG_PKTS_TIME)) + .thenReturn("5"); + Registration reg = new Registration("id"); + reg.setCrDtime(System.currentTimeMillis() - (10L * 24 * 60 * 60 * 1000)); // 10 days ago + when(mockRegistrationRepository.getOldestRegistrationByStatus(PacketClientStatus.APPROVED.name())) + .thenReturn(reg); + + boolean result = packetService.validatingLastExportDuration(); + + assertTrue(result); + } + + @Test + public void test_isMaxPacketCountLimitReached_nullLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_CNT_OFFLINE_FREQ)) + .thenReturn(null); + + boolean result = packetService.isMaxPacketCountLimitReached(); + + assertFalse(result); + } + + @Test + public void test_isMaxPacketCountLimitReached_emptyLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_CNT_OFFLINE_FREQ)) + .thenReturn(""); + + boolean result = packetService.isMaxPacketCountLimitReached(); + + assertFalse(result); + } + + @Test + public void test_isMaxPacketCountLimitReached_invalidLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_CNT_OFFLINE_FREQ)) + .thenReturn("invalid"); + + boolean result = packetService.isMaxPacketCountLimitReached(); + + assertFalse(result); + } + + @Test + public void test_isMaxPacketCountLimitReached_zeroLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_CNT_OFFLINE_FREQ)) + .thenReturn("0"); + + boolean result = packetService.isMaxPacketCountLimitReached(); + + assertFalse(result); + } + + @Test + public void test_isMaxPacketCountLimitReached_countBelowLimit_returnsFalse() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_CNT_OFFLINE_FREQ)) + .thenReturn("100"); + when(mockRegistrationRepository.getYetToExportCount()).thenReturn(50); + + boolean result = packetService.isMaxPacketCountLimitReached(); + + assertFalse(result); + } + + @Test + public void test_isMaxPacketCountLimitReached_countAtLimit_returnsTrue() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_CNT_OFFLINE_FREQ)) + .thenReturn("100"); + when(mockRegistrationRepository.getYetToExportCount()).thenReturn(100); + + boolean result = packetService.isMaxPacketCountLimitReached(); + + assertTrue(result); + } + + @Test + public void test_isMaxPacketCountLimitReached_countAboveLimit_returnsTrue() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_PAK_MAX_CNT_OFFLINE_FREQ)) + .thenReturn("100"); + when(mockRegistrationRepository.getYetToExportCount()).thenReturn(150); + + boolean result = packetService.isMaxPacketCountLimitReached(); + + assertTrue(result); + } + + @Test + public void test_deleteRegistrationPackets_nullConfiguredDays() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS)) + .thenReturn(null); + + packetService.deleteRegistrationPackets(); + + verify(mockGlobalParamRepository).getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS); + verify(mockRegistrationRepository, never()).findByServerStatusAndCrDtimeBefore(any(), anyLong()); + } + + @Test + public void test_deleteRegistrationPackets_invalidConfiguredDays() { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS)) + .thenReturn("invalid"); + + packetService.deleteRegistrationPackets(); + + verify(mockGlobalParamRepository).getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS); + verify(mockRegistrationRepository, never()).findByServerStatusAndCrDtimeBefore(any(), anyLong()); + } + + @Test + public void test_deleteRegistrationPackets_noRegistrationsFound() throws Exception { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS)) + .thenReturn("30"); + when(mockRegistrationRepository.findByServerStatusAndCrDtimeBefore(any(), anyLong())) + .thenReturn(Collections.emptyList()); + + packetService.deleteRegistrationPackets(); + + verify(mockGlobalParamRepository).getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS); + verify(mockRegistrationRepository).findByServerStatusAndCrDtimeBefore(any(), anyLong()); + verify(mockRegistrationRepository, never()).deleteRegistration(anyString()); + } + + @Test + public void test_deleteRegistrationPackets_withRegistrations_deletesFilesAndRecords() throws Exception { + String filePath = File.createTempFile("test", ".zip").getAbsolutePath(); + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS)) + .thenReturn("30"); + Registration reg = new Registration("packet1"); + reg.setFilePath(filePath); + reg.setPacketId("packet1"); + when(mockRegistrationRepository.findByServerStatusAndCrDtimeBefore(any(), anyLong())) + .thenReturn(Collections.singletonList(reg)); + + packetService.deleteRegistrationPackets(); + + verify(mockGlobalParamRepository).getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS); + verify(mockRegistrationRepository).findByServerStatusAndCrDtimeBefore(any(), anyLong()); + verify(mockRegistrationRepository).deleteRegistration("packet1"); + } + + @Test + public void test_deleteRegistrationPackets_nullFilePath_skipsFileDeletion() throws Exception { + when(mockGlobalParamRepository.getCachedStringGlobalParam(RegistrationConstants.REG_DELETION_CONFIGURED_DAYS)) + .thenReturn("30"); + Registration reg = new Registration("packet1"); + reg.setFilePath(null); + reg.setPacketId("packet1"); + when(mockRegistrationRepository.findByServerStatusAndCrDtimeBefore(any(), anyLong())) + .thenReturn(Collections.singletonList(reg)); + + packetService.deleteRegistrationPackets(); + + verify(mockRegistrationRepository).findByServerStatusAndCrDtimeBefore(any(), anyLong()); + verify(mockRegistrationRepository).deleteRegistration("packet1"); + } + } diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PreCheckValidatorServiceImplTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PreCheckValidatorServiceImplTest.java index 358aa4672..56b3faff5 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PreCheckValidatorServiceImplTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PreCheckValidatorServiceImplTest.java @@ -39,7 +39,7 @@ * * @author Sachin S P */ -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) public class PreCheckValidatorServiceImplTest { @Mock @@ -102,16 +102,18 @@ public void testValidateSyncStatus_Success_AllJobsWithinLimit() throws Exception // Setup: Configure frequencies when(mockGlobalParamRepository.getCachedStringGlobalParam( - RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + RegistrationConstants.FREQUENCY)) - .thenReturn("190"); + RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + + RegistrationConstants.FREQUENCY)) + .thenReturn("190"); when(mockGlobalParamRepository.getCachedStringGlobalParam( - RegistrationConstants.MOSIP_REGISTRATION + API_NAME_2 + RegistrationConstants.DOT + RegistrationConstants.FREQUENCY)) - .thenReturn("190"); + RegistrationConstants.MOSIP_REGISTRATION + API_NAME_2 + RegistrationConstants.DOT + + RegistrationConstants.FREQUENCY)) + .thenReturn("190"); // Setup: Last sync times (within limit - 1 day ago) when(mockJobManagerService.generateJobServiceId(JOB_ID_1)).thenReturn(SERVICE_JOB_ID_1); when(mockJobManagerService.generateJobServiceId(JOB_ID_2)).thenReturn(SERVICE_JOB_ID_2); - + long oneDayAgo = System.currentTimeMillis() - (24 * 60 * 60 * 1000L); when(mockJobTransactionService.getLastSyncTime(SERVICE_JOB_ID_1)).thenReturn(oneDayAgo); when(mockJobTransactionService.getLastSyncTime(SERVICE_JOB_ID_2)).thenReturn(oneDayAgo); @@ -131,8 +133,9 @@ public void testValidateSyncStatus_Failure_JobOverdue() throws Exception { // Setup: Configure frequency (1 day limit) when(mockGlobalParamRepository.getCachedStringGlobalParam( - RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + RegistrationConstants.FREQUENCY)) - .thenReturn("1"); + RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + + RegistrationConstants.FREQUENCY)) + .thenReturn("1"); // Setup: Last sync time (2 days ago - overdue) when(mockJobManagerService.generateJobServiceId(JOB_ID_1)).thenReturn(SERVICE_JOB_ID_1); @@ -163,8 +166,9 @@ public void testValidateSyncStatus_JobWithoutSyncHistory_Skipped() throws Except // Setup: Configure frequency when(mockGlobalParamRepository.getCachedStringGlobalParam( - RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + RegistrationConstants.FREQUENCY)) - .thenReturn("190"); + RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + + RegistrationConstants.FREQUENCY)) + .thenReturn("190"); // Setup: No sync history (returns 0) - job should be skipped when(mockJobManagerService.generateJobServiceId(JOB_ID_1)).thenReturn(SERVICE_JOB_ID_1); @@ -197,33 +201,33 @@ public void testValidateSyncStatus_NoFrequencyConfigured_Skipped() throws Except public void testValidateSyncStatus_MultipleJobsOverdue() throws Exception { // Setup: Create multiple active jobs List activeJobs = new ArrayList<>(); - SyncJobDef job1 = new SyncJobDef(); - job1.setId(JOB_ID_1); + SyncJobDef job1 = new SyncJobDef(JOB_ID_1); job1.setApiName(API_NAME_1); job1.setIsActive(true); - - SyncJobDef job2 = new SyncJobDef(); - job2.setId(JOB_ID_2); + + SyncJobDef job2 = new SyncJobDef(JOB_ID_2); job2.setApiName(API_NAME_2); job2.setIsActive(true); - + activeJobs.add(job1); activeJobs.add(job2); - + when(mockSyncJobDefRepository.getActiveSyncJobs()).thenReturn(activeJobs); // Setup: Configure frequencies (1 day limit) when(mockGlobalParamRepository.getCachedStringGlobalParam( - RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + RegistrationConstants.FREQUENCY)) - .thenReturn("1"); + RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + + RegistrationConstants.FREQUENCY)) + .thenReturn("1"); when(mockGlobalParamRepository.getCachedStringGlobalParam( - RegistrationConstants.MOSIP_REGISTRATION + API_NAME_2 + RegistrationConstants.DOT + RegistrationConstants.FREQUENCY)) - .thenReturn("1"); + RegistrationConstants.MOSIP_REGISTRATION + API_NAME_2 + RegistrationConstants.DOT + + RegistrationConstants.FREQUENCY)) + .thenReturn("1"); // Setup: Both jobs overdue (2 days ago) when(mockJobManagerService.generateJobServiceId(JOB_ID_1)).thenReturn(SERVICE_JOB_ID_1); when(mockJobManagerService.generateJobServiceId(JOB_ID_2)).thenReturn(SERVICE_JOB_ID_2); - + long twoDaysAgo = System.currentTimeMillis() - (2 * 24 * 60 * 60 * 1000L); when(mockJobTransactionService.getLastSyncTime(SERVICE_JOB_ID_1)).thenReturn(twoDaysAgo); when(mockJobTransactionService.getLastSyncTime(SERVICE_JOB_ID_2)).thenReturn(twoDaysAgo); @@ -244,7 +248,7 @@ public void testValidateSyncStatus_MultipleJobsOverdue() throws Exception { @Test public void testValidateCenterToMachineDistance_GPSDisabled_Skipped() throws Exception { // Setup: GPS validation disabled - when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); + when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); // Execute preCheckValidatorService.validateCenterToMachineDistance(77.5946, 12.9716); @@ -269,16 +273,14 @@ public void testValidateCenterToMachineDistance_LocationNull_Skipped() throws Ex @Test public void testValidateCenterToMachineDistance_WithinDistance_Success() throws Exception { // Setup: GPS enabled - when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); + when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Setup: Center details CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterId(CENTER_ID); when(mockMasterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - RegistrationCenter center = new RegistrationCenter(); - center.setId(CENTER_ID); - center.setLangCode("eng"); + RegistrationCenter center = new RegistrationCenter(CENTER_ID, "eng"); center.setLatitude("12.9716"); center.setLongitude("77.5946"); List centers = new ArrayList<>(); @@ -287,7 +289,7 @@ public void testValidateCenterToMachineDistance_WithinDistance_Success() throws // Setup: Distance calculation (within limit - 100 meters) when(mockLocationValidationService.getDistance(78.5946, 13.9716, 77.5946, 12.9716)) - .thenReturn(0.1); // 0.1 km = 100 meters + .thenReturn(0.1); // 0.1 km = 100 meters // Setup: Max allowed distance (500 meters) when(mockGlobalParamRepository.getCachedStringMachineToCenterDistance()).thenReturn("500"); @@ -302,16 +304,14 @@ public void testValidateCenterToMachineDistance_WithinDistance_Success() throws @Test(expected = ClientCheckedException.class) public void testValidateCenterToMachineDistance_OutsideDistance_ThrowsException() throws Exception { // Setup: GPS enabled - when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); + when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Setup: Center details CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterId(CENTER_ID); when(mockMasterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - RegistrationCenter center = new RegistrationCenter(); - center.setId(CENTER_ID); - center.setLangCode("eng"); + RegistrationCenter center = new RegistrationCenter(CENTER_ID, "eng"); center.setLatitude("12.9716"); center.setLongitude("77.5946"); List centers = new ArrayList<>(); @@ -320,7 +320,7 @@ public void testValidateCenterToMachineDistance_OutsideDistance_ThrowsException( // Setup: Distance calculation (outside limit - 1000 meters) when(mockLocationValidationService.getDistance(78.5946, 13.9716, 77.5946, 12.9716)) - .thenReturn(1.0); // 1.0 km = 1000 meters + .thenReturn(1.0); // 1.0 km = 1000 meters // Setup: Max allowed distance (500 meters) when(mockGlobalParamRepository.getCachedStringMachineToCenterDistance()).thenReturn("500"); @@ -380,14 +380,15 @@ public void testValidateCenterToMachineDistance_EmptyCentersList_ThrowsException @Test(expected = ClientCheckedException.class) public void testValidateCenterToMachineDistance_CenterCoordinatesMissing_ThrowsException() throws Exception { // Setup: GPS enabled - when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); + when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Setup: Center details CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterId(CENTER_ID); when(mockMasterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - RegistrationCenter center = new RegistrationCenter(); + RegistrationCenter center = new RegistrationCenter(CENTER_ID, "eng"); + center.setLatitude(null); // Missing coordinates center.setLongitude(null); List centers = new ArrayList<>(); @@ -401,16 +402,14 @@ public void testValidateCenterToMachineDistance_CenterCoordinatesMissing_ThrowsE @Test(expected = ClientCheckedException.class) public void testValidateCenterToMachineDistance_MaxDistanceConfigMissing_ThrowsException() throws Exception { // Setup: GPS enabled - when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); + when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Setup: Center details CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterId(CENTER_ID); when(mockMasterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - RegistrationCenter center = new RegistrationCenter(); - center.setId(CENTER_ID); - center.setLangCode("eng"); + RegistrationCenter center = new RegistrationCenter(CENTER_ID, "eng"); center.setLatitude("12.9716"); center.setLongitude("77.5946"); List centers = new ArrayList<>(); @@ -419,7 +418,7 @@ public void testValidateCenterToMachineDistance_MaxDistanceConfigMissing_ThrowsE // Setup: Distance calculation when(mockLocationValidationService.getDistance(78.5946, 13.9716, 77.5946, 12.9716)) - .thenReturn(0.1); + .thenReturn(0.1); // Setup: Max distance config missing when(mockGlobalParamRepository.getCachedStringMachineToCenterDistance()).thenReturn(null); @@ -431,16 +430,14 @@ public void testValidateCenterToMachineDistance_MaxDistanceConfigMissing_ThrowsE @Test public void testValidateCenterToMachineDistance_InvalidCoordinateFormat_ThrowsException() throws Exception { // Setup: GPS enabled - when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); + when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Setup: Center details CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterId(CENTER_ID); when(mockMasterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - RegistrationCenter center = new RegistrationCenter(); - center.setId(CENTER_ID); - center.setLangCode("eng"); + RegistrationCenter center = new RegistrationCenter(CENTER_ID, "eng"); center.setLatitude("invalid"); // Invalid format center.setLongitude("77.5946"); List centers = new ArrayList<>(); @@ -460,12 +457,11 @@ public void testValidateCenterToMachineDistance_InvalidCoordinateFormat_ThrowsEx public void testValidateSyncStatus_JobWithNullId_Skipped() throws Exception { // Setup: Create job with null ID List activeJobs = new ArrayList<>(); - SyncJobDef job = new SyncJobDef(); - job.setId(null); - job.setApiName(API_NAME_1); + SyncJobDef job = new SyncJobDef(JOB_ID_1); + job.setApiName(null); job.setIsActive(true); activeJobs.add(job); - + when(mockSyncJobDefRepository.getActiveSyncJobs()).thenReturn(activeJobs); // Execute @@ -479,12 +475,11 @@ public void testValidateSyncStatus_JobWithNullId_Skipped() throws Exception { public void testValidateSyncStatus_JobWithNullApiName_Skipped() throws Exception { // Setup: Create job with null apiName List activeJobs = new ArrayList<>(); - SyncJobDef job = new SyncJobDef(); - job.setId(JOB_ID_1); + SyncJobDef job = new SyncJobDef(JOB_ID_1); job.setApiName(null); job.setIsActive(true); activeJobs.add(job); - + when(mockSyncJobDefRepository.getActiveSyncJobs()).thenReturn(activeJobs); // Execute @@ -502,8 +497,9 @@ public void testValidateSyncStatus_InvalidFrequencyValue_ThrowsException() throw // Setup: Invalid frequency value (non-numeric) when(mockGlobalParamRepository.getCachedStringGlobalParam( - RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + RegistrationConstants.FREQUENCY)) - .thenReturn("invalid"); + RegistrationConstants.MOSIP_REGISTRATION + API_NAME_1 + RegistrationConstants.DOT + + RegistrationConstants.FREQUENCY)) + .thenReturn("invalid"); // Execute - should throw exception due to invalid frequency value preCheckValidatorService.validateSyncStatus(); @@ -512,16 +508,14 @@ public void testValidateSyncStatus_InvalidFrequencyValue_ThrowsException() throw @Test public void testValidateCenterToMachineDistance_ExactDistanceLimit_Passes() throws Exception { // Setup: GPS enabled - when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); + when(mockGlobalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Setup: Center details CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterId(CENTER_ID); when(mockMasterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - RegistrationCenter center = new RegistrationCenter(); - center.setId(CENTER_ID); - center.setLangCode("eng"); + RegistrationCenter center = new RegistrationCenter(CENTER_ID, "eng"); center.setLatitude("12.9716"); center.setLongitude("77.5946"); List centers = new ArrayList<>(); @@ -530,7 +524,7 @@ public void testValidateCenterToMachineDistance_ExactDistanceLimit_Passes() thro // Setup: Distance exactly at limit (500 meters) when(mockLocationValidationService.getDistance(78.5946, 13.9716, 77.5946, 12.9716)) - .thenReturn(0.5); // 0.5 km = 500 meters + .thenReturn(0.5); // 0.5 km = 500 meters // Setup: Max allowed distance (500 meters) when(mockGlobalParamRepository.getCachedStringMachineToCenterDistance()).thenReturn("500"); @@ -546,20 +540,17 @@ public void testValidateCenterToMachineDistance_ExactDistanceLimit_Passes() thro private List createActiveJobs() { List jobs = new ArrayList<>(); - - SyncJobDef job1 = new SyncJobDef(); - job1.setId(JOB_ID_1); + + SyncJobDef job1 = new SyncJobDef(JOB_ID_1); job1.setApiName(API_NAME_1); job1.setIsActive(true); jobs.add(job1); - - SyncJobDef job2 = new SyncJobDef(); - job2.setId(JOB_ID_2); + + SyncJobDef job2 = new SyncJobDef(JOB_ID_2); job2.setApiName(API_NAME_2); job2.setIsActive(true); jobs.add(job2); - + return jobs; } } - diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PreRegZipHandlingServiceImplTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PreRegZipHandlingServiceImplTest.java index 2138623ff..5138cb84d 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PreRegZipHandlingServiceImplTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/PreRegZipHandlingServiceImplTest.java @@ -50,20 +50,34 @@ public class PreRegZipHandlingServiceImplTest { - @Mock private Context mockContext; - @Mock private ApplicantValidDocumentDao mockApplicantValidDocumentDao; - @Mock private IdentitySchemaRepository mockIdentitySchemaRepository; - @Mock private ClientCryptoManagerService mockClientCryptoManagerService; - @Mock private RegistrationService mockRegistrationService; - @Mock private CryptoManagerService mockCryptoManagerService; - @Mock private PacketKeeper mockPacketKeeper; - @Mock private IPacketCryptoService mockIPacketCryptoService; - @Mock private MasterDataService mockMasterDataService; - @Mock private GlobalParamRepository mockGlobalParamRepository; - @Mock private RegistrationService regService; - @Mock private MasterDataService masterDataService; - @Mock private RegistrationDto regDto; - @Mock private Context ctx; + @Mock + private Context mockContext; + @Mock + private ApplicantValidDocumentDao mockApplicantValidDocumentDao; + @Mock + private IdentitySchemaRepository mockIdentitySchemaRepository; + @Mock + private ClientCryptoManagerService mockClientCryptoManagerService; + @Mock + private RegistrationService mockRegistrationService; + @Mock + private CryptoManagerService mockCryptoManagerService; + @Mock + private PacketKeeper mockPacketKeeper; + @Mock + private IPacketCryptoService mockIPacketCryptoService; + @Mock + private MasterDataService mockMasterDataService; + @Mock + private GlobalParamRepository mockGlobalParamRepository; + @Mock + private RegistrationService regService; + @Mock + private MasterDataService masterDataService; + @Mock + private RegistrationDto regDto; + @Mock + private Context ctx; private PreRegZipHandlingServiceImpl service; @@ -80,15 +94,14 @@ public void setUp() { mockPacketKeeper, mockIPacketCryptoService, mockMasterDataService, - mockGlobalParamRepository - ); + mockGlobalParamRepository); } @Test public void test_decryptPreRegPacket_callsCryptoManager() throws Exception { - byte[] encrypted = new byte[]{1,2,3}; + byte[] encrypted = new byte[] { 1, 2, 3 }; String key = Base64.getEncoder().encodeToString("1234567890123456".getBytes()); - byte[] expected = new byte[]{4,5,6}; + byte[] expected = new byte[] { 4, 5, 6 }; when(mockCryptoManagerService.symmetricDecrypt(any(), eq(encrypted), isNull())).thenReturn(expected); byte[] result = service.decryptPreRegPacket(key, encrypted); @@ -104,7 +117,7 @@ public void test_validateFilename_invalidPath_throws() throws Exception { .invoke(service, file, dir); } - @Test (expected = RegBaseUncheckedException.class) + @Test(expected = RegBaseUncheckedException.class) public void test_extractPreRegZipFile_returnsRegistrationDto() throws Exception { RegistrationDto dto = new RegistrationDto(); when(mockRegistrationService.getRegistrationDto()).thenReturn(dto); @@ -120,7 +133,7 @@ public void test_encryptAndSavePreRegPacket_handlesException() { @Test public void test_storePreRegPacketToDisk_handleIOException() throws RegBaseUncheckedException { - String path = service.storePreRegPacketToDisk("id", new byte[]{1,2,3}, new CenterMachineDto()); + String path = service.storePreRegPacketToDisk("id", new byte[] { 1, 2, 3 }, new CenterMachineDto()); assertNotNull(path); } @@ -136,7 +149,8 @@ public void test_extractPreRegZipFile_handlesOtherException() throws Exception { @Test public void test_parseDemographicJson_handlesEmptyString() throws Exception { - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("parseDemographicJson", String.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("parseDemographicJson", + String.class); m.setAccessible(true); m.invoke(service, ""); } @@ -148,7 +162,8 @@ public void test_parseDemographicJson_handlesException() throws Exception { f.setAccessible(true); f.set(service, regService); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("parseDemographicJson", String.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("parseDemographicJson", + String.class); m.setAccessible(true); try { m.invoke(service, "{\"identity\":{}}"); @@ -159,7 +174,8 @@ public void test_parseDemographicJson_handlesException() throws Exception { @Test public void test_getValueFromJson_allTypes() throws Exception { - when(masterDataService.getFieldValues(anyString(), anyString())).thenReturn(Collections.singletonList(new GenericValueDto("code", "name", "en"))); + when(masterDataService.getFieldValues(anyString(), anyString())) + .thenReturn(Collections.singletonList(new GenericValueDto("code", "name", "en"))); when(masterDataService.findAllLocationsByLangCode(anyString())).thenReturn(Collections.emptyList()); java.lang.reflect.Field f = PreRegZipHandlingServiceImpl.class.getDeclaredField("masterDataService"); f.setAccessible(true); @@ -169,9 +185,11 @@ public void test_getValueFromJson_allTypes() throws Exception { obj.put("string", "abc"); obj.put("integer", 1); obj.put("number", 2L); - obj.put("simpleType", new org.json.JSONArray().put(new JSONObject().put("language", "en").put("value", "code"))); + obj.put("simpleType", + new org.json.JSONArray().put(new JSONObject().put("language", "en").put("value", "code"))); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", String.class, String.class, JSONObject.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", + String.class, String.class, JSONObject.class); m.setAccessible(true); assertEquals("abc", m.invoke(service, "string", "string", obj)); @@ -184,7 +202,8 @@ public void test_getValueFromJson_allTypes() throws Exception { public void test_getValueFromJson_handlesThrowable() throws Exception { JSONObject obj = new JSONObject(); obj.put("bad", new Object()); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", String.class, String.class, JSONObject.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", + String.class, String.class, JSONObject.class); m.setAccessible(true); assertNull(m.invoke(service, "bad", "string", obj)); } @@ -195,7 +214,8 @@ public void test_validateDemographicInfoObject_nullService() throws Exception { f.setAccessible(true); f.set(service, null); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("validateDemographicInfoObject"); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class + .getDeclaredMethod("validateDemographicInfoObject"); m.setAccessible(true); assertFalse((Boolean) m.invoke(service)); } @@ -208,7 +228,8 @@ public void test_validateDemographicInfoObject_nullDemographics() throws Excepti f.setAccessible(true); f.set(service, regService); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("validateDemographicInfoObject"); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class + .getDeclaredMethod("validateDemographicInfoObject"); m.setAccessible(true); assertFalse((Boolean) m.invoke(service)); } @@ -221,7 +242,8 @@ public void test_validateDemographicInfoObject_true() throws Exception { f.setAccessible(true); f.set(service, regService); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("validateDemographicInfoObject"); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class + .getDeclaredMethod("validateDemographicInfoObject"); m.setAccessible(true); assertTrue((Boolean) m.invoke(service)); } @@ -241,7 +263,7 @@ public void test_storePreRegPacketToDisk_handlesIOException() { f2.set(service, repo); try { - service.storePreRegPacketToDisk("id", new byte[]{1,2,3}, new CenterMachineDto()); + service.storePreRegPacketToDisk("id", new byte[] { 1, 2, 3 }, new CenterMachineDto()); } catch (RuntimeException e) { assertTrue(e.getCause() instanceof RegBaseUncheckedException); } @@ -257,7 +279,8 @@ public void test_valid_file_within_intended_directory() throws IOException { testFile.createNewFile(); testFile.deleteOnExit(); - String result = ReflectionTestUtils.invokeMethod(service, "validateFilename", testFile.getAbsolutePath(), intendedDir); + String result = ReflectionTestUtils.invokeMethod(service, "validateFilename", testFile.getAbsolutePath(), + intendedDir); assertEquals(testFile.getCanonicalPath(), result); } @@ -281,24 +304,16 @@ public void test_file_outside_intended_directory_throws_exception() throws IOExc assertEquals("File is outside extraction target directory.", exception.getMessage()); } - @Test public void test_init_prereg_adapter_when_external_storage_not_mounted() { MockedStatic mockedEnvironment = Mockito.mockStatic(Environment.class); mockedEnvironment.when(Environment::getExternalStorageState).thenReturn("unmounted"); - MockedStatic mockedLog = Mockito.mockStatic(Log.class); - ReflectionTestUtils.invokeMethod(service, "initPreRegAdapter", mockContext); assertEquals(mockContext, ReflectionTestUtils.getField(service, "appContext")); - assertNull(ReflectionTestUtils.getField(service, "BASE_LOCATION")); - - mockedLog.verify(() -> Log.e(anyString(), eq("External Storage not mounted"))); - mockedLog.verify(() -> Log.i(anyString(), eq("initLocalClientCryptoService: Initialization call successful"))); mockedEnvironment.close(); - mockedLog.close(); } @Test @@ -325,13 +340,18 @@ public void test_parse_demographic_json_with_valid_data() throws Exception { fieldList.add(fieldSpec2); when(mockIdentitySchemaRepository.getAllFieldSpec(any(Context.class), anyDouble())).thenReturn(fieldList); + when(mockGlobalParamRepository.getCachedStringFieldsToRetainOnPridFetch()).thenReturn(""); + doNothing().when(mockRegistrationDto).retainConfiguredFields(anyString()); + ReflectionTestUtils.setField(service, "globalParamRepository", mockGlobalParamRepository); String validJson = "{ \"identity\": { \"fullName\": \"John Doe\", \"proofOfIdentity\": { \"type\": \"passport\", \"format\": \"pdf\", \"value\": \"doc1\", \"refNumber\": \"ABC123\" } } }"; ReflectionTestUtils.invokeMethod(service, "parseDemographicJson", validJson); - verify(mockRegistrationDto).getDocuments(); - verify(mockRegistrationDto).addWithoutDocument(eq("proofOfIdentity"), eq("passport"), eq("pdf"), eq("doc1"), eq("ABC123")); + verify(mockRegistrationDto, atLeastOnce()).addWithoutDocument(anyString(), anyString(), anyString(), + anyString(), anyString()); + verify(mockRegistrationDto).addWithoutDocument(eq("proofOfIdentity"), eq("passport"), eq("pdf"), eq("doc1"), + eq("ABC123")); verify(mockIdentitySchemaRepository).getAllFieldSpec(any(Context.class), eq(1.0)); } @@ -344,10 +364,12 @@ public void test_parse_demographic_json_with_empty_input() throws Exception { ReflectionTestUtils.invokeMethod(spyService, "parseDemographicJson", ""); - verify(mockRegistrationDto, never()).addWithoutDocument(anyString(), anyString(), anyString(), anyString(), anyString()); + verify(mockRegistrationDto, never()).addWithoutDocument(anyString(), anyString(), anyString(), anyString(), + anyString()); verify(mockRegistrationDto, never()).getDemographics(); verify(mockIdentitySchemaRepository, never()).getAllFieldSpec(any(Context.class), anyDouble()); - verify(mockRegistrationDto, never()).addWithoutDocument(anyString(), anyString(), anyString(), anyString(), anyString()); + verify(mockRegistrationDto, never()).addWithoutDocument(anyString(), anyString(), anyString(), anyString(), + anyString()); verify(mockRegistrationDto, never()).getDemographics(); verify(mockIdentitySchemaRepository, never()).getAllFieldSpec(any(Context.class), anyDouble()); } @@ -412,8 +434,10 @@ public void test_process_document_files_matching_entries() throws Exception { documentDto.setFormat("pdf"); regDto.getDocuments().put("doc1", documentDto); - when(mockApplicantValidDocumentDao.findAllDocTypesByDocCategory("document")).thenReturn(Collections.singletonList("docType1")); - when(mockApplicantValidDocumentDao.findAllDocTypesByCode("docType1")).thenReturn(Collections.singletonList("document")); + when(mockApplicantValidDocumentDao.findAllDocTypesByDocCategory("document")) + .thenReturn(Collections.singletonList("docType1")); + when(mockApplicantValidDocumentDao.findAllDocTypesByCode("docType1")) + .thenReturn(Collections.singletonList("document")); assertThrows(RegBaseUncheckedException.class, () -> { service.extractPreRegZipFile(zipFile); @@ -443,7 +467,8 @@ public void test_returns_populated_registration_dto() throws Exception { @Test public void test_handles_zip_within_threshold() throws Exception { - byte[] preRegZipFile = createZipFileWithEntries(10, 10000); // Mock method to create a zip file with 10 entries, each 10KB + byte[] preRegZipFile = createZipFileWithEntries(10, 10000); // Mock method to create a zip file with 10 entries, + // each 10KB Mockito.when(regService.getRegistrationDto()).thenReturn(regDto); assertThrows(RegBaseUncheckedException.class, () -> { @@ -453,7 +478,8 @@ public void test_handles_zip_within_threshold() throws Exception { @Test public void test_validates_filenames_and_processes_documents() throws Exception { - byte[] preRegZipFile = createZipFileWithValidDocuments(); // Mock method to create a zip file with valid document entries + byte[] preRegZipFile = createZipFileWithValidDocuments(); // Mock method to create a zip file with valid + // document entries RegistrationDto registrationDtoMock = new RegistrationDto(); Mockito.when(regService.getRegistrationDto()).thenReturn(registrationDtoMock); @@ -525,7 +551,7 @@ public void test_readZipInputStreamToByteArray() throws Exception { assertArrayEquals(data, result); } - @Test (expected = RegBaseUncheckedException.class) + @Test(expected = RegBaseUncheckedException.class) public void test_extractPreRegZipFile_handlesIOException() throws Exception { when(regService.getRegistrationDto()).thenReturn(regDto); RegistrationDto result = service.extractPreRegZipFile("notazip".getBytes()); @@ -552,7 +578,8 @@ public void test_encryptAndSavePreRegPacket_success() throws Exception { when(mockCryptoManagerService.symmetricEncryptWithRandomIV(any(), any(), any())).thenReturn("enc".getBytes()); when(mockGlobalParamRepository.getCachedStringPreRegPacketLocation()).thenReturn("prereg"); when(mockContext.getFilesDir()).thenReturn(new File(System.getProperty("java.io.tmpdir"))); - PreRegistrationDto dto = service.encryptAndSavePreRegPacket("id", Base64.getEncoder().encodeToString("abc".getBytes()), new CenterMachineDto()); + PreRegistrationDto dto = service.encryptAndSavePreRegPacket("id", + Base64.getEncoder().encodeToString("abc".getBytes()), new CenterMachineDto()); assertNotNull(dto); assertEquals("id", dto.getPreRegId()); } @@ -570,7 +597,7 @@ public void test_encryptAndSavePreRegPacket_populatesSymmetricKeyAndEncryptedPac when(mockCryptoManagerService.generateAESKey(anyInt())).thenReturn(keyGeneratorMock); when(keyGeneratorMock.generateKey()).thenReturn(secretKey); - byte[] encryptedBytes = new byte[]{9, 8, 7}; + byte[] encryptedBytes = new byte[] { 9, 8, 7 }; when(mockCryptoManagerService.symmetricEncryptWithRandomIV(eq(secretKey), any(byte[].class), isNull())) .thenReturn(encryptedBytes); @@ -597,8 +624,8 @@ public void test_storePreRegPacketToDisk_success() throws Exception { @Test public void test_decryptPreRegPacket_success() throws Exception { String key = Base64.getEncoder().encodeToString("1234567890123456".getBytes()); - byte[] encrypted = new byte[]{1,2,3}; - byte[] expected = new byte[]{4,5,6}; + byte[] encrypted = new byte[] { 1, 2, 3 }; + byte[] expected = new byte[] { 4, 5, 6 }; when(mockCryptoManagerService.symmetricDecrypt(any(), eq(encrypted), isNull())).thenReturn(expected); byte[] result = service.decryptPreRegPacket(key, encrypted); assertArrayEquals(expected, result); @@ -650,26 +677,38 @@ public void test_parseDemographicJson_valid() throws Exception { when(dto.getDocuments()).thenReturn(new HashMap<>()); when(dto.getDemographics()).thenReturn(new HashMap<>()); List fields = new ArrayList<>(); - FieldSpecDto f1 = new FieldSpecDto(); f1.setId("fullName"); f1.setType("string"); f1.setControlType("textbox"); fields.add(f1); - FieldSpecDto f2 = new FieldSpecDto(); f2.setId("proofOfIdentity"); f2.setType("documentType"); fields.add(f2); + FieldSpecDto f1 = new FieldSpecDto(); + f1.setId("fullName"); + f1.setType("string"); + f1.setControlType("textbox"); + fields.add(f1); + FieldSpecDto f2 = new FieldSpecDto(); + f2.setId("proofOfIdentity"); + f2.setType("documentType"); + fields.add(f2); when(mockIdentitySchemaRepository.getAllFieldSpec(any(), anyDouble())).thenReturn(fields); + when(mockGlobalParamRepository.getCachedStringFieldsToRetainOnPridFetch()).thenReturn(""); + doNothing().when(dto).retainConfiguredFields(anyString()); ReflectionTestUtils.setField(service, "registrationService", regService); ReflectionTestUtils.setField(service, "identitySchemaService", mockIdentitySchemaRepository); + ReflectionTestUtils.setField(service, "globalParamRepository", mockGlobalParamRepository); String json = "{ \"identity\": { \"fullName\": \"John Doe\", \"proofOfIdentity\": { \"type\": \"passport\", \"format\": \"pdf\", \"value\": \"doc1\", \"refNumber\": \"ABC123\" } } }"; ReflectionTestUtils.invokeMethod(service, "parseDemographicJson", json); - verify(dto).getDocuments(); + verify(dto, atLeastOnce()).addWithoutDocument(anyString(), anyString(), anyString(), anyString(), anyString()); } @Test public void test_getValueFromJson_allTypes_Success() throws Exception { - when(masterDataService.getFieldValues(anyString(), anyString())).thenReturn(Collections.singletonList(new GenericValueDto("code", "name", "en"))); + when(masterDataService.getFieldValues(anyString(), anyString())) + .thenReturn(Collections.singletonList(new GenericValueDto("code", "name", "en"))); when(masterDataService.findAllLocationsByLangCode(anyString())).thenReturn(Collections.emptyList()); ReflectionTestUtils.setField(service, "masterDataService", masterDataService); JSONObject obj = new JSONObject(); obj.put("string", "abc"); obj.put("integer", 1); obj.put("number", 2L); - obj.put("simpleType", new org.json.JSONArray().put(new JSONObject().put("language", "en").put("value", "code"))); + obj.put("simpleType", + new org.json.JSONArray().put(new JSONObject().put("language", "en").put("value", "code"))); assertEquals("abc", ReflectionTestUtils.invokeMethod(service, "getValueFromJson", "string", "string", obj)); assertNotNull(ReflectionTestUtils.invokeMethod(service, "getValueFromJson", "simpleType", "simpleType", obj)); } @@ -679,6 +718,7 @@ public void test_initPreRegAdapter_externalStorageNotMounted() { MockedStatic mockedEnv = Mockito.mockStatic(Environment.class); mockedEnv.when(Environment::getExternalStorageState).thenReturn("unmounted"); ReflectionTestUtils.invokeMethod(service, "initPreRegAdapter", mockContext); + assertEquals(mockContext, ReflectionTestUtils.getField(service, "appContext")); mockedEnv.close(); } @@ -699,17 +739,21 @@ public void test_parseDemographicJson_documentType_and_biometricsType() throws E bioField.setType("biometricsType"); fields.add(bioField); when(mockIdentitySchemaRepository.getAllFieldSpec(any(), anyDouble())).thenReturn(fields); + when(mockGlobalParamRepository.getCachedStringFieldsToRetainOnPridFetch()).thenReturn(""); + doNothing().when(dto).retainConfiguredFields(anyString()); ReflectionTestUtils.setField(service, "registrationService", regService); ReflectionTestUtils.setField(service, "identitySchemaService", mockIdentitySchemaRepository); + ReflectionTestUtils.setField(service, "globalParamRepository", mockGlobalParamRepository); String json = "{ \"identity\": { \"proofOfIdentity\": { \"type\": \"passport\", \"format\": \"pdf\", \"value\": \"doc1\", \"refNumber\": \"ABC123\" }, \"face\": \"faceData\" } }"; ReflectionTestUtils.invokeMethod(service, "parseDemographicJson", json); - verify(dto).getDocuments(); + verify(dto, atLeastOnce()).addWithoutDocument(anyString(), anyString(), anyString(), anyString(), anyString()); } @Test public void test_getValueFromJson_missingKey() throws Exception { JSONObject obj = new JSONObject(); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", String.class, String.class, JSONObject.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", + String.class, String.class, JSONObject.class); m.setAccessible(true); assertNull(m.invoke(service, "notfound", "string", obj)); } @@ -718,7 +762,8 @@ public void test_getValueFromJson_missingKey() throws Exception { public void test_getValueFromJson_unexpectedType() throws Exception { JSONObject obj = new JSONObject(); obj.put("weird", new Object()); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", String.class, String.class, JSONObject.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", + String.class, String.class, JSONObject.class); m.setAccessible(true); assertNull(m.invoke(service, "weird", "unknownType", obj)); } @@ -733,7 +778,7 @@ public void test_storePreRegPacketToDisk_directoryCreationFails() { ReflectionTestUtils.setField(service, "appContext", mockContext); ReflectionTestUtils.setField(service, "globalParamRepository", mockGlobalParamRepository); try { - service.storePreRegPacketToDisk("id", new byte[]{1,2,3}, new CenterMachineDto()); + service.storePreRegPacketToDisk("id", new byte[] { 1, 2, 3 }, new CenterMachineDto()); } catch (Exception e) { // Should not throw, just print error } @@ -757,7 +802,7 @@ public void test_extractPreRegZipFile_withNonMatchingEntries() throws Exception assertEquals(dto, result); } - @Test (expected = RegBaseUncheckedException.class) + @Test(expected = RegBaseUncheckedException.class) public void test_extractPreRegZipFile_removesEmptyDocumentEntries() throws Exception { RegistrationDto dto = new RegistrationDto(); Map docs = new HashMap<>(); @@ -791,9 +836,11 @@ public void test_getValueFromJson_simpleType_index1_branch() throws Exception { Location loc = new Location("123", "eng"); loc.setHierarchyName("district"); loc.setHierarchyLevel(1); - when(masterDataService.getFieldValues(eq("district"), eq("en"))).thenReturn(Collections.singletonList(new GenericValueDto("code", "DistrictName", "en"))); + when(masterDataService.getFieldValues(eq("district"), eq("en"))) + .thenReturn(Collections.singletonList(new GenericValueDto("code", "DistrictName", "en"))); when(masterDataService.findAllLocationsByLangCode(anyString())).thenReturn(Collections.singletonList(loc)); - when(masterDataService.findLocationByHierarchyLevel(eq(1), eq("en"))).thenReturn(Collections.singletonList(new GenericValueDto("code", "DistrictName", "en"))); + when(masterDataService.findLocationByHierarchyLevel(eq(1), eq("en"))) + .thenReturn(Collections.singletonList(new GenericValueDto("code", "DistrictName", "en"))); ReflectionTestUtils.setField(service, "masterDataService", masterDataService); List result = ReflectionTestUtils.invokeMethod(service, "getValueFromJson", "district", "simpleType", obj); @@ -818,13 +865,14 @@ public void test_getValueFromJson_simpleType_fallback_to_value() throws Exceptio List result = ReflectionTestUtils.invokeMethod(service, "getValueFromJson", "district", "simpleType", obj); assertNotNull(result); assertFalse(result.isEmpty()); - assertEquals("unknown", ((io.mosip.registration.packetmanager.dto.SimpleType)result.get(0)).getValue()); + assertEquals("unknown", ((io.mosip.registration.packetmanager.dto.SimpleType) result.get(0)).getValue()); } @Test public void test_getValueFromJson_catchThrowable() throws Exception { JSONObject obj = new JSONObject(); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", String.class, String.class, JSONObject.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", + String.class, String.class, JSONObject.class); m.setAccessible(true); assertNull(m.invoke(service, "nonexistent", "string", obj)); } @@ -833,7 +881,8 @@ public void test_getValueFromJson_catchThrowable() throws Exception { public void test_getValueFromJson_nullJSONArray() throws Exception { JSONObject obj = new JSONObject(); obj.put("simpleType", JSONObject.NULL); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", String.class, String.class, JSONObject.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", + String.class, String.class, JSONObject.class); m.setAccessible(true); assertNull(m.invoke(service, "simpleType", "simpleType", obj)); } @@ -842,11 +891,12 @@ public void test_getValueFromJson_nullJSONArray() throws Exception { public void test_getValueFromJson_emptyJSONArray() throws Exception { JSONObject obj = new JSONObject(); obj.put("simpleType", new org.json.JSONArray()); - java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", String.class, String.class, JSONObject.class); + java.lang.reflect.Method m = PreRegZipHandlingServiceImpl.class.getDeclaredMethod("getValueFromJson", + String.class, String.class, JSONObject.class); m.setAccessible(true); Object result = m.invoke(service, "simpleType", "simpleType", obj); assertNotNull(result); - assertTrue(((List)result).isEmpty()); + assertTrue(((List) result).isEmpty()); } @Test @@ -911,21 +961,10 @@ public void test_validateDemographicInfoObject_getRegistrationDtoThrows() throws @Test public void test_initPreRegAdapter_externalStorageMounted() { MockedStatic mockedEnv = Mockito.mockStatic(Environment.class); - MockedStatic mockedConfig = Mockito.mockStatic(ConfigService.class); - MockedStatic mockedLog = Mockito.mockStatic(Log.class); - mockedEnv.when(Environment::getExternalStorageState).thenReturn(Environment.MEDIA_MOUNTED); - mockedConfig.when(() -> ConfigService.getProperty(anyString(), any())).thenReturn("testLocation"); - File mockFile = mock(File.class); - when(mockFile.exists()).thenReturn(false); - when(mockFile.mkdirs()).thenReturn(true); - ReflectionTestUtils.invokeMethod(service, "initPreRegAdapter", mockContext); - - mockedLog.verify(() -> Log.i(anyString(), eq("initLocalClientCryptoService: Initialization call successful"))); + assertEquals(mockContext, ReflectionTestUtils.getField(service, "appContext")); mockedEnv.close(); - mockedConfig.close(); - mockedLog.close(); } @Test @@ -939,38 +978,43 @@ public void test_GetValueFromJson_usesMasterDataServiceAndLocationHierarchy() th when(masterDataService.getFieldValues("region", "eng")).thenReturn(Collections.singletonList(valueDto)); // Setup location hierarchy: level 0 = "Country", level 1 = "Region" - // Note: HashMap iteration order is not guaranteed, so we can't rely on index being exactly 1 + // Note: HashMap iteration order is not guaranteed, so we can't rely on index + // being exactly 1 Location countryLocation = new Location("COUNTRY", "eng"); countryLocation.setHierarchyName("Country"); countryLocation.setHierarchyLevel(0); - + Location regionLocation = new Location("REGION", "eng"); regionLocation.setHierarchyName("Region"); regionLocation.setHierarchyLevel(1); - + when(masterDataService.findAllLocationsByLangCode("eng")) .thenReturn(Arrays.asList(countryLocation, regionLocation)); - // Note: findLocationByHierarchyLevel may or may not be called depending on HashMap iteration order + // Note: findLocationByHierarchyLevel may or may not be called depending on + // HashMap iteration order when(masterDataService.findLocationByHierarchyLevel(anyInt(), eq("eng"))) .thenReturn(Collections.singletonList(new GenericValueDto("LOC_CODE", "LocationName", "eng"))); ReflectionTestUtils.setField(service, "masterDataService", masterDataService); - Object result = ReflectionTestUtils.invokeMethod(service, "getValueFromJson", "region", "simpleType", jsonObject); - + Object result = ReflectionTestUtils.invokeMethod(service, "getValueFromJson", "region", "simpleType", + jsonObject); + assertNotNull(result); assertTrue("Result should be a List", result instanceof List); @SuppressWarnings("unchecked") List simpleTypes = (List) result; assertEquals("Should have one SimpleType entry", 1, simpleTypes.size()); - // The value should be "RegionName" from getFieldValues match, or "LOC_CODE" as fallback + // The value should be "RegionName" from getFieldValues match, or "LOC_CODE" as + // fallback String actualValue = simpleTypes.get(0).getValue(); assertTrue("Value should be RegionName (from getFieldValues) or LOC_CODE (fallback)", "RegionName".equals(actualValue) || "LOC_CODE".equals(actualValue)); assertEquals("eng", simpleTypes.get(0).getLanguage()); - + verify(masterDataService).getFieldValues("region", "eng"); verify(masterDataService).findAllLocationsByLangCode("eng"); - // findLocationByHierarchyLevel may or may not be called depending on HashMap iteration order + // findLocationByHierarchyLevel may or may not be called depending on HashMap + // iteration order verify(masterDataService, atMost(1)).findLocationByHierarchyLevel(anyInt(), eq("eng")); } @@ -1065,11 +1109,11 @@ public void test_storePreRegPacketToDisk_createsDirectories() throws Exception { String path = service.storePreRegPacketToDisk("RID123", "payload".getBytes(), new CenterMachineDto()); assertTrue("Path should contain RID123.zip", path.contains("RID123.zip")); - + // Verify directory was created File targetDir = new File(tempDir, "preRegPackets"); assertTrue("Expected preRegPackets directory to be created", targetDir.exists() && targetDir.isDirectory()); - + // Verify zip file was created File zipFile = new File(targetDir, "RID123.zip"); assertTrue("Expected stored packet file to exist", zipFile.exists()); diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/RegistrationServiceImplTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/RegistrationServiceImplTest.java index 6d07b46b1..c5f9ef6b4 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/RegistrationServiceImplTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/service/RegistrationServiceImplTest.java @@ -25,6 +25,7 @@ import io.mosip.registration.keymanager.spi.ClientCryptoManagerService; import io.mosip.registration.packetmanager.spi.PacketWriterService; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -41,6 +42,7 @@ import io.mosip.registration.clientmanager.entity.RegistrationCenter; import io.mosip.registration.packetmanager.cbeffutil.jaxbclasses.BIR; import io.mosip.registration.packetmanager.dto.PacketWriter.BiometricRecord; +import io.mosip.registration.packetmanager.util.StorageUtils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -55,8 +57,10 @@ import java.util.List; import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyDouble; @@ -68,7 +72,7 @@ import javax.inject.Provider; -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) public class RegistrationServiceImplTest { @Mock @@ -107,17 +111,48 @@ public class RegistrationServiceImplTest { @Mock private PreCheckValidatorService preCheckValidatorService; + private MockedStatic storageUtilsMock; + @Before - public void setUp() { + public void setUp() throws Exception { MockitoAnnotations.openMocks(this); SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class); + when(editor.putString(anyString(), anyString())).thenReturn(editor); + when(editor.commit()).thenReturn(true); when(mockSharedPreferences.edit()).thenReturn(editor); when(mockApplicationContext.getString(anyInt())).thenReturn("Registration Client"); when(mockApplicationContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mockSharedPreferences); + // Mock StorageUtils.getPacketStorageDir so doPreChecksBeforeRegistration/validatingDiskSpace don't NPE + storageUtilsMock = Mockito.mockStatic(StorageUtils.class); + File packetDir = new File(System.getProperty("java.io.tmpdir"), "packets"); + packetDir.mkdirs(); + storageUtilsMock.when(() -> StorageUtils.getPacketStorageDir(any(Context.class))).thenReturn(packetDir); when(preRegistrationDataSyncServiceProvider.get()).thenReturn(preRegistrationDataSyncService); registrationService = new RegistrationServiceImpl(mockApplicationContext, packetWriterService, registrationRepository, masterDataService, identitySchemaRepository, clientCryptoManagerService, - keyStoreRepository, globalParamRepository, auditManagerService,registrationCenterRepository,locationValidationService, preRegistrationDataSyncServiceProvider, biometricService, packetService, preCheckValidatorService); + keyStoreRepository, globalParamRepository, auditManagerService, registrationCenterRepository, + locationValidationService, preRegistrationDataSyncServiceProvider, biometricService, packetService, + preCheckValidatorService); + + // Common mocks to prevent NPEs in pre-checks + Mockito.lenient().when(globalParamRepository.getCachedIntegerDiskSpaceSize()).thenReturn(50); + Mockito.lenient().when(packetService.isRegisteredPacketApprovalTimeBreached()).thenReturn(false); + Mockito.lenient().when(packetService.validatingLastExportDuration()).thenReturn(false); + Mockito.lenient().when(packetService.isMaxPacketCountLimitReached()).thenReturn(false); + Mockito.lenient().when(packetService.isMaxNotApprovedPacketCountLimitReached()).thenReturn(false); + + // Mock for getAttemptsCount which is called during startRegistration + Mockito.lenient().when(globalParamRepository.getCachedIntegerGlobalParam(anyString())).thenReturn(3); + + // Mock for GPS validation which is called during startRegistration + Mockito.lenient().doNothing().when(preCheckValidatorService).validateCenterToMachineDistance(any(), any()); + } + + @After + public void tearDown() { + if (storageUtilsMock != null) { + storageUtilsMock.close(); + } } @Test(expected = ClientCheckedException.class) @@ -140,9 +175,10 @@ public void getRegistrationDtoAfterStartingRegistration() throws Exception { when(keyStoreRepository.getCertificateData("10001_110001")).thenReturn("dummy_cert"); when(globalParamRepository.getCachedIntegerGlobalParam(Mockito.anyString())).thenReturn(3); File mockFile = mock(File.class); - when(mockFile.getUsableSpace()).thenReturn(100l*(1024 * 1024)); + when(mockFile.getUsableSpace()).thenReturn(100l * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); - RegistrationDto registrationDto = registrationService.startRegistration(Arrays.asList("eng"), "NEW", "NEW", null, null); + RegistrationDto registrationDto = registrationService.startRegistration(Arrays.asList("eng"), "NEW", "NEW", + null, null); RegistrationDto result = registrationService.getRegistrationDto(); Assert.assertNotNull(registrationDto); @@ -157,7 +193,8 @@ public void submitRegistrationDtoWithoutStartingRegistration() throws Exception } @Test - // Test for startAndSubmitRegistration - should succeed when all dependencies are mocked + // Test for startAndSubmitRegistration - should succeed when all dependencies + // are mocked public void startAndSubmitRegistration() throws Exception { SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class); when(mockSharedPreferences.edit()).thenReturn(editor); @@ -172,11 +209,12 @@ public void startAndSubmitRegistration() throws Exception { when(keyStoreRepository.getCertificateData("10001_110001")).thenReturn("dummy_cert"); when(globalParamRepository.getCachedIntegerGlobalParam(Mockito.anyString())).thenReturn(3); File mockFile = mock(File.class); - when(mockFile.getUsableSpace()).thenReturn(100l*(1024 * 1024)); + when(mockFile.getUsableSpace()).thenReturn(100l * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); List selectedLanguages = new ArrayList<>(); selectedLanguages.add("eng"); - RegistrationDto registrationDto = registrationService.startRegistration(selectedLanguages, "NEW", "NEW", null, null); + RegistrationDto registrationDto = registrationService.startRegistration(selectedLanguages, "NEW", "NEW", null, + null); RegistrationDto result = registrationService.getRegistrationDto(); Assert.assertNotNull(registrationDto); @@ -195,7 +233,9 @@ public void startAndSubmitRegistration() throws Exception { when(auditManagerService.getAuditLogs(Mockito.anyLong())).thenReturn(Collections.emptyList()); when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); when(identitySchemaRepository.getSchemaJson(Mockito.any(), Mockito.anyDouble())).thenReturn("{}"); - when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn("containerPath123"); + when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())) + .thenReturn("containerPath123"); registrationService.submitRegistrationDto("100006"); } @@ -287,7 +327,7 @@ public void clearRegistration() throws Exception { when(keyStoreRepository.getCertificateData("10001_110001")).thenReturn("dummy_cert"); when(globalParamRepository.getCachedIntegerGlobalParam(Mockito.anyString())).thenReturn(3); File mockFile = mock(File.class); - when(mockFile.getUsableSpace()).thenReturn(100l*(1024 * 1024)); + when(mockFile.getUsableSpace()).thenReturn(100l * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); List languages = new ArrayList<>(); languages.add("eng"); @@ -350,7 +390,8 @@ public void testGetAdditionalInfo_StringAndList() throws Exception { when(mockFile.getUsableSpace()).thenReturn(100L * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); - registrationService.startRegistration(new ArrayList<>(Collections.singletonList("eng")), "NEW", "NEW", null, null); + registrationService.startRegistration(new ArrayList<>(Collections.singletonList("eng")), "NEW", "NEW", null, + null); Method setRegistrationDto = registrationService.getClass().getDeclaredMethod("getRegistrationDto"); setRegistrationDto.setAccessible(true); @@ -365,7 +406,8 @@ public void testGetAdditionalInfo_StringAndList() throws Exception { @Test // Test for convertImageToBytes with valid base64 string public void testConvertImageToBytes_NullAndIOException() throws Exception { - Method convertImageToBytes = registrationService.getClass().getDeclaredMethod("convertImageToBytes", String.class); + Method convertImageToBytes = registrationService.getClass().getDeclaredMethod("convertImageToBytes", + String.class); convertImageToBytes.setAccessible(true); // Should return null for invalid base64 assertNull(convertImageToBytes.invoke(registrationService, "not_base64")); @@ -399,7 +441,8 @@ public void testAddMetaInfoMap() throws Exception { bioDevicesServiceField.setAccessible(true); bioDevicesServiceField.set(biometricService, new HashMap<>()); // Should not throw - Method addMetaInfoMap = registrationService.getClass().getDeclaredMethod("addMetaInfoMap", String.class, String.class, String.class); + Method addMetaInfoMap = registrationService.getClass().getDeclaredMethod("addMetaInfoMap", String.class, + String.class, String.class); addMetaInfoMap.setAccessible(true); addMetaInfoMap.invoke(registrationService, "center", "machine", "maker"); } @@ -407,11 +450,13 @@ public void testAddMetaInfoMap() throws Exception { @Test // Test for getLabelValueDTOListString with valid map public void testGetLabelValueDTOListString() throws Exception { - Method getLabelValueDTOListString = registrationService.getClass().getDeclaredMethod("getLabelValueDTOListString", Map.class); + Method getLabelValueDTOListString = registrationService.getClass() + .getDeclaredMethod("getLabelValueDTOListString", Map.class); getLabelValueDTOListString.setAccessible(true); Map map = new HashMap<>(); map.put("label", "value"); - List> result = (List>) getLabelValueDTOListString.invoke(registrationService, map); + List> result = (List>) getLabelValueDTOListString + .invoke(registrationService, map); assertEquals(1, result.size()); assertEquals("label", result.get(0).get("label")); assertEquals("value", result.get(0).get("value")); @@ -427,7 +472,8 @@ public void testDoPreChecksBeforeRegistration_ThrowsException() throws Exception when(mockFile.getUsableSpace()).thenReturn(10l * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); - Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", CenterMachineDto.class); + Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", + CenterMachineDto.class); doPreChecks.setAccessible(true); try { doPreChecks.invoke(registrationService, centerMachineDto); @@ -451,7 +497,8 @@ public void testConvertImageToPDF_ReturnsNullOnException() throws Exception { @Test // Test for getCompressedImage with valid input public void testGetCompressedImage() throws Exception { - Method getCompressedImage = registrationService.getClass().getDeclaredMethod("getCompressedImage", byte[].class, Float.class); + Method getCompressedImage = registrationService.getClass().getDeclaredMethod("getCompressedImage", byte[].class, + Float.class); getCompressedImage.setAccessible(true); byte[] input = "test".getBytes(); byte[] result = (byte[]) getCompressedImage.invoke(registrationService, input, 0.5f); @@ -461,7 +508,8 @@ public void testGetCompressedImage() throws Exception { @Test // Test for getScaledDimension with valid parameters public void testGetScaledDimension() throws Exception { - Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, int.class, int.class, int.class); + Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, + int.class, int.class, int.class); getScaledDimension.setAccessible(true); int[] result = (int[]) getScaledDimension.invoke(null, 200, 100, 100, 50); assertEquals(100, result[0]); @@ -492,9 +540,12 @@ public void testBuildBIR_NullAndFace() { // Test for getAttemptsCount with all modalities public void testGetAttemptsCount_AllCases() throws Exception { // Fix: Return 2 for each specific key used in getAttemptsCount - when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.LEFT_SLAP_ATTEMPTS_KEY)).thenReturn(2); - when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.RIGHT_SLAP_ATTEMPTS_KEY)).thenReturn(2); - when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.THUMBS_ATTEMPTS_KEY)).thenReturn(2); + when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.LEFT_SLAP_ATTEMPTS_KEY)) + .thenReturn(2); + when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.RIGHT_SLAP_ATTEMPTS_KEY)) + .thenReturn(2); + when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.THUMBS_ATTEMPTS_KEY)) + .thenReturn(2); when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.IRIS_ATTEMPTS_KEY)).thenReturn(2); when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.FACE_ATTEMPTS_KEY)).thenReturn(2); @@ -519,7 +570,7 @@ public void testGetAttemptsCount_AllCases() throws Exception { public void testGetAudits_EmptyList() { when(globalParamRepository.getCachedStringGlobalParam(Mockito.anyString())).thenReturn(null); when(auditManagerService.getAuditLogs(Mockito.anyLong())).thenReturn(Collections.emptyList()); - List> audits = ((RegistrationServiceImpl)registrationService).getAudits(); + List> audits = ((RegistrationServiceImpl) registrationService).getAudits(); assertTrue(audits.isEmpty()); } @@ -536,7 +587,7 @@ public void testBuildBIR_NonNull() { biometricsDto.setSdkScore(0.5); biometricsDto.setSpecVersion("1.0"); biometricsDto.setQualityScore(10); - BIR bir = ((RegistrationServiceImpl)registrationService).buildBIR(biometricsDto); + BIR bir = ((RegistrationServiceImpl) registrationService).buildBIR(biometricsDto); assertNotNull(bir); } @@ -545,7 +596,8 @@ public void testBuildBIR_NonNull() { public void testBuildBIR_ExceptionPhoto() { BiometricsDto biometricsDto = new BiometricsDto(); // Use the correct value for EXCEPTION_PHOTO that SingleType.fromValue() expects - biometricsDto.setModality(io.mosip.registration.packetmanager.cbeffutil.jaxbclasses.SingleType.EXCEPTION_PHOTO.value()); + biometricsDto.setModality( + io.mosip.registration.packetmanager.cbeffutil.jaxbclasses.SingleType.EXCEPTION_PHOTO.value()); biometricsDto.setBioValue(null); biometricsDto.setBioSubType("subtype"); biometricsDto.setDecodedBioResponse("{\"bioValue\":\"abc\"}"); @@ -554,24 +606,27 @@ public void testBuildBIR_ExceptionPhoto() { biometricsDto.setSdkScore(0.0); biometricsDto.setSpecVersion(null); biometricsDto.setQualityScore(0); - BIR bir = ((RegistrationServiceImpl)registrationService).buildBIR(biometricsDto); + BIR bir = ((RegistrationServiceImpl) registrationService).buildBIR(biometricsDto); assertNotNull(bir); } @Test // Test for getLabelValueDTOListString with empty map public void testGetLabelValueDTOListString_EmptyMap() throws Exception { - Method getLabelValueDTOListString = registrationService.getClass().getDeclaredMethod("getLabelValueDTOListString", Map.class); + Method getLabelValueDTOListString = registrationService.getClass() + .getDeclaredMethod("getLabelValueDTOListString", Map.class); getLabelValueDTOListString.setAccessible(true); Map map = new HashMap<>(); - List> result = (List>) getLabelValueDTOListString.invoke(registrationService, map); + List> result = (List>) getLabelValueDTOListString + .invoke(registrationService, map); assertTrue(result.isEmpty()); } @Test // Test for getScaledDimension with various scaling scenarios public void testGetScaledDimension_NoScalingNeeded() throws Exception { - Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, int.class, int.class, int.class); + Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, + int.class, int.class, int.class); getScaledDimension.setAccessible(true); int[] result = (int[]) getScaledDimension.invoke(null, 50, 50, 100, 100); assertEquals(50, result[0]); @@ -581,7 +636,8 @@ public void testGetScaledDimension_NoScalingNeeded() throws Exception { @Test // Test for getScaledDimension with width scaling public void testGetScaledDimension_ScaleWidth() throws Exception { - Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, int.class, int.class, int.class); + Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, + int.class, int.class, int.class); getScaledDimension.setAccessible(true); int[] result = (int[]) getScaledDimension.invoke(null, 200, 100, 100, 100); assertEquals(100, result[0]); @@ -591,7 +647,8 @@ public void testGetScaledDimension_ScaleWidth() throws Exception { @Test // Test for getScaledDimension with height scaling public void testGetScaledDimension_ScaleHeight() throws Exception { - Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, int.class, int.class, int.class); + Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, + int.class, int.class, int.class); getScaledDimension.setAccessible(true); int[] result = (int[]) getScaledDimension.invoke(null, 100, 200, 100, 100); assertEquals(50, result[0]); @@ -601,7 +658,8 @@ public void testGetScaledDimension_ScaleHeight() throws Exception { @Test // Test for getCompressedImage with null input public void testGetCompressedImage_NullInput() throws Exception { - Method getCompressedImage = registrationService.getClass().getDeclaredMethod("getCompressedImage", byte[].class, Float.class); + Method getCompressedImage = registrationService.getClass().getDeclaredMethod("getCompressedImage", byte[].class, + Float.class); getCompressedImage.setAccessible(true); byte[] result = (byte[]) getCompressedImage.invoke(registrationService, (Object) null, null); assertNull(result); @@ -650,21 +708,27 @@ public void testDoPreChecksBeforeRegistration_Success() throws Exception { File mockFile = mock(File.class); when(mockFile.getUsableSpace()).thenReturn(100L * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); - Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", CenterMachineDto.class); + Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", + CenterMachineDto.class); doPreChecks.setAccessible(true); doPreChecks.invoke(registrationService, centerMachineDto); } @Test(expected = Exception.class) - // Test for doPreChecksBeforeRegistration with low disk space + // Test for doPreChecksBeforeRegistration with low disk space (implementation uses StorageUtils.getPacketStorageDir) public void testDoPreChecksBeforeRegistration_LowSpace() throws Exception { CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterStatus(true); centerMachineDto.setMachineStatus(true); - File mockFile = mock(File.class); - when(mockFile.getUsableSpace()).thenReturn(10L * (1024 * 1024)); - when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); - Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", CenterMachineDto.class); + // Override StorageUtils mock to return a dir with low space (10MB < 50MB required) + File lowSpaceFile = mock(File.class); + when(lowSpaceFile.exists()).thenReturn(true); + when(lowSpaceFile.isDirectory()).thenReturn(true); + when(lowSpaceFile.canWrite()).thenReturn(true); + when(lowSpaceFile.getUsableSpace()).thenReturn(10L * (1024 * 1024)); + storageUtilsMock.when(() -> StorageUtils.getPacketStorageDir(any(Context.class))).thenReturn(lowSpaceFile); + Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", + CenterMachineDto.class); doPreChecks.setAccessible(true); doPreChecks.invoke(registrationService, centerMachineDto); } @@ -678,7 +742,8 @@ public void testDoPreChecksBeforeRegistration_InactiveCenter() throws Exception File mockFile = mock(File.class); when(mockFile.getUsableSpace()).thenReturn(100L * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); - Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", CenterMachineDto.class); + Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", + CenterMachineDto.class); doPreChecks.setAccessible(true); doPreChecks.invoke(registrationService, centerMachineDto); } @@ -692,7 +757,8 @@ public void testDoPreChecksBeforeRegistration_InactiveMachine() throws Exception File mockFile = mock(File.class); when(mockFile.getUsableSpace()).thenReturn(100L * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); - Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", CenterMachineDto.class); + Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", + CenterMachineDto.class); doPreChecks.setAccessible(true); doPreChecks.invoke(registrationService, centerMachineDto); } @@ -730,9 +796,11 @@ public void testSubmitRegistrationDto_UpdateFlow_UINField() throws Exception { regDtoField.set(registrationService, dto); when(globalParamRepository.getSelectedHandles()).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.argThat(arg -> - !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); + Mockito.when( + globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))) + .thenReturn(null); + Mockito.when(globalParamRepository.getCachedStringGlobalParam( + Mockito.argThat(arg -> !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); // Mock GPS validation to be disabled to skip location validation when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Mock audit service to return empty list to avoid NPE @@ -744,7 +812,9 @@ public void testSubmitRegistrationDto_UpdateFlow_UINField() throws Exception { centerMachineDto.setMachineRefId("machineRefId"); when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); when(identitySchemaRepository.getSchemaJson(Mockito.any(), Mockito.anyDouble())).thenReturn("{}"); - when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn("containerPath123"); + when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())) + .thenReturn("containerPath123"); // Fix: Set BIO_DEVICES field on biometricService mock Field bioDevicesServiceField = Biometrics095Service.class.getDeclaredField("BIO_DEVICES"); bioDevicesServiceField.setAccessible(true); @@ -786,9 +856,11 @@ public void testSubmitRegistrationDto_NewFlow_AllFields() throws Exception { regDtoField.set(registrationService, dto); when(globalParamRepository.getSelectedHandles()).thenReturn(Collections.singletonList("handle1")); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.argThat(arg -> - !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); + Mockito.when( + globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))) + .thenReturn(null); + Mockito.when(globalParamRepository.getCachedStringGlobalParam( + Mockito.argThat(arg -> !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); // Mock GPS validation to be disabled to skip location validation when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Mock audit service to return empty list to avoid NPE @@ -800,7 +872,9 @@ public void testSubmitRegistrationDto_NewFlow_AllFields() throws Exception { centerMachineDto.setMachineRefId("machineRefId"); when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); when(identitySchemaRepository.getSchemaJson(Mockito.any(), Mockito.anyDouble())).thenReturn("{}"); - when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn("containerPath123"); + when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())) + .thenReturn("containerPath123"); // Fix: Set BIO_DEVICES field on biometricService mock Field bioDevicesServiceField = Biometrics095Service.class.getDeclaredField("BIO_DEVICES"); bioDevicesServiceField.setAccessible(true); @@ -842,9 +916,11 @@ public void testSubmitRegistrationDto_CorrectionFlow() throws Exception { regDtoField.set(registrationService, dto); when(globalParamRepository.getSelectedHandles()).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.argThat(arg -> - !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); + Mockito.when( + globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))) + .thenReturn(null); + Mockito.when(globalParamRepository.getCachedStringGlobalParam( + Mockito.argThat(arg -> !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); // Mock GPS validation to be disabled to skip location validation when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Mock audit service to return empty list to avoid NPE @@ -856,7 +932,9 @@ public void testSubmitRegistrationDto_CorrectionFlow() throws Exception { centerMachineDto.setMachineRefId("machineRefId"); when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); when(identitySchemaRepository.getSchemaJson(Mockito.any(), Mockito.anyDouble())).thenReturn("{}"); - when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn("containerPath123"); + when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())) + .thenReturn("containerPath123"); // Fix: Set BIO_DEVICES field on biometricService mock Field bioDevicesServiceField = Biometrics095Service.class.getDeclaredField("BIO_DEVICES"); bioDevicesServiceField.setAccessible(true); @@ -898,9 +976,11 @@ public void testSubmitRegistrationDto_LostFlow() throws Exception { regDtoField.set(registrationService, dto); when(globalParamRepository.getSelectedHandles()).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.argThat(arg -> - !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); + Mockito.when( + globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))) + .thenReturn(null); + Mockito.when(globalParamRepository.getCachedStringGlobalParam( + Mockito.argThat(arg -> !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); // Mock GPS validation to be disabled to skip location validation when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Mock audit service to return empty list to avoid NPE @@ -912,7 +992,9 @@ public void testSubmitRegistrationDto_LostFlow() throws Exception { centerMachineDto.setMachineRefId("machineRefId"); when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); when(identitySchemaRepository.getSchemaJson(Mockito.any(), Mockito.anyDouble())).thenReturn("{}"); - when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn("containerPath123"); + when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())) + .thenReturn("containerPath123"); // Fix: Set BIO_DEVICES field on biometricService mock Field bioDevicesServiceField = Biometrics095Service.class.getDeclaredField("BIO_DEVICES"); bioDevicesServiceField.setAccessible(true); @@ -923,7 +1005,8 @@ public void testSubmitRegistrationDto_LostFlow() throws Exception { } @Test - // Test for submitRegistrationDto with empty container path - implementation doesn't throw exception, just skips packetId + // Test for submitRegistrationDto with empty container path - implementation + // doesn't throw exception, just skips packetId public void testSubmitRegistrationDto_EmptyContainerPath() throws Exception { RegistrationDto dto = mock(RegistrationDto.class); Map demographics = new HashMap<>(); @@ -954,9 +1037,11 @@ public void testSubmitRegistrationDto_EmptyContainerPath() throws Exception { regDtoField.set(registrationService, dto); when(globalParamRepository.getSelectedHandles()).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))).thenReturn(null); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.argThat(arg -> - !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); + Mockito.when( + globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))) + .thenReturn(null); + Mockito.when(globalParamRepository.getCachedStringGlobalParam( + Mockito.argThat(arg -> !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg)))).thenReturn("1.2.3"); // Mock GPS validation to be disabled to skip location validation when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Mock audit service to return empty list to avoid NPE @@ -968,7 +1053,8 @@ public void testSubmitRegistrationDto_EmptyContainerPath() throws Exception { centerMachineDto.setMachineRefId("machineRefId"); when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); when(identitySchemaRepository.getSchemaJson(Mockito.any(), Mockito.anyDouble())).thenReturn("{}"); - when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn(""); + when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn(""); // Fix: Set BIO_DEVICES field on biometricService mock Field bioDevicesServiceField = Biometrics095Service.class.getDeclaredField("BIO_DEVICES"); bioDevicesServiceField.setAccessible(true); @@ -976,8 +1062,10 @@ public void testSubmitRegistrationDto_EmptyContainerPath() throws Exception { registrationService.submitRegistrationDto("makerName"); // Verify that insertRegistration was called even with empty containerPath - // When containerPath is empty string "", the condition evaluates to true but packetId mock returns null - // getAdditionalInfo() may return null for email/phone if getKey() returns empty string + // When containerPath is empty string "", the condition evaluates to true but + // packetId mock returns null + // getAdditionalInfo() may return null for email/phone if getKey() returns empty + // string Mockito.verify(registrationRepository).insertRegistration( Mockito.any(), // packetId is null (mock returns null) eq(""), // containerPath is "" @@ -1012,10 +1100,12 @@ public void testAddMetaInfoMap_AllFields() throws Exception { Map serviceBioDevices = new HashMap<>(); serviceBioDevices.put(Modality.FACE, new HashMap<>()); bioDevicesServiceField.set(biometricService, serviceBioDevices); - Method addMetaInfoMap = registrationService.getClass().getDeclaredMethod("addMetaInfoMap", String.class, String.class, String.class); + Method addMetaInfoMap = registrationService.getClass().getDeclaredMethod("addMetaInfoMap", String.class, + String.class, String.class); addMetaInfoMap.setAccessible(true); addMetaInfoMap.invoke(registrationService, "center", "machine", "maker"); - Mockito.verify(packetWriterService, Mockito.atLeastOnce()).addMetaInfo(Mockito.anyString(), Mockito.anyString(), Mockito.any()); + Mockito.verify(packetWriterService, Mockito.atLeastOnce()).addMetaInfo(Mockito.anyString(), Mockito.anyString(), + Mockito.any()); } @Test @@ -1036,8 +1126,10 @@ public void testGetKey_FullNameAndOther() throws Exception { Method getKey = registrationService.getClass().getDeclaredMethod("getKey", RegistrationDto.class, String.class); getKey.setAccessible(true); - String fullNameKey = (String) getKey.invoke(registrationService, dto, RegistrationConstants.UI_SCHEMA_SUBTYPE_FULL_NAME); - String emailKey = (String) getKey.invoke(registrationService, dto, RegistrationConstants.UI_SCHEMA_SUBTYPE_EMAIL); + String fullNameKey = (String) getKey.invoke(registrationService, dto, + RegistrationConstants.UI_SCHEMA_SUBTYPE_FULL_NAME); + String emailKey = (String) getKey.invoke(registrationService, dto, + RegistrationConstants.UI_SCHEMA_SUBTYPE_EMAIL); assertEquals("fullNameId", fullNameKey); assertEquals("emailId", emailKey); } @@ -1045,7 +1137,8 @@ public void testGetKey_FullNameAndOther() throws Exception { @Test // Test for convertImageToBytes with valid base64 string public void testConvertImageToBytes_IOException() throws Exception { - Method convertImageToBytes = registrationService.getClass().getDeclaredMethod("convertImageToBytes", String.class); + Method convertImageToBytes = registrationService.getClass().getDeclaredMethod("convertImageToBytes", + String.class); convertImageToBytes.setAccessible(true); // Should return null for invalid base64 assertNull(convertImageToBytes.invoke(registrationService, "not_base64")); @@ -1054,9 +1147,12 @@ public void testConvertImageToBytes_IOException() throws Exception { @Test // Test for getAttemptsCount with default value of zero public void testGetAttemptsCount_DefaultZero() throws Exception { - // Use a valid modality not handled in the switch-case, or use a handled one and expect the correct value. - // If all modalities are handled, use a handled one and expect the configured value. - java.lang.reflect.Method getAttemptsCount = registrationService.getClass().getDeclaredMethod("getAttemptsCount", Modality.class); + // Use a valid modality not handled in the switch-case, or use a handled one and + // expect the correct value. + // If all modalities are handled, use a handled one and expect the configured + // value. + java.lang.reflect.Method getAttemptsCount = registrationService.getClass().getDeclaredMethod("getAttemptsCount", + Modality.class); getAttemptsCount.setAccessible(true); // Use Modality.FACE for a handled case, expecting the mocked value (2) when(globalParamRepository.getCachedIntegerGlobalParam(RegistrationConstants.FACE_ATTEMPTS_KEY)).thenReturn(2); @@ -1092,7 +1188,8 @@ public void testGetBiometricRecord_ServerVersion_115_SkipsExceptionPhotoAndExcep regDtoField.set(registrationService, dto); // Call private method via reflection - java.lang.reflect.Method getBiometricRecord = registrationService.getClass().getDeclaredMethod("getBiometricRecord", String.class, String.class); + java.lang.reflect.Method getBiometricRecord = registrationService.getClass() + .getDeclaredMethod("getBiometricRecord", String.class, String.class); getBiometricRecord.setAccessible(true); Object result = getBiometricRecord.invoke(registrationService, fieldId, serverVersion); @@ -1127,7 +1224,8 @@ public void testGetBiometricRecord_EmptyListsAndNoExceptions() throws Exception regDtoField.set(registrationService, dto); // Call private method via reflection - java.lang.reflect.Method getBiometricRecord = registrationService.getClass().getDeclaredMethod("getBiometricRecord", String.class, String.class); + java.lang.reflect.Method getBiometricRecord = registrationService.getClass() + .getDeclaredMethod("getBiometricRecord", String.class, String.class); getBiometricRecord.setAccessible(true); Object result = getBiometricRecord.invoke(registrationService, fieldId, serverVersion); @@ -1209,13 +1307,20 @@ public void testSubmitRegistrationDto_SelectedHandles_UpdateFlow() throws Except regDtoField.set(registrationService, dto); when(globalParamRepository.getSelectedHandles()).thenReturn(Collections.singletonList("handle1")); - // Fix: Provide a valid numeric string for AUDIT_EXPORTED_TILL to avoid NumberFormatException - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))).thenReturn("0"); - // Only return "1.1.5" for SERVER_VERSION, otherwise return null or a valid numeric string - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.argThat(arg -> - RegistrationConstants.SERVER_VERSION.equals(arg)))).thenReturn("1.1.5"); - Mockito.when(globalParamRepository.getCachedStringGlobalParam(Mockito.argThat(arg -> - !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg) && !RegistrationConstants.SERVER_VERSION.equals(arg)))).thenReturn("1"); + // Fix: Provide a valid numeric string for AUDIT_EXPORTED_TILL to avoid + // NumberFormatException + Mockito.when( + globalParamRepository.getCachedStringGlobalParam(Mockito.eq(RegistrationConstants.AUDIT_EXPORTED_TILL))) + .thenReturn("0"); + // Only return "1.1.5" for SERVER_VERSION, otherwise return null or a valid + // numeric string + Mockito.when(globalParamRepository + .getCachedStringGlobalParam(Mockito.argThat(arg -> RegistrationConstants.SERVER_VERSION.equals(arg)))) + .thenReturn("1.1.5"); + Mockito.when(globalParamRepository.getCachedStringGlobalParam( + Mockito.argThat(arg -> !RegistrationConstants.AUDIT_EXPORTED_TILL.equals(arg) + && !RegistrationConstants.SERVER_VERSION.equals(arg)))) + .thenReturn("1"); // Mock GPS validation to be disabled to skip location validation when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); // Mock audit service to return empty list to avoid NPE @@ -1226,7 +1331,9 @@ public void testSubmitRegistrationDto_SelectedHandles_UpdateFlow() throws Except centerMachineDto.setMachineRefId("machineRefId"); when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); when(identitySchemaRepository.getSchemaJson(Mockito.any(), Mockito.anyDouble())).thenReturn("{}"); - when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn("containerPath123"); + when(packetWriterService.persistPacket(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())) + .thenReturn("containerPath123"); // Fix: Set BIO_DEVICES field on biometricService mock Field bioDevicesServiceField = Biometrics095Service.class.getDeclaredField("BIO_DEVICES"); bioDevicesServiceField.setAccessible(true); @@ -1258,7 +1365,8 @@ public void testBuildBIR_NullDecodedBioResponse() { assertArrayEquals(new byte[0], bir.getBdb()); // sb is also an empty array assertArrayEquals(new byte[0], bir.getSb()); - // others is not null, and should contain all expected keys with default/empty values + // others is not null, and should contain all expected keys with default/empty + // values assertNotNull(bir.getOthers()); // Accept both "true" and null for "exception" key String exceptionValue = bir.getOthers().get("exception"); @@ -1294,12 +1402,12 @@ public void testBuildBIR_InvalidDecodedBioResponse() { biometricsDto.setSpecVersion("1.0"); biometricsDto.setQualityScore(10); - BIR bir = ((RegistrationServiceImpl)registrationService).buildBIR(biometricsDto); + BIR bir = ((RegistrationServiceImpl) registrationService).buildBIR(biometricsDto); assertNotNull(bir); assertNotNull(bir.getBdb()); - assertEquals("test", new String(bir.getBdb())); // decoded from base64 - assertEquals("sig", new String(bir.getSb())); // assuming set directly + assertEquals("test", new String(bir.getBdb())); // decoded from base64 + assertEquals("sig", new String(bir.getSb())); // assuming set directly assertNotNull(bir.getOthers()); // Accept both expected value and null for these keys String modality = bir.getOthers().get("modality"); @@ -1328,20 +1436,24 @@ public void testAddMetaInfoMap_EmptyBioDevices() throws Exception { java.lang.reflect.Field bioDevicesServiceField = biometricService.getClass().getDeclaredField("BIO_DEVICES"); bioDevicesServiceField.setAccessible(true); bioDevicesServiceField.set(biometricService, new HashMap<>()); - Method addMetaInfoMap = registrationService.getClass().getDeclaredMethod("addMetaInfoMap", String.class, String.class, String.class); + Method addMetaInfoMap = registrationService.getClass().getDeclaredMethod("addMetaInfoMap", String.class, + String.class, String.class); addMetaInfoMap.setAccessible(true); addMetaInfoMap.invoke(registrationService, "center", "machine", "maker"); - Mockito.verify(packetWriterService, Mockito.atLeastOnce()).addMetaInfo(Mockito.anyString(), Mockito.anyString(), Mockito.any()); + Mockito.verify(packetWriterService, Mockito.atLeastOnce()).addMetaInfo(Mockito.anyString(), Mockito.anyString(), + Mockito.any()); } @Test // Test getLabelValueDTOListString with null values in map public void testGetLabelValueDTOListString_NullValues() throws Exception { - Method getLabelValueDTOListString = registrationService.getClass().getDeclaredMethod("getLabelValueDTOListString", Map.class); + Method getLabelValueDTOListString = registrationService.getClass() + .getDeclaredMethod("getLabelValueDTOListString", Map.class); getLabelValueDTOListString.setAccessible(true); Map map = new HashMap<>(); map.put("label", null); - List> result = (List>) getLabelValueDTOListString.invoke(registrationService, map); + List> result = (List>) getLabelValueDTOListString + .invoke(registrationService, map); assertEquals(1, result.size()); assertNull(result.get(0).get("value")); } @@ -1371,7 +1483,7 @@ public void testGetAudits_NonEmptyList() { when(globalParamRepository.getCachedStringGlobalParam(Mockito.anyString())).thenReturn("0"); when(auditManagerService.getAuditLogs(Mockito.anyLong())).thenReturn(Collections.singletonList(audit)); - List> audits = ((RegistrationServiceImpl)registrationService).getAudits(); + List> audits = ((RegistrationServiceImpl) registrationService).getAudits(); assertEquals(1, audits.size()); assertEquals("EID", audits.get(0).get("eventId")); } @@ -1395,12 +1507,13 @@ public void testGetKey_NoMatchingSubtype() throws Exception { } @Test - // Test getAttemptsCount with null modality (should throw NPE as per current implementation) + // Test getAttemptsCount with null modality (should throw NPE as per current + // implementation) public void testGetAttemptsCount_NullModality() throws Exception { Method getAttemptsCount = registrationService.getClass().getDeclaredMethod("getAttemptsCount", Modality.class); getAttemptsCount.setAccessible(true); try { - getAttemptsCount.invoke(registrationService, new Object[]{null}); + getAttemptsCount.invoke(registrationService, new Object[] { null }); fail("Expected NullPointerException"); } catch (Exception e) { Throwable cause = e.getCause(); @@ -1409,7 +1522,8 @@ public void testGetAttemptsCount_NullModality() throws Exception { } @Test - // Test convertImageToPDF with IOException (simulate by passing null image, expect null result) + // Test convertImageToPDF with IOException (simulate by passing null image, + // expect null result) public void testConvertImageToPDF_IOException() throws Exception { Method convertImageToPDF = registrationService.getClass().getDeclaredMethod("convertImageToPDF", List.class); convertImageToPDF.setAccessible(true); @@ -1431,7 +1545,8 @@ public void testConvertImageToPDF_IOException() throws Exception { } @Test - // Test approveRegistration and rejectRegistration with a real Registration object (no-op) + // Test approveRegistration and rejectRegistration with a real Registration + // object (no-op) public void testApproveAndRejectRegistration_RealRegistration() { Registration registration = new Registration("dummy"); registrationService.approveRegistration(registration); @@ -1507,7 +1622,8 @@ public void testConvertImageToPDF_NullAndZeroLength() throws Exception { @Test // Test getCompressedImage with empty array and null quality public void testGetCompressedImage_EmptyArray() throws Exception { - Method getCompressedImage = registrationService.getClass().getDeclaredMethod("getCompressedImage", byte[].class, Float.class); + Method getCompressedImage = registrationService.getClass().getDeclaredMethod("getCompressedImage", byte[].class, + Float.class); getCompressedImage.setAccessible(true); byte[] result = (byte[]) getCompressedImage.invoke(registrationService, new byte[0], null); assertArrayEquals(new byte[0], result); @@ -1516,7 +1632,8 @@ public void testGetCompressedImage_EmptyArray() throws Exception { @Test // Test getScaledDimension with original smaller than bounds public void testGetScaledDimension_OriginalSmaller() throws Exception { - Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, int.class, int.class, int.class); + Method getScaledDimension = registrationService.getClass().getDeclaredMethod("getScaledDimension", int.class, + int.class, int.class, int.class); getScaledDimension.setAccessible(true); int[] result = (int[]) getScaledDimension.invoke(null, 10, 10, 100, 100); assertEquals(10, result[0]); @@ -1564,7 +1681,8 @@ public void testBuildBIR_NullAndEmpty() { @Test // Test getLabelValueDTOListString with null map public void testGetLabelValueDTOListString_NullMap() throws Exception { - Method getLabelValueDTOListString = registrationService.getClass().getDeclaredMethod("getLabelValueDTOListString", Map.class); + Method getLabelValueDTOListString = registrationService.getClass() + .getDeclaredMethod("getLabelValueDTOListString", Map.class); getLabelValueDTOListString.setAccessible(true); try { getLabelValueDTOListString.invoke(registrationService, (Object) null); @@ -1580,138 +1698,14 @@ public void testGetAudits_NullAndEmpty() { when(globalParamRepository.getCachedStringGlobalParam(Mockito.anyString())).thenReturn(null); // Fix: Return empty list instead of null to avoid NPE in production code when(auditManagerService.getAuditLogs(Mockito.anyLong())).thenReturn(Collections.emptyList()); - List> audits = ((RegistrationServiceImpl)registrationService).getAudits(); + List> audits = ((RegistrationServiceImpl) registrationService).getAudits(); assertNotNull(audits); assertTrue(audits.isEmpty()); } @Test - // Test for validateLocation when distance exceeds allowed threshold - public void testValidateLocation_DistanceExceedsThrowsClientCheckedException() throws Exception { - RegistrationDto dto = mock(RegistrationDto.class); - GeoLocationDto geoLocationDto = new GeoLocationDto(77.0d, 12.0d); - when(dto.getGeoLocationDto()).thenReturn(geoLocationDto); - - Field regDtoField = registrationService.getClass().getDeclaredField("registrationDto"); - regDtoField.setAccessible(true); - regDtoField.set(registrationService, dto); - - when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); - CenterMachineDto centerMachineDto = new CenterMachineDto(); - centerMachineDto.setCenterId("CENTER"); - when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - - RegistrationCenter center = new RegistrationCenter("CENTER", "eng"); - center.setLatitude("12.0"); - center.setLongitude("77.1"); - when(registrationCenterRepository.getRegistrationCenter("CENTER")) - .thenReturn(Collections.singletonList(center)); - - when(globalParamRepository.getCachedStringMachineToCenterDistance()).thenReturn("1.0"); - when(locationValidationService.getDistance(anyDouble(), anyDouble(), anyDouble(), anyDouble())).thenReturn(5.0); - - Method validateLocation = registrationService.getClass().getDeclaredMethod("validateLocation"); - validateLocation.setAccessible(true); - - try { - validateLocation.invoke(registrationService); - fail("Expected ClientCheckedException"); - } catch (InvocationTargetException e) { - assertTrue(e.getCause() instanceof ClientCheckedException); - } finally { - regDtoField.set(registrationService, null); - } - } - - @Test - // Test for validateLocation when center coordinates are invalid - public void testValidateLocation_InvalidCenterCoordinatesIgnored() throws Exception { - RegistrationDto dto = mock(RegistrationDto.class); - GeoLocationDto geoLocationDto = new GeoLocationDto(77.0d, 12.0d); - when(dto.getGeoLocationDto()).thenReturn(geoLocationDto); - - Field regDtoField = registrationService.getClass().getDeclaredField("registrationDto"); - regDtoField.setAccessible(true); - regDtoField.set(registrationService, dto); - - when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); - CenterMachineDto centerMachineDto = new CenterMachineDto(); - centerMachineDto.setCenterId("CENTER"); - when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - - RegistrationCenter center = new RegistrationCenter("CENTER", "eng"); - center.setLatitude("invalid"); - center.setLongitude("77.1"); - when(registrationCenterRepository.getRegistrationCenter("CENTER")) - .thenReturn(Collections.singletonList(center)); - - Method validateLocation = registrationService.getClass().getDeclaredMethod("validateLocation"); - validateLocation.setAccessible(true); - - validateLocation.invoke(registrationService); - - regDtoField.set(registrationService, null); - } - - @Test - // Test for validateLocation when geo location is not available - public void testValidateLocation_NoGeoLocationSkipsValidation() throws Exception { - RegistrationDto dto = mock(RegistrationDto.class); - when(dto.getGeoLocationDto()).thenReturn(null); - - Field regDtoField = registrationService.getClass().getDeclaredField("registrationDto"); - regDtoField.setAccessible(true); - regDtoField.set(registrationService, dto); - - when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); - - Method validateLocation = registrationService.getClass().getDeclaredMethod("validateLocation"); - validateLocation.setAccessible(true); - - validateLocation.invoke(registrationService); - - regDtoField.set(registrationService, null); - } - - @Test - // Test for validateLocation when max allowed distance is missing - public void testValidateLocation_MissingMaxDistanceThrowsClientCheckedException() throws Exception { - RegistrationDto dto = mock(RegistrationDto.class); - GeoLocationDto geoLocationDto = new GeoLocationDto(77.0d, 12.0d); - when(dto.getGeoLocationDto()).thenReturn(geoLocationDto); - - Field regDtoField = registrationService.getClass().getDeclaredField("registrationDto"); - regDtoField.setAccessible(true); - regDtoField.set(registrationService, dto); - - when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("N"); - CenterMachineDto centerMachineDto = new CenterMachineDto(); - centerMachineDto.setCenterId("CENTER"); - when(masterDataService.getRegistrationCenterMachineDetails()).thenReturn(centerMachineDto); - - RegistrationCenter center = new RegistrationCenter("CENTER", "eng"); - center.setLatitude("12.0"); - center.setLongitude("77.1"); - when(registrationCenterRepository.getRegistrationCenter("CENTER")) - .thenReturn(Collections.singletonList(center)); - - when(globalParamRepository.getCachedStringMachineToCenterDistance()).thenReturn(null); - - Method validateLocation = registrationService.getClass().getDeclaredMethod("validateLocation"); - validateLocation.setAccessible(true); - - try { - validateLocation.invoke(registrationService); - fail("Expected ClientCheckedException"); - } catch (InvocationTargetException e) { - assertTrue(e.getCause() instanceof ClientCheckedException); - } finally { - regDtoField.set(registrationService, null); - } - } - - @Test - // Test for submitRegistrationDto deleting pre-registration records when preRegistrationId present + // Test for submitRegistrationDto deleting pre-registration records when + // preRegistrationId present public void testSubmitRegistrationDto_DeletesPreRegistrationRecord() throws Exception { RegistrationDto dto = Mockito.mock(RegistrationDto.class, Mockito.withSettings().lenient()); Field regDtoField = registrationService.getClass().getDeclaredField("registrationDto"); @@ -1732,7 +1726,8 @@ public void testSubmitRegistrationDto_DeletesPreRegistrationRecord() throws Exce when(dto.getGeoLocationDto()).thenReturn(null); when(dto.getPacketId()).thenReturn(null); when(dto.getApplicationId()).thenReturn(null); - when(dto.getBestBiometrics(Mockito.anyString(), Mockito.any(Modality.class))).thenReturn(Collections.emptyList()); + when(dto.getBestBiometrics(Mockito.anyString(), Mockito.any(Modality.class))) + .thenReturn(Collections.emptyList()); java.lang.reflect.Field capturedBioFieldsField = dto.getClass().getField("CAPTURED_BIO_FIELDS"); capturedBioFieldsField.set(dto, Collections.emptySet()); @@ -1743,10 +1738,12 @@ public void testSubmitRegistrationDto_DeletesPreRegistrationRecord() throws Exce when(globalParamRepository.getSelectedHandles()).thenReturn(Collections.singletonList("handle1")); when(globalParamRepository.getCachedStringGpsDeviceEnableFlag()).thenReturn("Y"); - when(globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.AUDIT_EXPORTED_TILL)).thenReturn("0"); - when(globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.INDIVIDUAL_BIOMETRICS_ID)).thenReturn("bioField"); - when(globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)).thenReturn("2.0.0"); - + when(globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.AUDIT_EXPORTED_TILL)) + .thenReturn("0"); + when(globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.INDIVIDUAL_BIOMETRICS_ID)) + .thenReturn("bioField"); + when(globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION)) + .thenReturn("2.0.0"); CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterId("centerId"); @@ -1765,13 +1762,15 @@ public void testSubmitRegistrationDto_DeletesPreRegistrationRecord() throws Exce PreRegistrationList preRegistrationList = new PreRegistrationList(); preRegistrationList.setId("pre-id"); - when(preRegistrationDataSyncService.getPreRegistrationRecordForDeletion("pre123")).thenReturn(preRegistrationList); + when(preRegistrationDataSyncService.getPreRegistrationRecordForDeletion("pre123")) + .thenReturn(preRegistrationList); registrationService.submitRegistrationDto("maker"); verify(preRegistrationDataSyncService).getPreRegistrationRecordForDeletion("pre123"); ArgumentCaptor listCaptor = ArgumentCaptor.forClass(List.class); - verify(preRegistrationDataSyncService).deletePreRegRecords(Mockito.any(ResponseDto.class), listCaptor.capture()); + verify(preRegistrationDataSyncService).deletePreRegRecords(Mockito.any(ResponseDto.class), + listCaptor.capture()); List captured = listCaptor.getValue(); assertNotNull(captured); assertTrue(captured.contains(preRegistrationList)); @@ -1818,20 +1817,17 @@ public void testSetBiometrics_AddsBiometricRecordAndMetaInfo() throws Exception } @Test - // Test doPreChecksBeforeRegistration with null context external cache dir + // Test doPreChecksBeforeRegistration with null context external cache dir - implementation uses StorageUtils (mocked), so succeeds public void testDoPreChecksBeforeRegistration_NullCacheDir() throws Exception { CenterMachineDto centerMachineDto = new CenterMachineDto(); centerMachineDto.setCenterStatus(true); centerMachineDto.setMachineStatus(true); when(mockApplicationContext.getExternalCacheDir()).thenReturn(null); - Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", CenterMachineDto.class); + Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", + CenterMachineDto.class); doPreChecks.setAccessible(true); - try { - doPreChecks.invoke(registrationService, centerMachineDto); - fail("Expected NullPointerException"); - } catch (Exception e) { - // Expected - } + // StorageUtils.getPacketStorageDir is mocked in setUp, so doPreChecks succeeds + doPreChecks.invoke(registrationService, centerMachineDto); } @Test @@ -1840,14 +1836,16 @@ public void testDoPreChecksBeforeRegistration_NullCenterMachineDto() throws Exce File mockFile = mock(File.class); when(mockFile.getUsableSpace()).thenReturn(100L * (1024 * 1024)); when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); - Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", CenterMachineDto.class); + Method doPreChecks = registrationService.getClass().getDeclaredMethod("doPreChecksBeforeRegistration", + CenterMachineDto.class); doPreChecks.setAccessible(true); try { doPreChecks.invoke(registrationService, (Object) null); fail("Expected ClientCheckedException"); - } catch (Exception e) { + } catch (InvocationTargetException e) { Throwable cause = e.getCause(); - assertTrue(cause instanceof ClientCheckedException); + assertTrue("Expected ClientCheckedException but got " + cause.getClass().getName(), + cause instanceof ClientCheckedException); } } @@ -1872,12 +1870,14 @@ public void testStartRegistration_WithNullGPS_Success() throws Exception { // Execute with null GPS RegistrationDto result = registrationService.startRegistration( - Arrays.asList("eng"), "NEW", "NEW", null, null); + new ArrayList<>(Arrays.asList("eng")), "NEW", "NEW", null, null); - // Verify: Registration succeeds, no validation called + // Verify: Registration succeeds, validation called (implementation always calls validateCenterToMachineDistance) assertNotNull(result); - assertNull(result.getGeoLocationDto()); - verify(preCheckValidatorService, never()).validateCenterToMachineDistance(any(), any()); + assertNotNull(result.getGeoLocationDto()); + assertNull(result.getGeoLocationDto().getLatitude()); + assertNull(result.getGeoLocationDto().getLongitude()); + verify(preCheckValidatorService, Mockito.atLeastOnce()).validateCenterToMachineDistance(any(), any()); } @Test @@ -1898,13 +1898,14 @@ public void testStartRegistration_WithGPS_ValidationPasses_Success() throws Exce when(mockApplicationContext.getExternalCacheDir()).thenReturn(mockFile); // Setup: Validation passes (no exception thrown) - // Note: PreCheckValidatorService.validateCenterToMachineDistance doesn't throw when validation passes + // Note: PreCheckValidatorService.validateCenterToMachineDistance doesn't throw + // when validation passes // Execute with GPS coordinates Double latitude = 12.9716; Double longitude = 77.5946; RegistrationDto result = registrationService.startRegistration( - Arrays.asList("eng"), "NEW", "NEW", latitude, longitude); + new ArrayList<>(Arrays.asList("eng")), "NEW", "NEW", latitude, longitude); // Verify: Registration succeeds, GPS set, validation called assertNotNull(result); @@ -1935,14 +1936,14 @@ public void testStartRegistration_WithGPS_ValidationFails_ThrowsException() thro Double latitude = 13.9716; Double longitude = 78.5946; ClientCheckedException validationException = new ClientCheckedException( - mockApplicationContext, android.R.string.unknownName, "OPT_TO_REG_OUTSIDE_LOCATION"); + "OPT_TO_REG_OUTSIDE_LOCATION", "validation failed"); Mockito.doThrow(validationException).when(preCheckValidatorService) .validateCenterToMachineDistance(longitude, latitude); // Execute - should throw exception try { registrationService.startRegistration( - Arrays.asList("eng"), "NEW", "NEW", latitude, longitude); + new ArrayList<>(Arrays.asList("eng")), "NEW", "NEW", latitude, longitude); } catch (ClientCheckedException e) { // Verify: Validation was called verify(preCheckValidatorService).validateCenterToMachineDistance(longitude, latitude); @@ -1955,9 +1956,9 @@ public void testStartRegistration_WithGPS_SyncValidatorNull_SkipsValidation() th // Setup: Create service without PreCheckValidatorService (null) RegistrationService serviceWithoutValidator = new RegistrationServiceImpl( mockApplicationContext, packetWriterService, - registrationRepository, masterDataService, identitySchemaRepository, - clientCryptoManagerService, keyStoreRepository, globalParamRepository, - auditManagerService, registrationCenterRepository, locationValidationService, + registrationRepository, masterDataService, identitySchemaRepository, + clientCryptoManagerService, keyStoreRepository, globalParamRepository, + auditManagerService, registrationCenterRepository, locationValidationService, preRegistrationDataSyncServiceProvider, biometricService, packetService, null); CenterMachineDto centerMachineDto = new CenterMachineDto(); @@ -1978,7 +1979,7 @@ public void testStartRegistration_WithGPS_SyncValidatorNull_SkipsValidation() th Double latitude = 12.9716; Double longitude = 77.5946; RegistrationDto result = serviceWithoutValidator.startRegistration( - Arrays.asList("eng"), "NEW", "NEW", latitude, longitude); + new ArrayList<>(Arrays.asList("eng")), "NEW", "NEW", latitude, longitude); // Verify: Registration succeeds, GPS set, no validation exception assertNotNull(result); @@ -2007,12 +2008,14 @@ public void testStartRegistration_WithGPS_LatitudeNull_SkipsValidation() throws // Execute with null latitude (partial GPS) RegistrationDto result = registrationService.startRegistration( - Arrays.asList("eng"), "NEW", "NEW", null, 77.5946); + new ArrayList<>(Arrays.asList("eng")), "NEW", "NEW", null, 77.5946); - // Verify: Registration succeeds, no GPS set, no validation called + // Verify: Registration succeeds, geo set with longitude only (implementation always sets geo) assertNotNull(result); - assertNull(result.getGeoLocationDto()); - verify(preCheckValidatorService, never()).validateCenterToMachineDistance(any(), any()); + assertNotNull(result.getGeoLocationDto()); + assertNull(result.getGeoLocationDto().getLatitude()); + assertEquals(Double.valueOf(77.5946), result.getGeoLocationDto().getLongitude()); + verify(preCheckValidatorService, Mockito.atLeastOnce()).validateCenterToMachineDistance(any(), any()); } @Test @@ -2034,11 +2037,13 @@ public void testStartRegistration_WithGPS_LongitudeNull_SkipsValidation() throws // Execute with null longitude (partial GPS) RegistrationDto result = registrationService.startRegistration( - Arrays.asList("eng"), "NEW", "NEW", 12.9716, null); + new ArrayList<>(Arrays.asList("eng")), "NEW", "NEW", 12.9716, null); - // Verify: Registration succeeds, no GPS set, no validation called + // Verify: Registration succeeds, geo set with latitude only (implementation always sets geo) assertNotNull(result); - assertNull(result.getGeoLocationDto()); - verify(preCheckValidatorService, never()).validateCenterToMachineDistance(any(), any()); + assertNotNull(result.getGeoLocationDto()); + assertEquals(Double.valueOf(12.9716), result.getGeoLocationDto().getLatitude()); + assertNull(result.getGeoLocationDto().getLongitude()); + verify(preCheckValidatorService, Mockito.atLeastOnce()).validateCenterToMachineDistance(any(), any()); } } \ No newline at end of file diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/CronExpressionParserTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/CronExpressionParserTest.java index 4919feb02..aaa880185 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/CronExpressionParserTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/CronExpressionParserTest.java @@ -18,7 +18,7 @@ import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) public class CronExpressionParserTest { private MockedStatic logMock; diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/SyncRestUtilTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/SyncRestUtilTest.java index 043f1292a..829405ab6 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/SyncRestUtilTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/SyncRestUtilTest.java @@ -29,7 +29,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) public class SyncRestUtilTest { @Mock @@ -124,7 +124,7 @@ public void testReturnsFirstServiceErrorWhenErrorsExist() { wrapper.getErrors().add(error2); try (MockedStatic logMock = mockStatic(Log.class); - MockedStatic jsonMock = mockStatic(JsonUtils.class)) { + MockedStatic jsonMock = mockStatic(JsonUtils.class)) { jsonMock.when(() -> JsonUtils.javaObjectToJsonString(any())).thenReturn("json"); ServiceError result = SyncRestUtil.getServiceError(wrapper); assertEquals(error1, result); @@ -139,9 +139,10 @@ public void testHandlesJsonProcessingException() throws Exception { wrapper.setResponse(null); try (MockedStatic logMock = mockStatic(Log.class); - MockedStatic jsonMock = mockStatic(JsonUtils.class)) { + MockedStatic jsonMock = mockStatic(JsonUtils.class)) { jsonMock.when(() -> JsonUtils.javaObjectToJsonString(any())) - .thenThrow(new JsonProcessingException("fail") {}); + .thenThrow(new JsonProcessingException("fail") { + }); ServiceError result = SyncRestUtil.getServiceError(wrapper); assertEquals(error, result); } diff --git a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/UserInterfaceHelperServiceTest.java b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/UserInterfaceHelperServiceTest.java index 28cac6142..317df6d2a 100644 --- a/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/UserInterfaceHelperServiceTest.java +++ b/android/clientmanager/src/test/java/io/mosip/registration/clientmanager/util/UserInterfaceHelperServiceTest.java @@ -25,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) public class UserInterfaceHelperServiceTest { private UserInterfaceHelperService service; @@ -36,7 +36,6 @@ public class UserInterfaceHelperServiceTest { @Mock private Bitmap mockResultBitmap; - @Before public void setUp() { service = new UserInterfaceHelperService(mock(Context.class)); @@ -178,7 +177,7 @@ public void testGetFaceBitMap_IOException() { BiometricsDto dto = new BiometricsDto(); dto.setBioValue("invalid"); try (MockedStatic cryptoMock = mockStatic(CryptoUtil.class); - MockedStatic logMock = mockStatic(Log.class)) { + MockedStatic logMock = mockStatic(Log.class)) { assertNull(service.getFaceBitMap(dto)); } } @@ -193,7 +192,7 @@ public void testGetFingerBitMap_IOException() { BiometricsDto dto = new BiometricsDto(); dto.setBioValue("invalid"); try (MockedStatic cryptoMock = mockStatic(CryptoUtil.class); - MockedStatic logMock = mockStatic(Log.class)) { + MockedStatic logMock = mockStatic(Log.class)) { assertNull(service.getFingerBitMap(dto)); } } @@ -208,14 +207,14 @@ public void testGetIrisBitMap_IOException() { BiometricsDto dto = new BiometricsDto(); dto.setBioValue("invalid"); try (MockedStatic cryptoMock = mockStatic(CryptoUtil.class); - MockedStatic logMock = mockStatic(Log.class)) { + MockedStatic logMock = mockStatic(Log.class)) { assertNull(service.getIrisBitMap(dto)); } } @Test public void testGetBytes() throws IOException { - byte[] data = new byte[]{1,2,3,4,5}; + byte[] data = new byte[] { 1, 2, 3, 4, 5 }; InputStream is = new ByteArrayInputStream(data); byte[] result = service.getBytes(is); assertArrayEquals(data, result); diff --git a/android/packetmanager/src/test/java/io/mosip/registration/packetmanager/service/PosixAdapterServiceImplTest.java b/android/packetmanager/src/test/java/io/mosip/registration/packetmanager/service/PosixAdapterServiceImplTest.java index e536e06f9..e513ce304 100644 --- a/android/packetmanager/src/test/java/io/mosip/registration/packetmanager/service/PosixAdapterServiceImplTest.java +++ b/android/packetmanager/src/test/java/io/mosip/registration/packetmanager/service/PosixAdapterServiceImplTest.java @@ -1,6 +1,8 @@ package io.mosip.registration.packetmanager.service; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; import android.content.Context; @@ -15,6 +17,7 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; @@ -33,6 +36,7 @@ import io.mosip.registration.packetmanager.spi.IPacketCryptoService; import io.mosip.registration.packetmanager.util.ConfigService; +import io.mosip.registration.packetmanager.util.StorageUtils; @RunWith(RobolectricTestRunner.class) @Config(sdk = Build.VERSION_CODES.P) @@ -655,29 +659,27 @@ public void testRemoveContainer_shouldCatchExceptionAndReturnFalse() throws Exce } @Test - // Tests if initPosixAdapterService sets BASE_LOCATION correctly when storage is mounted + // Tests if initPosixAdapterService sets BASE_LOCATION to null when storage dir cannot be created public void testInitPosixAdapterService_withUnmountedStorage_shouldNotSetBaseLocation() throws Exception { - // Simulate unmounted storage + // Simulate unmounted storage: mock StorageUtils to return a dir that fails exists() and mkdirs() Context context = mock(Context.class); ObjectMapper objectMapper = new ObjectMapper(); IPacketCryptoService cryptoService = mock(IPacketCryptoService.class); - // Patch Environment.getExternalStorageState() to return not mounted - String originalState = System.getProperty("EXTERNAL_STORAGE_STATE"); - System.setProperty("EXTERNAL_STORAGE_STATE", "unmounted"); + File failingDir = mock(File.class); + when(failingDir.exists()).thenReturn(false); + when(failingDir.mkdirs()).thenReturn(false); + when(failingDir.getAbsolutePath()).thenReturn("/unmounted/path"); - PosixAdapterServiceImpl localService = new PosixAdapterServiceImpl(context, cryptoService, objectMapper); + try (MockedStatic storageUtilsMock = mockStatic(StorageUtils.class)) { + storageUtilsMock.when(() -> StorageUtils.getPacketStorageDir(any(Context.class))).thenReturn(failingDir); - // Use reflection to check BASE_LOCATION is null or not set - Field baseLocationField = PosixAdapterServiceImpl.class.getDeclaredField("BASE_LOCATION"); - baseLocationField.setAccessible(true); - String baseLocation = (String) baseLocationField.get(localService); - // Should be null or not set - assertNull(baseLocation); + PosixAdapterServiceImpl localService = new PosixAdapterServiceImpl(context, cryptoService, objectMapper); - // Restore property - if (originalState != null) { - System.setProperty("EXTERNAL_STORAGE_STATE", originalState); + Field baseLocationField = PosixAdapterServiceImpl.class.getDeclaredField("BASE_LOCATION"); + baseLocationField.setAccessible(true); + String baseLocation = (String) baseLocationField.get(localService); + assertNull(baseLocation); } } @@ -1552,30 +1554,27 @@ public void testAddObjectMetaData_createsJsonInZip() throws Exception { @Test // Tests if initPosixAdapterService sets BASE_LOCATION correctly when storage is mounted public void testInitPosixAdapterService_withMountedStorage_shouldSetBaseLocation() throws Exception { - // Arrange + // Arrange: mock StorageUtils to return a dir so BASE_LOCATION gets set File fakeExternalStorage = temporaryFolder.newFolder("external"); - ShadowEnvironment.setExternalStorageState(Environment.MEDIA_MOUNTED); - ShadowEnvironment.setExternalStorageDirectory(fakeExternalStorage.toPath()); + File expectedDir = new File(fakeExternalStorage, "mosip-test"); + expectedDir.mkdirs(); - // Mock ConfigService to return a folder name - mockStatic(ConfigService.class); - when(ConfigService.getProperty(eq("objectstore.base.location"), any())).thenReturn("mosip-test"); + try (MockedStatic storageUtilsMock = mockStatic(StorageUtils.class)) { + storageUtilsMock.when(() -> StorageUtils.getPacketStorageDir(any(Context.class))).thenReturn(expectedDir); - ObjectMapper objectMapper = new ObjectMapper(); - IPacketCryptoService cryptoService = mock(IPacketCryptoService.class); - Context context = mock(Context.class); + ObjectMapper objectMapper = new ObjectMapper(); + IPacketCryptoService cryptoService = mock(IPacketCryptoService.class); + Context context = mock(Context.class); - // Act - PosixAdapterServiceImpl localService = new PosixAdapterServiceImpl(context, cryptoService, objectMapper); + PosixAdapterServiceImpl localService = new PosixAdapterServiceImpl(context, cryptoService, objectMapper); - // Assert - File expectedDir = new File(fakeExternalStorage, "mosip-test"); - assertTrue(expectedDir.exists()); + assertTrue("Expected dir should exist after init", expectedDir.exists()); - Field baseLocationField = PosixAdapterServiceImpl.class.getDeclaredField("BASE_LOCATION"); - baseLocationField.setAccessible(true); - String baseLocation = (String) baseLocationField.get(localService); - assertEquals(expectedDir.getAbsolutePath(), baseLocation); + Field baseLocationField = PosixAdapterServiceImpl.class.getDeclaredField("BASE_LOCATION"); + baseLocationField.setAccessible(true); + String baseLocation = (String) baseLocationField.get(localService); + assertEquals(expectedDir.getAbsolutePath(), baseLocation); + } } @Test @@ -1621,8 +1620,9 @@ public boolean putObject(String account, String container, String source, String // Tests if createContainerZipWithSubPacket creates a new zip file when it does not exist @Config(manifest = Config.NONE) public void testCreateContainerZipWithSubPacket_whenZipDoesNotExist_shouldCreateNewZip() throws Exception { - // Set external storage to mounted + // Set external storage to mounted for baseDir so getExternalStorageState(baseDir) returns MEDIA_MOUNTED ShadowEnvironment.setExternalStorageState(Environment.MEDIA_MOUNTED); + ShadowEnvironment.setExternalStorageState(baseDir, Environment.MEDIA_MOUNTED); // Point to test base directory Field baseLocationField = PosixAdapterServiceImpl.class.getDeclaredField("BASE_LOCATION"); @@ -1645,8 +1645,9 @@ public void testCreateContainerZipWithSubPacket_whenZipDoesNotExist_shouldCreate // Tests if createContainerZipWithSubPacket appends to existing zip file @Config(manifest = Config.NONE) public void testCreateContainerZipWithSubPacket_whenZipExists_shouldAppendEntry() throws Exception { - // Simulate mounted external storage + // Set external storage to mounted for baseDir so getExternalStorageState(baseDir) returns MEDIA_MOUNTED ShadowEnvironment.setExternalStorageState(Environment.MEDIA_MOUNTED); + ShadowEnvironment.setExternalStorageState(baseDir, Environment.MEDIA_MOUNTED); // Set base location manually Field baseLocationField = PosixAdapterServiceImpl.class.getDeclaredField("BASE_LOCATION");