Skip to content

Commit

Permalink
[RCF-1100] Unit Test Cases (#492)
Browse files Browse the repository at this point in the history
* client manager unit test cases

Signed-off-by: Sachin S P <[email protected]>

* unit test cases

Signed-off-by: Sachin S P <[email protected]>

* unit test cases

Signed-off-by: Sachin S P <[email protected]>

* added unit test cases for packet manager

Signed-off-by: Sachin S P <[email protected]>

* unit test cases null handle

Signed-off-by: Sachin S P <[email protected]>

---------

Signed-off-by: Sachin S P <[email protected]>
Co-authored-by: Sachin S P <[email protected]>
  • Loading branch information
SachinPremkumar and Sachin S P authored Dec 24, 2024
1 parent b21ab3c commit 8e48b39
Show file tree
Hide file tree
Showing 25 changed files with 1,361 additions and 36 deletions.
4 changes: 2 additions & 2 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ buildscript {
}

dependencies {
classpath 'com.android.tools.build:gradle:7.2.0'
classpath 'com.android.tools.build:gradle:7.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.ibotta:plugin:1.2.0"
//Jacoco Plugin
Expand All @@ -27,7 +27,7 @@ allprojects {
}

ext {
compileSdkVersion = 31
compileSdkVersion = 33
buildToolsVersion = "31.0.0"

minSdkVersion = 28
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ public void syncGlobalParamsData(Runnable onFinish, boolean isManualSync) throws
Log.i(TAG, "config data sync is started");
String serverVersion = getServerVersionFromConfigs();

Call<ResponseWrapper<Map<String, Object>>> call = serverVersion.startsWith("1.1.5") ? syncRestService.getV1GlobalConfigs(
Call<ResponseWrapper<Map<String, Object>>> call = (serverVersion != null && serverVersion.startsWith("1.1.5")) ? syncRestService.getV1GlobalConfigs(
clientCryptoManagerService.getMachineName(), BuildConfig.CLIENT_VERSION) : syncRestService.getGlobalConfigs(
clientCryptoManagerService.getClientKeyIndex(), BuildConfig.CLIENT_VERSION);
call.enqueue(new Callback<ResponseWrapper<Map<String, Object>>>() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,21 +293,21 @@ public void syncAllPacketStatus() {
String serverVersion = this.globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.SERVER_VERSION);

PacketStatusRequest packetStatusRequest = new PacketStatusRequest();
packetStatusRequest.setId(serverVersion.startsWith("1.1.5") ? PACKET_STATUS_READER_ID : PACKET_EXTERNAL_STATUS_READER_ID);
packetStatusRequest.setId((serverVersion!=null && serverVersion.startsWith("1.1.5")) ? PACKET_STATUS_READER_ID : PACKET_EXTERNAL_STATUS_READER_ID);
packetStatusRequest.setVersion(PACKET_SYNC_VERSION);
packetStatusRequest.setRequesttime(DateUtils.formatToISOString(LocalDateTime.now(ZoneOffset.UTC)));
List<PacketIdDto> packets = new ArrayList<>();
for (Registration reg : registrations) {
PacketIdDto packet = new PacketIdDto();
if (serverVersion.startsWith("1.1.5")) {
if (serverVersion!=null && serverVersion.startsWith("1.1.5")) {
packet.setRegistrationId(reg.getPacketId());
} else {
packet.setPacketId(reg.getPacketId());
}
}
packetStatusRequest.setRequest(packets);

Call<PacketStatusResponse> call = serverVersion.startsWith("1.1.5") ? this.syncRestService.getV1PacketStatus(packetStatusRequest) : this.syncRestService.getPacketStatus(packetStatusRequest);
Call<PacketStatusResponse> call = (serverVersion!=null && serverVersion.startsWith("1.1.5")) ? this.syncRestService.getV1PacketStatus(packetStatusRequest) : this.syncRestService.getPacketStatus(packetStatusRequest);
call.enqueue(new Callback<PacketStatusResponse>() {
@Override
public void onResponse(Call<PacketStatusResponse> call, Response<PacketStatusResponse> response) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ public void fetchPreRegistrationIds(Runnable onFinish) {
Log.i(TAG,"Fetching Pre-Registration Id's started {}");

CenterMachineDto centerMachineDto = this.masterDataService.getRegistrationCenterMachineDetails();
Log.i(TAG,"Pre-Registration get center Id"+ centerMachineDto.getCenterId());
if (centerMachineDto == null) {
result = "application_id_sync_failed";
onFinish.run();
Expand Down Expand Up @@ -262,10 +261,9 @@ private Map<String, Object> setPacketToResponse(byte[] decryptedPacket, String p
}

private PreRegistrationList downloadAndSavePacket(@NonNull String preRegistrationId,
String lastUpdatedTimeStamp) throws ClientCheckedException, ExecutionException, InterruptedException {
String lastUpdatedTimeStamp) throws ClientCheckedException, ExecutionException, InterruptedException {

CenterMachineDto centerMachineDto = this.masterDataService.getRegistrationCenterMachineDetails();
Log.i(TAG,"Pre-Registration get center Id"+ centerMachineDto.getCenterId() + centerMachineDto.getMachineId());
if (centerMachineDto == null) {
throw new ClientCheckedException(context, R.string.err_001);
}
Expand Down Expand Up @@ -342,8 +340,10 @@ private String getToDate(Timestamp reqTime) {

Calendar cal = Calendar.getInstance();
cal.setTime(reqTime);
cal.add(Calendar.DATE,
Integer.parseInt(String.valueOf(this.globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.PRE_REG_DAYS_LIMIT))));
if(this.globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.PRE_REG_DAYS_LIMIT)!=null) {
cal.add(Calendar.DATE,
Integer.parseInt(String.valueOf(this.globalParamRepository.getCachedStringGlobalParam(RegistrationConstants.PRE_REG_DAYS_LIMIT))));
}

return formatDate(cal);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ public void submitRegistrationDto(String makerName) throws Exception {
packetWriterService.setDocument(this.registrationDto.getRId(), entry.getKey(), document);
});

if (serverVersion.startsWith("1.1.5")) {
if (serverVersion!=null && serverVersion.startsWith("1.1.5")) {
this.registrationDto.getBestBiometrics(individualBiometricsFieldId, Modality.EXCEPTION_PHOTO).forEach( b -> {
Document document = new Document();
document.setType("EOP");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
import java.util.List;

import io.mosip.registration.clientmanager.config.ClientDatabase;
import io.mosip.registration.clientmanager.dao.GlobalParamDao;
import io.mosip.registration.clientmanager.dao.IdentitySchemaDao;
import io.mosip.registration.clientmanager.dao.ProcessSpecDao;
import io.mosip.registration.clientmanager.dao.TemplateDao;
import io.mosip.registration.clientmanager.dto.http.IdSchemaResponse;
import io.mosip.registration.clientmanager.dto.uispec.FieldSpecDto;
import io.mosip.registration.clientmanager.dto.uispec.ProcessSpecDto;
Expand All @@ -41,7 +44,15 @@ public void setUp() {
.build();

IdentitySchemaDao identitySchemaDao = clientDatabase.identitySchemaDao();
identitySchemaRepository = new IdentitySchemaRepository(identitySchemaDao);
//template dao
TemplateDao templateDao = clientDatabase.templateDao();
TemplateRepository templateRepository = new TemplateRepository(templateDao);
//global param dao
GlobalParamDao globalParamDao = clientDatabase.globalParamDao();
GlobalParamRepository globalParamRepository = new GlobalParamRepository(globalParamDao);

ProcessSpecDao processSpecDao = clientDatabase.processSpecDao();
identitySchemaRepository = new IdentitySchemaRepository(templateRepository, globalParamRepository, identitySchemaDao,processSpecDao);

ProcessSpecDto processSpecDto = new ProcessSpecDto();
ScreenSpecDto screen = new ScreenSpecDto();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package io.mosip.registration.clientmanager.service;

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import android.content.Context;

import org.junit.Before;
import org.junit.Test;
import org.mockito.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.mosip.registration.clientmanager.dto.sbi.CaptureBioDetail;
import io.mosip.registration.clientmanager.exception.BiometricsServiceException;
import io.mosip.registration.clientmanager.spi.AuditManagerService;
import io.mosip.registration.clientmanager.repository.GlobalParamRepository;
import io.mosip.registration.clientmanager.repository.UserBiometricRepository;
import io.mosip.registration.keymanager.dto.JWTSignatureVerifyRequestDto;
import io.mosip.registration.keymanager.dto.JWTSignatureVerifyResponseDto;
import io.mosip.registration.keymanager.spi.ClientCryptoManagerService;
import io.mosip.registration.clientmanager.dto.sbi.CaptureRequest;
import io.mosip.registration.clientmanager.constant.Modality;
import io.mosip.registration.keymanager.util.KeyManagerConstant;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

public class Biometrics095ServiceTest {

@Mock private Context context;
@Mock private ObjectMapper objectMapper;
@Mock private AuditManagerService auditManagerService;
@Mock private GlobalParamRepository globalParamRepository;
@Mock private ClientCryptoManagerService clientCryptoManagerService;
@Mock private UserBiometricRepository userBiometricRepository;

private Biometrics095Service biometrics095Service;

@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
biometrics095Service = new Biometrics095Service(
context, objectMapper, auditManagerService, globalParamRepository,
clientCryptoManagerService, userBiometricRepository);
}

@Test
public void getRCaptureRequest_Test() {
String deviceId = "device123";
Modality modality = Modality.FACE;
List<String> exceptionAttributes = new ArrayList<>();

CaptureRequest captureRequest = biometrics095Service.getRCaptureRequest(modality, deviceId, exceptionAttributes);

assertNotNull(captureRequest);
assertEquals("Registration", captureRequest.getPurpose());
assertEquals(10000, captureRequest.getTimeout());
assertNotNull(captureRequest.getBio());
assertEquals(1, captureRequest.getBio().size());
CaptureBioDetail bioDetail = captureRequest.getBio().get(0);
assertEquals(deviceId, bioDetail.getDeviceId());
assertEquals(modality.getSingleType().value(), bioDetail.getType());
}

@Test(expected = BiometricsServiceException.class)
public void handleRCaptureResponse_Error_Test() throws Exception {
String responseJson = "{\"biometrics\": [{\"error\": {\"errorCode\": \"SOME_ERROR\", \"errorInfo\": \"Some error\"}}]}"; // Error response
InputStream responseStream = new ByteArrayInputStream(responseJson.getBytes());
Modality modality = Modality.FACE;
List<String> exceptionAttributes = new ArrayList<>();
biometrics095Service.handleRCaptureResponse(modality, responseStream, exceptionAttributes);
}

@Test
public void validateJWTResponse_Success_Test() throws Exception {
JWTSignatureVerifyResponseDto mockResponse = mock(JWTSignatureVerifyResponseDto.class);
when(mockResponse.isSignatureValid()).thenReturn(true);
when(mockResponse.getTrustValid()).thenReturn(KeyManagerConstant.TRUST_VALID);
when(clientCryptoManagerService.jwtVerify(any(JWTSignatureVerifyRequestDto.class))).thenReturn(mockResponse);

biometrics095Service.validateJWTResponse("some-signed-data", "DEVICE");
}

@Test(expected = BiometricsServiceException.class)
public void validateJWTResponse_Failure_Test() throws Exception {
JWTSignatureVerifyResponseDto mockResponse = mock(JWTSignatureVerifyResponseDto.class);
when(mockResponse.isSignatureValid()).thenReturn(false);
when(clientCryptoManagerService.jwtVerify(any(JWTSignatureVerifyRequestDto.class))).thenReturn(mockResponse);

biometrics095Service.validateJWTResponse("some-invalid-signed-data", "DEVICE");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package io.mosip.registration.clientmanager.service;

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.Context;

import org.apache.commons.lang3.NotImplementedException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.*;

import io.mosip.registration.clientmanager.repository.SyncJobDefRepository;
import io.mosip.registration.clientmanager.spi.JobTransactionService;
import io.mosip.registration.clientmanager.util.DateUtil;

public class JobManagerServiceImplTest {

@Mock
private Context mockContext;

@Mock
private JobScheduler mockJobScheduler;

@Mock
private SyncJobDefRepository mockSyncJobDefRepository;

@Mock
private JobTransactionService mockJobTransactionService;

@Mock
private DateUtil mockDateUtil;

private JobManagerServiceImpl jobManagerService;

private static final String JOB_ID = "mosip.syncJobId";
@Mock
private JobInfo.Builder mockJobInfoBuilder;


@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
jobManagerService = new JobManagerServiceImpl(mockContext, mockSyncJobDefRepository, mockJobTransactionService, mockDateUtil);
when(mockContext.getSystemService(Context.JOB_SCHEDULER_SERVICE)).thenReturn(mockJobScheduler);

mockJobInfoBuilder = mock(JobInfo.Builder.class);
when(mockJobInfoBuilder.setRequiresCharging(anyBoolean())).thenReturn(mockJobInfoBuilder);
}


@Test(expected = NotImplementedException.class)
public void scheduleJob_NotImplementedJob_Test() {
int jobId = 1;
String apiName = "nonExistentJob";

jobManagerService.scheduleJob(jobId, apiName, null);
}

@Test
public void getLastSyncTime_Test() {
int jobId = 1;
long lastSyncTime = 1609459200L; // Example timestamp

when(mockJobTransactionService.getLastSyncTime(jobId)).thenReturn(lastSyncTime);
when(mockDateUtil.getDateTime(lastSyncTime)).thenReturn("2024-11-27 00:00:00");

String lastSync = jobManagerService.getLastSyncTime(jobId);

assertEquals("2024-11-27 00:00:00", lastSync);
}

@Test
public void getNextSyncTime_Test() {
int jobId = 1;
long lastSyncTime = 1609459200L; // Example timestamp
long nextSyncTime = lastSyncTime + 15 * 60;

when(mockJobTransactionService.getLastSyncTime(jobId)).thenReturn(lastSyncTime);
when(mockDateUtil.getDateTime(nextSyncTime)).thenReturn("2024-11-27 00:15:00");

String nextSync = jobManagerService.getNextSyncTime(jobId);

assertEquals("2024-11-27 00:15:00", nextSync);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package io.mosip.registration.clientmanager.service;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

import io.mosip.registration.clientmanager.entity.JobTransaction;
import io.mosip.registration.clientmanager.repository.JobTransactionRepository;

import org.junit.Before;
import org.junit.Test;
import org.mockito.*;

public class JobTransactionServiceImplTest {

@Mock
private JobTransactionRepository jobTransactionRepository;

@InjectMocks
private JobTransactionServiceImpl jobTransactionService;

@Before
public void setUp() {
MockitoAnnotations.openMocks(this); // Initialize mocks
}

@Test
public void logJobTransaction_WhenJobTransactionIsNotFound_Test() {

int jobId = 1;
long syncTime = 1000L;

when(jobTransactionRepository.getJobTransaction(jobId)).thenReturn(null); // JobTransaction not found

jobTransactionService.LogJobTransaction(jobId, syncTime);

verify(jobTransactionRepository).createJobTransaction(any(JobTransaction.class)); // Verifying createJobTransaction is called
}

@Test
public void logJobTransaction_WhenJobTransactionIsFound_Test() {

int jobId = 1;
long syncTime = 1000L;
JobTransaction existingJobTransaction = new JobTransaction(jobId, 0L);

when(jobTransactionRepository.getJobTransaction(jobId)).thenReturn(existingJobTransaction); // JobTransaction found

jobTransactionService.LogJobTransaction(jobId, syncTime);

verify(jobTransactionRepository).updateJobTransaction(jobId, syncTime); // Verifying updateJobTransaction is called
}

@Test
public void logJobTransaction_WhenJobTransactionIsNull_Test() {

int jobId = 2;
long syncTime = 2000L;

when(jobTransactionRepository.getJobTransaction(jobId)).thenReturn(null); // No transaction found

jobTransactionService.LogJobTransaction(jobId, syncTime);

verify(jobTransactionRepository, times(1)).createJobTransaction(any(JobTransaction.class)); // Ensure create is called once
}

@Test
public void getLastSyncTime_WhenJobTransactionDoesNotExist_Test() {

int jobId = 1;
when(jobTransactionRepository.getJobTransaction(jobId)).thenReturn(null);

long actualLastSyncTime = jobTransactionService.getLastSyncTime(jobId);

assertEquals(0, actualLastSyncTime);
verify(jobTransactionRepository, times(1)).getJobTransaction(jobId); // Ensure repository method was called once
}
}
Loading

0 comments on commit 8e48b39

Please sign in to comment.