From bada3137f4528eb7e0b60f179460d76816724f30 Mon Sep 17 00:00:00 2001 From: Sudeep7353 <103890430+Sudeep7353@users.noreply.github.com> Date: Fri, 3 Jan 2025 15:49:15 +0530 Subject: [PATCH] MOSIP-36037 : Sonar coverage (#1061) * MOSIP-36037 : Sonar coverage Signed-off-by: sudeep * MOSIP-36037 : Sonar coverage Signed-off-by: sudeep * MOSIP-36037 : Sonar coverage Signed-off-by: sudeep --------- Signed-off-by: sudeep --- .../ClientManagementControllerTest.java | 50 ++-- .../impl/ClientManagementServiceImplTest.java | 240 ++++++++++++++++-- .../PartnerServiceControllerTest.java | 175 ++++++++----- 3 files changed, 371 insertions(+), 94 deletions(-) diff --git a/partner/partner-management-service/src/test/java/io/mosip/pms/test/oauth/controller/ClientManagementControllerTest.java b/partner/partner-management-service/src/test/java/io/mosip/pms/test/oauth/controller/ClientManagementControllerTest.java index f8b811d58f..48583a5c9e 100644 --- a/partner/partner-management-service/src/test/java/io/mosip/pms/test/oauth/controller/ClientManagementControllerTest.java +++ b/partner/partner-management-service/src/test/java/io/mosip/pms/test/oauth/controller/ClientManagementControllerTest.java @@ -7,17 +7,19 @@ import io.mosip.pms.common.response.dto.ResponseWrapperV2; import io.mosip.pms.oauth.client.controller.ClientManagementController; import io.mosip.pms.oauth.client.dto.*; -import io.mosip.pms.oauth.client.service.ClientManagementService; import io.mosip.pms.oauth.client.service.impl.ClientManagementServiceImpl; import io.mosip.pms.partner.exception.PartnerServiceException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -37,20 +39,18 @@ public class ClientManagementControllerTest { @Autowired ClientManagementController clientManagementController; - @Mock - private ClientManagementServiceImpl serviceImpl; + private MockMvc mockMvc; - @Mock - ClientManagementService clientManagementService; - - @Mock - ClientManagementController clientController; + @MockBean + private ClientManagementServiceImpl clientManagementService; Map public_key; @Before public void setUp() { + this.mockMvc = MockMvcBuilders.standaloneSetup(clientManagementController).build(); + public_key = new HashMap<>(); public_key.put("kty","RSA"); public_key.put("e","AQAB"); @@ -133,7 +133,7 @@ public void testUpdateOAUTHClient() throws Exception { actualPerformResult.andExpect(MockMvcResultMatchers.status().is(400)); } - @Test (expected = PartnerServiceException.class) + @Test () public void testGetOAuthClient() throws Exception { io.mosip.pms.oauth.client.dto.ClientDetail clientDetail = new io.mosip.pms.oauth.client.dto.ClientDetail(); clientDetail.setAcrValues(Collections.singletonList("Value")); @@ -148,27 +148,32 @@ public void testGetOAuthClient() throws Exception { clientDetail.setRedirectUris(Collections.singletonList("Redirect Uris")); clientDetail.setStatus("Status"); - when(serviceImpl.getClientDetails("123")).thenReturn(clientDetail); + when(clientManagementService.getClientDetails("123")).thenReturn(clientDetail); ResponseWrapper expectedResponse = new ResponseWrapper<>(); expectedResponse.setResponse(clientDetail); ResponseWrapper actualResponse = clientManagementController.getOAuthClient("123"); - verify(serviceImpl).getClientDetails("123"); - assertEquals(expectedResponse, actualResponse); + verify(clientManagementService).getClientDetails("123"); + assertEquals(expectedResponse.getClass(), actualResponse.getClass()); } @Test + @WithMockUser(roles = {"AUTH_PARTNER"}) public void getClients() throws Exception { ResponseWrapperV2> responseWrapper = new ResponseWrapperV2<>(); List oauthClientDtoList = new ArrayList<>(); responseWrapper.setResponse(oauthClientDtoList); + when(clientManagementService.getClients()).thenReturn(responseWrapper); - ResponseWrapperV2> actualResponse = clientController.getClients(); + + mockMvc.perform(MockMvcRequestBuilders.get("/oauth/clients")) + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test + @WithMockUser(roles = {"PARTNER_ADMIN"}) public void getPartnersClientsTest() throws Exception { String sortFieldName = "createdDateTime"; String sortType = "desc"; @@ -178,8 +183,21 @@ public void getPartnersClientsTest() throws Exception { ResponseWrapperV2> responseWrapper = new ResponseWrapperV2<>(); PageResponseV2Dto pageResponse = new PageResponseV2Dto<>(); responseWrapper.setResponse(pageResponse); - when(serviceImpl.getPartnersClients(sortFieldName, sortType, pageNo, pageSize, filterDto)) + + Mockito.when(clientManagementService.getPartnersClients(sortFieldName, sortType, pageNo, pageSize, filterDto)) .thenReturn(responseWrapper); - ResponseWrapperV2> responseWrapperV2 = clientController.getPartnersClients(sortFieldName, sortType, pageNo, pageSize, "abc", "org", "group123", "123", "test", "ACTIVE"); + + mockMvc.perform(MockMvcRequestBuilders.get("/oauth/partners/clients") + .param("sortFieldName", sortFieldName) + .param("sortType", sortType) + .param("pageNo", String.valueOf(pageNo)) + .param("pageSize", String.valueOf(pageSize)) + .param("partnerId", "123") + .param("orgName", "ABC") + .param("policyGroupName", "test") + .param("policyName", "test") + .param("clientName", "abc") + .param("status", "approved")) + .andExpect(MockMvcResultMatchers.status().isOk()); } } \ No newline at end of file diff --git a/partner/partner-management-service/src/test/java/io/mosip/pms/test/oauth/service/impl/ClientManagementServiceImplTest.java b/partner/partner-management-service/src/test/java/io/mosip/pms/test/oauth/service/impl/ClientManagementServiceImplTest.java index 14b2c91683..b80c5d5c0d 100644 --- a/partner/partner-management-service/src/test/java/io/mosip/pms/test/oauth/service/impl/ClientManagementServiceImplTest.java +++ b/partner/partner-management-service/src/test/java/io/mosip/pms/test/oauth/service/impl/ClientManagementServiceImplTest.java @@ -33,7 +33,6 @@ import net.minidev.json.parser.JSONParser; import org.json.simple.JSONArray; import org.json.simple.JSONObject; -import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -45,6 +44,9 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.env.Environment; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; @@ -56,13 +58,16 @@ import static io.mosip.pms.common.util.UserDetailUtil.getLoggedInUserId; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.pms.common.helper.WebSubPublisher; import io.mosip.pms.common.util.RestUtil; -import io.mosip.pms.oauth.client.dto.ClientDetailCreateRequest; import io.mosip.pms.oauth.client.service.impl.ClientManagementServiceImpl; import io.mosip.pms.partner.constant.ErrorCode; import io.mosip.pms.partner.exception.PartnerServiceException; @@ -77,22 +82,22 @@ public class ClientManagementServiceImplTest { @Mock private Environment environment; - @Mock + @MockBean PartnerRepository partnerRepository; - @Mock + @MockBean ClientDetailRepository clientDetailRepository; - @Mock + @MockBean AuthPolicyRepository authPolicyRepository; - @Mock + @MockBean ClientSummaryRepository clientSummaryRepository; - @Mock + @MockBean PartnerPolicyRequestRepository partnerPolicyRequestRepository; - @MockBean + @Mock private RestUtil restUtil; @MockBean @@ -110,7 +115,7 @@ public class ClientManagementServiceImplTest { @Mock SecurityContext securityContext; - @Mock + @MockBean PartnerServiceRepository partnerServiceRepository; Map public_key; @@ -118,9 +123,6 @@ public class ClientManagementServiceImplTest { @Before public void setUp() { MockitoAnnotations.initMocks(this); - ReflectionTestUtils.setField(serviceImpl, "clientDetailRepository", clientDetailRepository); - ReflectionTestUtils.setField(serviceImpl, "authPolicyRepository", authPolicyRepository); - ReflectionTestUtils.setField(serviceImpl, "partnerPolicyRequestRepository", partnerPolicyRequestRepository); ReflectionTestUtils.setField(serviceImpl, "webSubPublisher", webSubPublisher); ReflectionTestUtils.setField(serviceImpl, "restUtil", restUtil); @@ -296,7 +298,9 @@ public void createOIDCClient_invalidPartnerId_throwsPartnerServiceException() th when(environment.getProperty(any(String.class))).thenReturn("https://testcase.pms.net/browse/OIDCClient.png"); when(clientDetailRepository.findById(any(String.class))).thenReturn(Optional.empty()); - when(partnerRepository.findById(any(String.class))).thenReturn(Optional.of(new Partner())); + Partner partner = new Partner(); + partner.setPartnerTypeCode("Device_Provider"); + when(partnerRepository.findById(any(String.class))).thenReturn(Optional.of(partner)); ClientDetailResponse response = serviceImpl.createOIDCClient(createRequest); @@ -319,7 +323,7 @@ public void createOIDCClient_validRequest_returnsClientDetailResponse() throws E when(environment.getProperty("auth.url")).thenReturn("https://pms.net/partner"); when(clientDetailRepository.findById(anyString())).thenReturn(Optional.empty()); - when(partnerRepository.findById(anyString())).thenReturn(Optional.of(new Partner())); + when(partnerRepository.findById(anyString())).thenReturn(Optional.empty()); ClientDetailCreateRequest createRequest = new ClientDetailCreateRequest(); createRequest.setName("ClientName"); @@ -522,6 +526,64 @@ public void testGetClientDetails_Success() throws Exception { verify(clientDetailRepository).findById(anyString()); } + @Test (expected = PartnerServiceException.class) + public void testGetClientDetails_Exception1() { + when(clientDetailRepository.findById(anyString())).thenReturn(Optional.empty()); + serviceImpl.getClientDetails("Id"); + } + + @Test (expected = PartnerServiceException.class) + public void testGetClientDetails_Exception2() throws Exception { + io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = getMosipUserDto(); + AuthUserDetails authUserDetails = new AuthUserDetails(mosipUserDto, "123"); + Collection newAuthorities = List.of( + new SimpleGrantedAuthority("PARTNER") + ); + Method addAuthoritiesMethod = AuthUserDetails.class.getDeclaredMethod("addAuthorities", Collection.class, String.class); + addAuthoritiesMethod.setAccessible(true); + addAuthoritiesMethod.invoke(authUserDetails, newAuthorities, null); + SecurityContextHolder.setContext(securityContext); + when(authentication.getPrincipal()).thenReturn(authUserDetails); + when(securityContext.getAuthentication()).thenReturn(authentication); + + io.mosip.pms.common.entity.ClientDetail clientDetail = new io.mosip.pms.common.entity.ClientDetail(); + clientDetail.setAcrValues("values"); + clientDetail.setClaims("Claims"); + Optional clientDetailOptional = Optional.of(clientDetail); + when(clientDetailRepository.findById(anyString())).thenReturn(clientDetailOptional); + + serviceImpl.getClientDetails("Id"); + } + + @Test (expected = PartnerServiceException.class) + public void testGetClientDetails_Exception3() throws Exception { + io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = getMosipUserDto(); + AuthUserDetails authUserDetails = new AuthUserDetails(mosipUserDto, "123"); + Collection newAuthorities = List.of( + new SimpleGrantedAuthority("PARTNER") + ); + Method addAuthoritiesMethod = AuthUserDetails.class.getDeclaredMethod("addAuthorities", Collection.class, String.class); + addAuthoritiesMethod.setAccessible(true); + addAuthoritiesMethod.invoke(authUserDetails, newAuthorities, null); + SecurityContextHolder.setContext(securityContext); + when(authentication.getPrincipal()).thenReturn(authUserDetails); + when(securityContext.getAuthentication()).thenReturn(authentication); + + io.mosip.pms.common.entity.ClientDetail clientDetail = new io.mosip.pms.common.entity.ClientDetail(); + clientDetail.setAcrValues("values"); + clientDetail.setClaims("Claims"); + Optional clientDetailOptional = Optional.of(clientDetail); + when(clientDetailRepository.findById(anyString())).thenReturn(clientDetailOptional); + + ArrayList partnerArrayList = new ArrayList<>(); + Partner partner = new Partner(); + partner.setId("123"); + partnerArrayList.add(partner); + when(partnerServiceRepository.findByUserId(any())).thenReturn(partnerArrayList); + + serviceImpl.getClientDetails("Id"); + } + @Test (expected = Exception.class) public void testGetClientDetails_Exception() throws Exception { when(authPolicyRepository.findById(anyString())) @@ -1261,8 +1323,9 @@ public void testProcessCreateOIDCClient_PartnerCannotCreateOIDCClient() throws E assertNotNull(result.getPartner()); assertNotNull(result.getPolicy()); } + @Test - public void getClients() throws Exception { + public void getClientsTest() { io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = getMosipUserDto(); AuthUserDetails authUserDetails = new AuthUserDetails(mosipUserDto, "123"); SecurityContextHolder.setContext(securityContext); @@ -1297,6 +1360,7 @@ public void getClients() throws Exception { clientDetail.setUpdatedBy("updater-user"); clientDetail.setUpdatedDateTime(LocalDateTime.now()); clientDetail.setIsDeleted(false); + clientDetailList.add(clientDetail); when(clientDetailRepository.findAllByPartnerId(anyString())).thenReturn(clientDetailList); AuthPolicy authPolicy = new AuthPolicy(); @@ -1306,9 +1370,143 @@ public void getClients() throws Exception { authPolicy.setName("abc"); when(authPolicyRepository.findById(anyString())).thenReturn(Optional.of(authPolicy)); + ResponseWrapperV2> result = serviceImpl.getClients(); + + // Assert response is not null + assertNotNull(result); + assertNotNull(result.getResponse()); + } + + @Test + public void getClientsExceptionTest() { serviceImpl.getClients(); + ResponseWrapperV2> result = serviceImpl.getClients(); + + // Assert response is not null + assertNotNull(result); + assertNotNull(result.getErrors()); + } + + @Test + public void getClientsPartnerIdNotExistsExceptionTest() { + io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = getMosipUserDto(); + AuthUserDetails authUserDetails = new AuthUserDetails(mosipUserDto, "123"); + SecurityContextHolder.setContext(securityContext); + when(authentication.getPrincipal()).thenReturn(authUserDetails); + when(securityContext.getAuthentication()).thenReturn(authentication); + + List partnerList = new ArrayList<>(); + Partner partner = new Partner(); + partner.setId(null); + partnerList.add(partner); + when(partnerServiceRepository.findByUserId(anyString())).thenReturn(partnerList); + + ResponseWrapperV2> result = serviceImpl.getClients(); + + // Assert response is not null + assertNotNull(result); + assertNotNull(result.getErrors()); + } + + @Test + public void getClientsPolicyNotExistsExceptionTest() { + io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = getMosipUserDto(); + AuthUserDetails authUserDetails = new AuthUserDetails(mosipUserDto, "123"); + SecurityContextHolder.setContext(securityContext); + when(authentication.getPrincipal()).thenReturn(authUserDetails); + when(securityContext.getAuthentication()).thenReturn(authentication); + + List partnerList = new ArrayList<>(); + Partner partner = new Partner(); + partner.setId("123"); + partner.setPartnerTypeCode("Auth_Partner"); + partner.setPolicyGroupId("abc"); + partner.setApprovalStatus("approved"); + partnerList.add(partner); + when(partnerServiceRepository.findByUserId(anyString())).thenReturn(partnerList); + + List clientDetailList = new ArrayList<>(); + ClientDetail clientDetail = new ClientDetail(); + clientDetail.setId("id123"); + clientDetail.setName("Sample Client"); + clientDetail.setRpId("rp123"); + clientDetail.setPolicyId("policy123"); + clientDetail.setLogoUri("https://example.com/logo.png"); + clientDetail.setRedirectUris("https://example.com/callback"); + clientDetail.setPublicKey("public-key-string"); + clientDetail.setClaims("claims-string"); + clientDetail.setAcrValues("acr-values-string"); + clientDetail.setStatus("active"); + clientDetail.setGrantTypes("grant-type-string"); + clientDetail.setClientAuthMethods("auth-methods-string"); + clientDetail.setCreatedBy("creator-user"); + clientDetail.setCreatedDateTime(LocalDateTime.now()); + clientDetail.setUpdatedBy("updater-user"); + clientDetail.setUpdatedDateTime(LocalDateTime.now()); + clientDetail.setIsDeleted(false); + clientDetailList.add(clientDetail); + when(clientDetailRepository.findAllByPartnerId(anyString())).thenReturn(clientDetailList); + + when(authPolicyRepository.findById(anyString())).thenReturn(Optional.empty()); + + ResponseWrapperV2> result = serviceImpl.getClients(); + + // Assert response is not null + assertNotNull(result); + assertNotNull(result.getErrors()); } + @Test + public void getClientsPolicyGroupNotExistsExceptionTest() { + io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = getMosipUserDto(); + AuthUserDetails authUserDetails = new AuthUserDetails(mosipUserDto, "123"); + SecurityContextHolder.setContext(securityContext); + when(authentication.getPrincipal()).thenReturn(authUserDetails); + when(securityContext.getAuthentication()).thenReturn(authentication); + + List partnerList = new ArrayList<>(); + Partner partner = new Partner(); + partner.setId("123"); + partner.setPartnerTypeCode("Auth_Partner"); + partner.setPolicyGroupId("abc"); + partner.setApprovalStatus("approved"); + partnerList.add(partner); + when(partnerServiceRepository.findByUserId(anyString())).thenReturn(partnerList); + + List clientDetailList = new ArrayList<>(); + ClientDetail clientDetail = new ClientDetail(); + clientDetail.setId("id123"); + clientDetail.setName("Sample Client"); + clientDetail.setRpId("rp123"); + clientDetail.setPolicyId("policy123"); + clientDetail.setLogoUri("https://example.com/logo.png"); + clientDetail.setRedirectUris("https://example.com/callback"); + clientDetail.setPublicKey("public-key-string"); + clientDetail.setClaims("claims-string"); + clientDetail.setAcrValues("acr-values-string"); + clientDetail.setStatus("active"); + clientDetail.setGrantTypes("grant-type-string"); + clientDetail.setClientAuthMethods("auth-methods-string"); + clientDetail.setCreatedBy("creator-user"); + clientDetail.setCreatedDateTime(LocalDateTime.now()); + clientDetail.setUpdatedBy("updater-user"); + clientDetail.setUpdatedDateTime(LocalDateTime.now()); + clientDetail.setIsDeleted(false); + clientDetailList.add(clientDetail); + when(clientDetailRepository.findAllByPartnerId(anyString())).thenReturn(clientDetailList); + + AuthPolicy authPolicy = new AuthPolicy(); + authPolicy.setName("abc"); + when(authPolicyRepository.findById(anyString())).thenReturn(Optional.of(authPolicy)); + + ResponseWrapperV2> result = serviceImpl.getClients(); + + // Assert response is not null + assertNotNull(result); + assertNotNull(result.getErrors()); + } + + @Test public void getPartnersClientsTest() throws Exception { io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = getMosipUserDto(); @@ -1325,8 +1523,11 @@ public void getPartnersClientsTest() throws Exception { filterDto.setPartnerId("abc"); filterDto.setStatus("ACTIVE"); filterDto.setOrgName("ABC"); - ResponseWrapperV2> responseWrapper = new ResponseWrapperV2<>(); - Page page = null; + Pageable pageable = PageRequest.of(pageNo, pageSize); + ClientSummaryEntity entity = new ClientSummaryEntity(); + entity.setClientId("123"); + Page page = new PageImpl<>(List.of(entity), pageable, 1); + when(clientSummaryRepository.getSummaryOfAllPartnerClients(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), any())).thenReturn(page); serviceImpl.getPartnersClients(sortFieldName, sortType, pageNo, pageSize, filterDto); } @@ -1344,7 +1545,10 @@ public void getPartnersClientsTestException() throws Exception { int pageNo = 0; int pageSize = 8; ResponseWrapperV2> responseWrapper = new ResponseWrapperV2<>(); - Page page = null; + Pageable pageable = PageRequest.of(pageNo, pageSize); + ClientSummaryEntity entity = new ClientSummaryEntity(); + entity.setClientId("123"); + Page page = new PageImpl<>(List.of(entity), pageable, 1); when(clientSummaryRepository.getSummaryOfAllPartnerClients(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), any())).thenReturn(page); serviceImpl.getPartnersClients(sortFieldName, sortType, pageNo, pageSize, null); } diff --git a/partner/partner-management-service/src/test/java/io/mosip/pms/test/partner/controller/PartnerServiceControllerTest.java b/partner/partner-management-service/src/test/java/io/mosip/pms/test/partner/controller/PartnerServiceControllerTest.java index 4663cb33ac..54465964e9 100644 --- a/partner/partner-management-service/src/test/java/io/mosip/pms/test/partner/controller/PartnerServiceControllerTest.java +++ b/partner/partner-management-service/src/test/java/io/mosip/pms/test/partner/controller/PartnerServiceControllerTest.java @@ -1,5 +1,8 @@ package io.mosip.pms.test.partner.controller; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -12,9 +15,8 @@ import java.util.List; import io.mosip.pms.common.request.dto.RequestWrapperV2; -import io.mosip.pms.common.response.dto.ResponseWrapper; import io.mosip.pms.common.response.dto.ResponseWrapperV2; -import io.mosip.pms.partner.dto.ApiKeyResponseDto; +import io.mosip.pms.partner.controller.PartnerServiceController; import io.mosip.pms.partner.dto.CertificateDto; import io.mosip.pms.partner.dto.PolicyDto; import io.mosip.pms.partner.dto.PartnerDtoV4; @@ -22,10 +24,9 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -33,10 +34,9 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -51,6 +51,8 @@ import io.mosip.pms.device.util.AuditUtil; import io.mosip.pms.partner.constant.PartnerServiceAuditEnum; import io.mosip.pms.partner.dto.PartnerPolicyMappingResponseDto; +import io.mosip.pms.partner.dto.PartnerDtoV4; +import io.mosip.pms.partner.dto.ApiKeyResponseDto; import io.mosip.pms.partner.manager.service.PartnerManagerService; import io.mosip.pms.partner.request.dto.APIKeyGenerateRequestDto; import io.mosip.pms.partner.request.dto.AddContactRequestDto; @@ -65,6 +67,7 @@ import io.mosip.pms.partner.request.dto.PartnerRequest; import io.mosip.pms.partner.request.dto.PartnerSearchDto; import io.mosip.pms.partner.request.dto.PartnerUpdateRequest; +import io.mosip.pms.partner.request.dto.PartnerRequestDto; import io.mosip.pms.partner.response.dto.APIKeyGenerateResponseDto; import io.mosip.pms.partner.response.dto.APIkeyRequests; import io.mosip.pms.partner.response.dto.CACertificateResponseDto; @@ -79,39 +82,38 @@ @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -@EnableWebMvc public class PartnerServiceControllerTest { @Autowired private MockMvc mockMvc; - @Mock + @MockBean private PartnerService partnerService; - - @Mock - PartnerManagerService partnerManagerService; - + + @MockBean + private PartnerManagerService partnerManagerService; + + @MockBean + private AuditUtil auditUtil; + + @Autowired + private PartnerServiceController partnerServiceController; + @Autowired private ObjectMapper objectMapper; - - @Autowired - @Qualifier("selfTokenRestTemplate") - private RestTemplate restTemplate; - - @MockBean - AuditUtil auditUtil; - - @Before - public void setup() { - Mockito.doNothing().when(auditUtil).setAuditRequestDto(Mockito.any(PartnerServiceAuditEnum.class)); - } + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + doNothing().when(auditUtil).setAuditRequestDto(any(PartnerServiceAuditEnum.class), anyString(), anyString()); + } @Test @WithMockUser(roles = {"PARTNER"}) public void partnerSelfRegistrationTest() throws Exception { PartnerResponse response = new PartnerResponse(); - Mockito.when(partnerService.savePartner(Mockito.any())).thenReturn(response); + when(partnerService.savePartner(any())).thenReturn(response); RequestWrapper request = createRequest(); mockMvc.perform(post("/partners").contentType(MediaType.APPLICATION_JSON_VALUE) @@ -121,7 +123,7 @@ public void partnerSelfRegistrationTest() throws Exception { @Test @WithMockUser(roles = {"PARTNER"}) public void addContactsTest() throws Exception { - Mockito.when(partnerService.createAndUpdateContactDetails(Mockito.any(),Mockito.any())).thenReturn(new String()); + when(partnerService.createAndUpdateContactDetails(any(), any())).thenReturn(new String()); mockMvc.perform(post("/partners/12345/contact/add").contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(addContactRequestWrapper()))).andExpect(status().isOk()); } @@ -130,7 +132,7 @@ public void addContactsTest() throws Exception { @WithMockUser(roles = {"PARTNERMANAGER"}) public void uploadCACertificateTest() throws Exception{ CACertificateResponseDto response = new CACertificateResponseDto(); - Mockito.when(partnerService.uploadCACertificate(cACertificateRequest())).thenReturn(response); + when(partnerService.uploadCACertificate(cACertificateRequest())).thenReturn(response); mockMvc.perform(post("/partners/certificate/ca/upload").contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(createCACertificateRequest()))).andExpect(status().isOk()); } @@ -139,7 +141,7 @@ public void uploadCACertificateTest() throws Exception{ @WithMockUser(roles = {"PARTNER"}) public void uploadPartnerCertificateTest() throws Exception{ PartnerCertificateResponseDto response = new PartnerCertificateResponseDto(); - Mockito.when(partnerService.uploadPartnerCertificate(Mockito.any())).thenReturn(response); + when(partnerService.uploadPartnerCertificate(any())).thenReturn(response); mockMvc.perform(post("/partners/certificate/upload").contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(partnerCertificateRequest()))).andExpect(status().isOk()); } @@ -147,7 +149,7 @@ public void uploadPartnerCertificateTest() throws Exception{ @Test @WithMockUser(roles = {"PARTNER"}) public void addBiometricExtractorsTest() throws JsonProcessingException, Exception { - Mockito.when(partnerService.addBiometricExtractors("123456", "12345", getExtractorsInput())).thenReturn(new String()); + when(partnerService.addBiometricExtractors("123456", "12345", getExtractorsInput())).thenReturn(new String()); mockMvc.perform(post("/partners/123456/bioextractors/12345").contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(createAddBiometricExtractorRequest()))).andExpect(status().isOk()); } @@ -156,21 +158,21 @@ public void addBiometricExtractorsTest() throws JsonProcessingException, Excepti @WithMockUser(roles = {"PARTNER"}) public void getCredentialTypePolicyTest() throws Exception{ PartnerCredentialTypePolicyDto response = new PartnerCredentialTypePolicyDto(); - Mockito.when(partnerService.getPartnerCredentialTypePolicy(Mockito.anyString(),Mockito.anyString())).thenReturn(response); + when(partnerService.getPartnerCredentialTypePolicy(anyString(), anyString())).thenReturn(response); mockMvc.perform(MockMvcRequestBuilders.get("/partners/12345/credentialtype/12345/policies")).andExpect(MockMvcResultMatchers.status().isOk()); } @Test @WithMockUser(roles = {"PARTNER"}) public void mapPolicyToCredentialTypeTest() throws Exception{ - Mockito.when(partnerService.mapPartnerPolicyCredentialType(Mockito.anyString(),Mockito.anyString(),Mockito.anyString())).thenReturn(new String()); + when(partnerService.mapPartnerPolicyCredentialType(anyString(), anyString(), anyString())).thenReturn(new String()); mockMvc.perform(MockMvcRequestBuilders.post("/partners/12345/credentialtype/12345/policies/12345")).andExpect(MockMvcResultMatchers.status().isOk()); } @Test @WithMockUser(roles = {"PARTNER"}) public void getBiometricExtractorsTest() throws JsonProcessingException, Exception { - Mockito.when(partnerService.getBiometricExtractors("123456", "12345")).thenReturn(new ExtractorsDto()); + when(partnerService.getBiometricExtractors("123456", "12345")).thenReturn(new ExtractorsDto()); mockMvc.perform(MockMvcRequestBuilders.get("/partners/123456/bioextractors/12345")).andExpect(status().isOk()); } @@ -178,7 +180,7 @@ public void getBiometricExtractorsTest() throws JsonProcessingException, Excepti @WithMockUser(roles = {"PARTNER"}) public void retrievePartnerCertificateTest() throws Exception { PartnerCertDownloadResponeDto partnerCertDownloadResponeDto = new PartnerCertDownloadResponeDto(); - Mockito.when(partnerService.getPartnerCertificate(Mockito.any())).thenReturn(partnerCertDownloadResponeDto); + when(partnerService.getPartnerCertificate(any())).thenReturn(partnerCertDownloadResponeDto); mockMvc.perform(MockMvcRequestBuilders.get("/partners/12345/certificate")).andExpect(MockMvcResultMatchers.status().isOk()); } @@ -187,7 +189,7 @@ public void retrievePartnerCertificateTest() throws Exception { @WithMockUser(roles = {"PARTNER"}) public void retrievePartnerDetailsTest() throws Exception { RetrievePartnerDetailsResponse response = new RetrievePartnerDetailsResponse(); - Mockito.when(partnerService.getPartnerDetails("12345")).thenReturn(response); + when(partnerService.getPartnerDetails("12345")).thenReturn(response); mockMvc.perform(MockMvcRequestBuilders.get("/partners/12345")).andExpect(MockMvcResultMatchers.status().isOk()); } @@ -199,7 +201,7 @@ public void updatePartnerDetailsTest() throws Exception{ response.setPartnerId(partnerId); response.setStatus("true"); - Mockito.when(partnerService.updatePartnerDetail(Mockito.any(), Mockito.any())).thenReturn(response); + when(partnerService.updatePartnerDetail(any(), any())).thenReturn(response); RequestWrapper request = updateRequest(); mockMvc.perform(put("/partners/12345").contentType(MediaType.APPLICATION_JSON_VALUE) @@ -222,7 +224,7 @@ public void retrieveAllApiKeyRequestsSubmittedByPartnerTillDateTest()throws Exce List list_aPIkeyRequests = new ArrayList<>(); list_aPIkeyRequests.add(aPIkeyRequests); - Mockito.when(partnerService.retrieveAllApiKeyRequestsSubmittedByPartner(partnerId)).thenReturn(list_aPIkeyRequests); + when(partnerService.retrieveAllApiKeyRequestsSubmittedByPartner(partnerId)).thenReturn(list_aPIkeyRequests); mockMvc.perform(MockMvcRequestBuilders.get("/partners/12345/apikey/request")).andExpect(MockMvcResultMatchers.status().isOk()); } @@ -277,7 +279,7 @@ public void apikeyRequetsFilterValuesTest() throws Exception{ @Test @WithMockUser(roles = {"PARTNER"}) public void updatePolicyGroup() throws Exception{ - Mockito.when(partnerService.updatePolicyGroup(Mockito.any(),Mockito.any())).thenReturn("Success"); + when(partnerService.updatePolicyGroup(any(), any())).thenReturn("Success"); mockMvc.perform(put("/partners/1234/policygroup/5678")).andExpect(MockMvcResultMatchers.status().isOk()); } @@ -288,32 +290,43 @@ public void isEmailExists() throws Exception{ RequestWrapper request = new RequestWrapper<>(); EmailVerificationRequestDto requestDto = new EmailVerificationRequestDto(); request.setRequest(requestDto); - Mockito.when(partnerService.isPartnerExistsWithEmail(request.getRequest().getEmailId())).thenReturn(response); + when(partnerService.isPartnerExistsWithEmail(request.getRequest().getEmailId())).thenReturn(response); mockMvc.perform(put("/partners/email/verify").contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(request))).andExpect(MockMvcResultMatchers.status().isOk()); } - @Test - @WithMockUser(roles = {"PARTNER"}) - public void mapPolicyToPartner() throws Exception{ - PartnerPolicyMappingResponseDto response = new PartnerPolicyMappingResponseDto(); - RequestWrapper request = new RequestWrapper<>(); - PartnerPolicyMappingRequest requestDto = new PartnerPolicyMappingRequest(); - request.setRequest(requestDto); - Mockito.when(partnerService.requestForPolicyMapping(request.getRequest(),"1234")).thenReturn(response); - mockMvc.perform(post("/partners/1234/policy/map").contentType(MediaType.APPLICATION_JSON_VALUE) - .content(objectMapper.writeValueAsString(request))).andExpect(MockMvcResultMatchers.status().isOk()); + @Test + @WithMockUser(roles = {"AUTH_PARTNER"}) + public void mapPolicyToPartner() throws Exception { + PartnerPolicyMappingResponseDto response = new PartnerPolicyMappingResponseDto(); + RequestWrapper request = new RequestWrapper<>(); + PartnerPolicyMappingRequest requestDto = new PartnerPolicyMappingRequest(); + requestDto.setPolicyName("abc"); + requestDto.setUseCaseDescription("abc"); + request.setRequest(requestDto); + + when(partnerService.requestForPolicyMapping(any(PartnerPolicyMappingRequest.class), eq("1234"))) + .thenReturn(response); + + MvcResult result = mockMvc.perform(post("/partners/1234/policy/map") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isOk()) + .andReturn(); + + String responseContent = result.getResponse().getContentAsString(); } - @Test - - @WithMockUser(roles = {"PARTNER_ADMIN"}) + @Test + @WithMockUser(roles = {"AUTH_PARTNER"}) public void generateAPIKey() throws Exception{ APIKeyGenerateResponseDto response = new APIKeyGenerateResponseDto(); RequestWrapper request = new RequestWrapper<>(); APIKeyGenerateRequestDto requestDto = new APIKeyGenerateRequestDto(); + requestDto.setPolicyName("abc"); + requestDto.setLabel("123"); request.setRequest(requestDto); - Mockito.when(partnerManagerService.generateAPIKey("1234",requestDto)).thenReturn(response); + when(partnerManagerService.generateAPIKey("1234",requestDto)).thenReturn(response); mockMvc.perform(MockMvcRequestBuilders.patch("/partners/1234/generate/apikey").contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(request))).andExpect(MockMvcResultMatchers.status().isOk()); } @@ -325,7 +338,7 @@ public void getPartnerCertificateTest() throws Exception{ RequestWrapper requestWrapper = new RequestWrapper<>(); PartnerCertDownloadRequestDto requestDto = new PartnerCertDownloadRequestDto(); requestWrapper.setRequest(requestDto); - Mockito.when(partnerService.getPartnerCertificate(requestDto)).thenReturn(certDownloadResponeDto); + when(partnerService.getPartnerCertificate(requestDto)).thenReturn(certDownloadResponeDto); mockMvc.perform(MockMvcRequestBuilders.get("/partners/1234/certificate")).andExpect(MockMvcResultMatchers.status().isOk()); } @@ -338,7 +351,7 @@ public void getPartnerCertificateDataTest() throws Exception{ PartnerCertDownloadRequestDto requestDto = new PartnerCertDownloadRequestDto(); requestWrapper.setRequest(requestDto); responseWrapper.setResponse(originalCertDownloadResponseDto); - Mockito.when(partnerService.getPartnerCertificateData(requestDto)).thenReturn(responseWrapper); + when(partnerService.getPartnerCertificateData(requestDto)).thenReturn(responseWrapper); mockMvc.perform(MockMvcRequestBuilders.get("/partners/1234/certificate-data")).andExpect(MockMvcResultMatchers.status().isOk()); } @@ -580,7 +593,7 @@ private AddContactRequestDto addContactRequestDto() { } @Test - @WithMockUser(roles = {"PARTNER"}) + @WithMockUser(roles = {"AUTH_PARTNER"}) public void getPolicyRequestsTest() throws Exception { ResponseWrapperV2> responseWrapper = new ResponseWrapperV2<>(); PolicyDto policyDto = new PolicyDto(); @@ -591,11 +604,12 @@ public void getPolicyRequestsTest() throws Exception { List policyDtoList = new ArrayList<>(); policyDtoList.add(policyDto); responseWrapper.setResponse(policyDtoList); - Mockito.when(partnerService.getPolicyRequests()).thenReturn(responseWrapper); + when(partnerService.getPolicyRequests()).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/partners//policy-requests")).andExpect(MockMvcResultMatchers.status().isOk()); } @Test - @WithMockUser(roles = {"PARTNER"}) + @WithMockUser(roles = {"AUTH_PARTNER"}) public void getPartnerCertificatesDetailsTest() throws Exception { ResponseWrapperV2> responseWrapper = new ResponseWrapperV2<>(); @@ -608,12 +622,12 @@ public void getPartnerCertificatesDetailsTest() throws Exception { certificateDtoList.add(certificateDto); responseWrapper.setResponse(certificateDtoList); - Mockito.when(partnerService.getPartnerCertificatesDetails()).thenReturn(responseWrapper); + when(partnerService.getPartnerCertificatesDetails()).thenReturn(responseWrapper); mockMvc.perform(MockMvcRequestBuilders.get("/partners/partner-certificates-details")).andExpect(MockMvcResultMatchers.status().isOk()); } @Test - @WithMockUser(roles = {"PARTNER"}) + @WithMockUser(roles = {"AUTH_PARTNER"}) public void getAuthPartnerApiKeysTest() throws Exception { ResponseWrapperV2> responseWrapper = new ResponseWrapperV2<>(); ApiKeyResponseDto apiKeyResponseDto = new ApiKeyResponseDto(); @@ -628,7 +642,7 @@ public void getAuthPartnerApiKeysTest() throws Exception { List apiKeyResponseDtoList = new ArrayList<>(); apiKeyResponseDtoList.add(apiKeyResponseDto); responseWrapper.setResponse(apiKeyResponseDtoList); - Mockito.when(partnerService.getAuthPartnerApiKeys()).thenReturn(responseWrapper); + when(partnerService.getAuthPartnerApiKeys()).thenReturn(responseWrapper); mockMvc.perform(MockMvcRequestBuilders.get("/partners/auth-partner-api-keys")).andExpect(MockMvcResultMatchers.status().isOk()); } @@ -670,5 +684,46 @@ public void getPartnersV4Test2() throws Exception { .param("partnerType", "Device_Provider")) .andExpect(status().isOk()); } + @Test + @WithMockUser(roles = {"AUTH_PARTNER"}) + public void testPartnerRegistration() throws Exception { + PartnerRequestDto partnerRequestDto = new PartnerRequestDto(); + partnerRequestDto.setPartnerId("12345"); + partnerRequestDto.setOrganizationName("abc"); + partnerRequestDto.setAddress("abc"); + partnerRequestDto.setContactNumber("283282822"); + partnerRequestDto.setEmailId("abc@email.com"); + partnerRequestDto.setPartnerType("AUTH_PARTNER"); + + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequest(partnerRequestDto); + + PartnerResponse partnerResponse = new PartnerResponse(); + partnerResponse.setPartnerId("12345"); + + Mockito.when(partnerService.registerPartner(partnerRequestDto)).thenReturn(partnerResponse); + + mockMvc.perform(post("/partners/v2") + .contentType(MediaType.APPLICATION_JSON) + .content(new ObjectMapper().writeValueAsString(requestWrapper))) + .andExpect(status().isOk()).andReturn(); + } + + @Test + @WithMockUser(roles = {"AUTH_PARTNER"}) + public void testGetPartnersV4() throws Exception { + List partnerDtoV4List = new ArrayList<>(); + PartnerDtoV4 partnerDto = new PartnerDtoV4(); + partnerDto.setPartnerId("123"); + partnerDtoV4List.add(partnerDto); + + ResponseWrapperV2> responseWrapper = new ResponseWrapperV2<>(); + responseWrapper.setResponse(partnerDtoV4List); + + Mockito.when(partnerService.getPartnersV4("approved", true, "typeA")).thenReturn(responseWrapper); + + mockMvc.perform(MockMvcRequestBuilders.get("/partners/v4?status=approved")).andExpect(MockMvcResultMatchers.status().isOk()); + + } } \ No newline at end of file