Skip to content

Commit

Permalink
Merge pull request #586 from tw-mosip/injiweb-1429-add-test-cases
Browse files Browse the repository at this point in the history
[Injiweb 1429] add test cases for newly added code
  • Loading branch information
Gurpreet41082 authored Feb 11, 2025
2 parents ab7c806 + 21b2470 commit 3cd9ae0
Show file tree
Hide file tree
Showing 14 changed files with 474 additions and 51 deletions.
3 changes: 1 addition & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@

<!-- test -->
<junit.version>4.13.1</junit.version>
<mockito.version>2.23.4</mockito.version>

<mockito.version>5.15.2</mockito.version>
<!-- logger -->
<logback.version>1.2.3</logback.version>

Expand Down
22 changes: 12 additions & 10 deletions src/main/java/io/mosip/mimoto/controller/IdpController.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,19 @@ public ResponseEntity<ResponseWrapper<BindingOtpResponseDto>> otpRequest(@Valid
log.debug("Received binding-otp request : " + JsonUtils.javaObjectToJsonString(requestDTO));
requestValidator.validateInputRequest(result);
requestValidator.validateNotificationChannel(requestDTO.getRequest().getOtpChannels());
ResponseWrapper<BindingOtpResponseDto> response = new ResponseWrapper<>();
ResponseWrapper<BindingOtpResponseDto> responseWrapper = new ResponseWrapper<>();
try {
response = (ResponseWrapper<BindingOtpResponseDto>) restClientService.postApi(ApiName.BINDING_OTP, requestDTO, ResponseWrapper.class, USE_BEARER_TOKEN);
if (response == null)
ResponseWrapper<BindingOtpResponseDto> internalResponse = (ResponseWrapper<BindingOtpResponseDto>) restClientService.postApi(ApiName.BINDING_OTP, requestDTO, ResponseWrapper.class, USE_BEARER_TOKEN);
if (internalResponse == null)
throw new IdpException();
return ResponseEntity.status(HttpStatus.OK).body(response);
return ResponseEntity.status(HttpStatus.OK).body(internalResponse);
} catch (Exception e) {
log.error("Wallet binding otp error occurred.", e);
List<ErrorDTO> errors = Utilities.getErrors(PlatformErrorMessages.MIMOTO_OTP_BINDING_EXCEPTION.getCode(), e.getMessage());
response.setErrors(errors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
log.error("Wallet binding otp error occurred." + e);
String[] errorObj = Utilities.handleExceptionWithErrorCode(e, PlatformErrorMessages.MIMOTO_OTP_BINDING_EXCEPTION.getCode());
List<ErrorDTO> errors = Utilities.getErrors(errorObj[0], errorObj[1]);
responseWrapper.setResponse(null);
responseWrapper.setErrors(errors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(responseWrapper);
}

}
Expand Down Expand Up @@ -108,7 +110,7 @@ public ResponseEntity<ResponseWrapper<WalletBindingResponseDto>> request(@Reques
return ResponseEntity.status(HttpStatus.OK).body(responseWrapper);
} catch (Exception e) {
log.error("Wallet binding error occured for tranaction id " + requestDTO.getRequest().getIndividualId(), e);
String[] errorObj = Utilities.handleExceptionWithErrorCode(e);
String[] errorObj = Utilities.handleExceptionWithErrorCode(e, PlatformErrorMessages.MIMOTO_WALLET_BINDING_EXCEPTION.getCode());
List<ErrorDTO> errors = Utilities.getErrors(errorObj[0], errorObj[1]);
responseWrapper.setResponse(null);
responseWrapper.setErrors(errors);
Expand All @@ -129,7 +131,7 @@ public ResponseEntity<Object> getToken(@RequestParam Map<String, String> params,
return ResponseEntity.status(HttpStatus.OK).body(response);
} catch (Exception ex) {
log.error("Exception Occurred while Invoking the Token Endpoint : ", ex);
String[] errorObj = Utilities.handleExceptionWithErrorCode(ex);
String[] errorObj = Utilities.handleExceptionWithErrorCode(ex, PlatformErrorMessages.MIMOTO_FETCHING_TOKEN_EXCEPTION.getCode());
List<ErrorDTO> errors = Utilities.getErrors(errorObj[0], errorObj[1]);
responseWrapper.setErrors(errors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(responseWrapper);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@
import java.io.IOException;
import java.util.List;

import static io.mosip.mimoto.exception.PlatformErrorMessages.API_NOT_ACCESSIBLE_EXCEPTION;
import static io.mosip.mimoto.exception.PlatformErrorMessages.INVALID_ISSUER_ID_EXCEPTION;
import static io.mosip.mimoto.exception.PlatformErrorMessages.*;

@RestController
@Slf4j
Expand Down Expand Up @@ -96,7 +95,7 @@ public ResponseEntity<ResponseWrapper<IssuerDTO>> getIssuerConfig(@PathVariable(
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseWrapper);
} catch (Exception exception) {
log.error("Exception occurred while fetching issuers ", exception);
String[] errorObj = Utilities.handleExceptionWithErrorCode(exception);
String[] errorObj = Utilities.handleExceptionWithErrorCode(exception, INVALID_ISSUER_ID_EXCEPTION.getCode());
List<ErrorDTO> errors = Utilities.getErrors(errorObj[0], errorObj[1]);
responseWrapper.setResponse(null);
responseWrapper.setErrors(errors);
Expand All @@ -114,7 +113,7 @@ public ResponseEntity<ResponseWrapper<CredentialIssuerConfigurationResponse>> ge
return ResponseEntity.status(HttpStatus.OK).body(responseWrapper);
} catch (Exception exception) {
log.error("Exception occurred while fetching issuers configurations - " + exception);
String[] errorObj = Utilities.handleExceptionWithErrorCode(exception);
String[] errorObj = Utilities.handleExceptionWithErrorCode(exception, INVALID_ISSUER_ID_CONFIGURATION.getCode());
List<ErrorDTO> errors = Utilities.getErrors(errorObj[0], errorObj[1]);
responseWrapper.setResponse(null);
responseWrapper.setErrors(errors);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,15 @@ public enum PlatformErrorMessages {
MIMOTO_IDP_OTP_EXCEPTION(PlatformConstants.PREFIX + "033", "IDP Otp error occured"),
MIMOTO_IDP_GENERIC_EXCEPTION(PlatformConstants.PREFIX + "034", "Could not get response from server"),
INVALID_ISSUER_ID_EXCEPTION(PlatformConstants.PREFIX + "035", "Invalid issuer ID"),
INVALID_ISSUER_ID_CONFIGURATION(PlatformConstants.PREFIX + "035", "Exception occurred while fetching issuer configuration"),
INVALID_CREDENTIAL_TYPE_EXCEPTION(PlatformConstants.PREFIX + "036", "Invalid Credential Type Id"),
MIMOTO_ISSUER_ONBOARDING_EXCEPTION(PlatformConstants.PREFIX + "037", "Issuers Onboarding exception occurred "),
INVALID_VERIFIER_ID_EXCEPTION(PlatformConstants.PREFIX + "038", "Invalid Verifier ClientId"),
INVALID_VERIFIER_REDIRECT_URI_EXCEPTION(PlatformConstants.PREFIX + "039", "Invalid Redirect Uri"),
INVALID_CREDENTIAL_RESOURCE_URI_EXCEPTION(PlatformConstants.PREFIX + "040", "The Credential Resource is Invalid"),
INVALID_CREDENTIAL_ISSUER_WELLKNOWN_RESPONSE_EXCEPTION(PlatformConstants.PREFIX + "041", "Invalid Wellknown from Issuer"),
INVALID_AUTHORIZATION_SERVER_WELLKNOWN_RESPONSE_EXCEPTION(PlatformConstants.PREFIX + "042", "Invalid Authorization Server well-known from server:");

INVALID_AUTHORIZATION_SERVER_WELLKNOWN_RESPONSE_EXCEPTION(PlatformConstants.PREFIX + "042", "Invalid Authorization Server well-known from server:"),
MIMOTO_FETCHING_TOKEN_EXCEPTION(PlatformConstants.PREFIX + "043", "Exception occurred when fetching the Token");

/** The error message. */
private final String errorMessage;
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/io/mosip/mimoto/util/Utilities.java
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,9 @@ public String getCredentialSupportedTemplateString(String issuerId, String crede
String specificCredentialPDFTemplate = getJson(configServerFileStorageURL, templateFileName);
return !StringUtils.isEmpty(specificCredentialPDFTemplate)? specificCredentialPDFTemplate : getJson(configServerFileStorageURL, credentialTemplatePath);
}
public static String[] handleExceptionWithErrorCode(Exception exception) {
public static String[] handleExceptionWithErrorCode(Exception exception, String flowErrorCode) {
String errorMessage = exception.getMessage();
String errorCode = PlatformErrorMessages.MIMOTO_WALLET_BINDING_EXCEPTION.getCode();
String errorCode = flowErrorCode;

if(errorMessage.contains(DELIMITER)){
String[] errorSections = errorMessage.split(DELIMITER);
Expand Down
72 changes: 69 additions & 3 deletions src/test/java/io/mosip/mimoto/controller/IdpControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import io.mosip.kernel.core.util.JsonUtils;
import io.mosip.mimoto.core.http.ResponseWrapper;
import io.mosip.mimoto.dto.mimoto.*;
import io.mosip.mimoto.exception.BaseUncheckedException;
import io.mosip.mimoto.exception.*;
import io.mosip.mimoto.service.RestClientService;
import io.mosip.mimoto.service.impl.CredentialServiceImpl;
import io.mosip.mimoto.service.impl.IdpServiceImpl;
Expand All @@ -13,6 +13,9 @@
import io.mosip.mimoto.util.JoseUtil;
import io.mosip.mimoto.util.RequestValidator;
import io.mosip.mimoto.util.RestApiClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
Expand All @@ -25,7 +28,12 @@
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import static io.mosip.mimoto.util.TestUtilities.*;

import java.util.Arrays;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
Expand Down Expand Up @@ -70,12 +78,19 @@ public void otpRequestTest() throws Exception {
ResponseWrapper<BindingOtpResponseDto> response = new ResponseWrapper<>();

Mockito.when(restClientService.postApi(Mockito.any(),
Mockito.any(), Mockito.any(), Mockito.anyBoolean())).thenReturn(response).thenThrow(new BaseUncheckedException("Exception"));
Mockito.any(), Mockito.any(), Mockito.anyBoolean())).thenReturn(response).thenReturn(null).thenThrow(new BaseUncheckedException("Exception"));

this.mockMvc.perform(post("/binding-otp").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(JsonUtils.javaObjectToJsonString(requestDTO)))
.andExpect(status().isOk());


this.mockMvc.perform(post("/binding-otp").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(JsonUtils.javaObjectToJsonString(requestDTO)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0].errorCode").value("RESIDENT-APP-034"))
.andExpect(jsonPath("$.errors[0].errorMessage").value("Could not get response from server"));

this.mockMvc.perform(post("/binding-otp").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(JsonUtils.javaObjectToJsonString(requestDTO)))
.andExpect(status().isBadRequest());
Expand All @@ -93,15 +108,66 @@ public void walletBindingTest() throws Exception {
ResponseWrapper<WalletBindingResponseDto> response = new ResponseWrapper<>();

Mockito.when(restClientService.postApi(Mockito.any(),
Mockito.any(), Mockito.any(), Mockito.anyBoolean())).thenReturn(response).thenThrow(new BaseUncheckedException("Exception"));
Mockito.any(), Mockito.any(), Mockito.anyBoolean())).thenReturn(response).thenReturn(null).thenThrow(new BaseUncheckedException("Exception"));

this.mockMvc.perform(post("/wallet-binding").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(JsonUtils.javaObjectToJsonString(requestDTO)))
.andExpect(status().isOk());

this.mockMvc.perform(post("/wallet-binding").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(JsonUtils.javaObjectToJsonString(requestDTO)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0].errorCode").value("RESIDENT-APP-034"))
.andExpect(jsonPath("$.errors[0].errorMessage").value("Could not get response from server"));

this.mockMvc.perform(post("/wallet-binding").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(JsonUtils.javaObjectToJsonString(requestDTO)))
.andExpect(status().isBadRequest());
}

@Test
public void shouldReturnTokenResponseForValidIssuerAndParams() throws Exception {
String issuer = "test-issuer";
Mockito.when(credentialService.getTokenResponse(Mockito.anyMap(), Mockito.eq(issuer))).thenReturn(getTokenResponseDTO());

mockMvc.perform(post("/get-token/{issuer}", issuer)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.content(EntityUtils.toString(new UrlEncodedFormEntity(Arrays.asList(
new BasicNameValuePair("grant_type", "authorization_code"),
new BasicNameValuePair("code", "test-code"),
new BasicNameValuePair("redirect_uri", "test-redirect_uri"),
new BasicNameValuePair("code_verifier", "test-code_verifier"),
new BasicNameValuePair("issuer", issuer),
new BasicNameValuePair("vcStorageExpiryLimitInTimes", "3"),
new BasicNameValuePair("credential", "test-credential"),
new BasicNameValuePair("locale", "test-locale")
)))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").value("test-id-token"))
.andExpect(jsonPath("$.access_token").value("test-accesstoken"))
.andExpect(jsonPath("$.expires_in").value(12345))
.andExpect(jsonPath("$.scope").value("test-scope"))
.andExpect(jsonPath("$.token_type").value("test-token-type"));
}

@Test
public void shouldReturnBadRequestWithErrorIfTokenResponseIsNull() throws Exception {
String issuer = "test-issuer";
Mockito.when(credentialService.getTokenResponse(Mockito.anyMap(), Mockito.eq(issuer)))
.thenThrow(new IdpException("Exception occurred while performing the authorization"));

mockMvc.perform(post("/get-token/{issuer}", issuer)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("grant_type", "authorization_code")
.param("code", "test-code")
.param("redirect_uri", "test-redirect_uri")
.param("code_verifier", "test-code_verifier")
.param("issuer", issuer)
.param("vcStorageExpiryLimitInTimes", "3")
.param("credential", "test-credential")
.param("locale", "test-locale"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0].errorCode").value("RESIDENT-APP-034"))
.andExpect(jsonPath("$.errors[0].errorMessage").value("Exception occurred while performing the authorization"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public void getIssuerDetailsTestForInvalidIssuerId() throws Exception {
public void getIssuerWellknownTest() throws Exception {
String issuerId = "issuer1";
String expectedCredentialIssuerWellknownResponse = getExpectedWellKnownJson();
CredentialIssuerConfigurationResponse expectedCredentialIssuerConfigurationResponse = getCredentialIssuerConfigurationResponseDto(issuerId, Map.of("CredentialType1", getCredentialSupportedResponse("CredentialType1")), List.of());
CredentialIssuerConfigurationResponse expectedCredentialIssuerConfigurationResponse = getCredentialIssuerConfigurationResponseDto(issuerId, "CredentialType1", List.of());
Mockito.when(issuersService.getIssuerConfiguration(issuerId)).thenReturn(expectedCredentialIssuerConfigurationResponse);

String actualResponse = mockMvc.perform(get("/issuers/" + issuerId + "/well-known-proxy").accept(MediaType.APPLICATION_JSON_VALUE))
Expand All @@ -206,11 +206,7 @@ public void getIssuerConfigurationTest() throws Exception {
expectedJsonString = expectedJsonString.substring(1);
}
String finalExpectedJsonString = expectedJsonString;
CredentialIssuerConfigurationResponse expectedResponse = getCredentialIssuerConfigurationResponseDto(
issuerId,
Map.of("CredentialType1", getCredentialSupportedResponse("Credential1")),
List.of()
);
CredentialIssuerConfigurationResponse expectedResponse = getCredentialIssuerConfigurationResponseDto(issuerId, "CredentialType1", List.of());
Mockito.when(issuersService.getIssuerConfiguration(issuerId)).thenReturn(expectedResponse);

mockMvc.perform(get("/issuers/" + issuerId + "/configuration")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.mosip.mimoto.dto.openid.VerifierDTO;
import io.mosip.mimoto.dto.openid.VerifiersDTO;
import io.mosip.mimoto.exception.ApiNotAccessibleException;
import io.mosip.mimoto.service.impl.VerifierServiceImpl;
import org.hamcrest.Matchers;
import org.junit.Test;
Expand Down Expand Up @@ -59,4 +60,15 @@ public void getAllTrustedVerifiers() throws Exception {
)
)));
}

@Test
public void shouldReturnEmptyResponseIfAnyErrorOccurredWhileFetchingVerifiersList() throws Exception {
Mockito.when(verifierService.getTrustedVerifiers())
.thenThrow(new ApiNotAccessibleException());

mockMvc.perform(get("/verifiers").accept(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.response.verifiers").isArray())
.andExpect(jsonPath("$.response.verifiers").isEmpty());
}
}
Loading

0 comments on commit 3cd9ae0

Please sign in to comment.