Skip to content

Commit

Permalink
Merge pull request #318 from thisisharshit/1.2.0-rc2
Browse files Browse the repository at this point in the history
Automated and added testscript for notification API
  • Loading branch information
Sohandey authored Jan 27, 2022
2 parents 0404bfa + 08fb3ad commit 32e32d3
Show file tree
Hide file tree
Showing 11 changed files with 458 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
import io.mosip.kernel.util.Translator;
import io.mosip.service.BaseTestCase;
import io.mosip.testrunner.MosipTestRunner;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;


Expand Down Expand Up @@ -430,6 +431,63 @@ protected Response postWithFormDataAndFile(String url, String jsonInput, String
}
}

protected Response postWithMultipartFormDataAndFile(String url, String jsonInput, String cookieName, String role, String testCaseName,String idKeyName) {
Response response=null;

jsonInput = inputJsonKeyWordHandeler(jsonInput, testCaseName);
jsonInput = jsonInput.replace("\r\n", "");

HashMap<String, String> formParams = new HashMap<String, String>();
formParams.put("NotificationRequestDTO", jsonInput);
if(BaseTestCase.languageList.size()==1) formParams.put("langCode", BaseTestCase.languageList.get(0));
else if(BaseTestCase.languageList.size()==2) formParams.put("langCode", BaseTestCase.languageList.get(0)+","+BaseTestCase.languageList.get(1));
else formParams.put("langCode", BaseTestCase.languageList.get(0)+","+BaseTestCase.languageList.get(1)+","+BaseTestCase.languageList.get(2));
formParams.put("attachment", "");

/* String absolueFilePath = null; */
/*
* JSONArray josnArray = req.getJSONArray("files"); for (int index = 0; index <
* josnArray.length(); index++) { String csvFilePath = (String)
* josnArray.get(index); absolueFilePath = getResourcePath() + csvFilePath; if
* (formParams.get("category").equalsIgnoreCase("masterData")) { absolueFilePath
* = StringUtils.substringBefore(absolueFilePath, "FilesToUpload") +
* "FilesToUpload"; } }
*/
/*
* File file = new File(absolueFilePath); File[] listFiles = file.listFiles();
*/
/*
* for (File specificFile : listFiles) { if
* (formParams.get("operation").equalsIgnoreCase("insert") &&
* specificFile.getName().equals(formParams.get("tableName") + ".csv")) {
* specificFile=updateCSV(specificFile.getAbsolutePath(),"OLD",1,0); listFiles =
* new File[1]; listFiles[0] = specificFile; } else { if
* (formParams.get("operation").equalsIgnoreCase("update") &&
* specificFile.getName().equalsIgnoreCase("update" +
* formParams.get("tableName") + ".csv")) { listFiles = new File[1];
* listFiles[0] = specificFile; } } }
*/
token = kernelAuthLib.getTokenByRole(role);
logger.info("******Post request Json to EndPointUrl: " + url + " *******");
Reporter.log("<pre>" + ReportUtil.getTextAreaJsonMsgHtml(jsonInput) + "</pre>");

try {
response = RestClient.postWithMultipartFormDataAndFile(url, formParams,
MediaType.MULTIPART_FORM_DATA, token);
Reporter.log("<b><u>Actual Response Content: </u></b>(EndPointUrl: " + url + ") <pre>"
+ ReportUtil.getTextAreaJsonMsgHtml(response.asString()) + "</pre>");
if(testCaseName.toLowerCase().contains("_sid"))
{
writeAutoGeneratedId(response, idKeyName, testCaseName);
}

return response;
} catch (Exception e) {
logger.error("Exception " + e);
return response;
}
}

protected Response postWithFormDataAndMultipleFile(String url, String jsonInput, String cookieName, String role, String testCaseName,String idKeyName) {
Response response=null;
String inputJson = inputJsonKeyWordHandeler(jsonInput, testCaseName);
Expand Down Expand Up @@ -1091,7 +1149,13 @@ private String replaceIdWithAutogeneratedId(String jsonString, String idKey, Str
} catch (IOException e) {
logger.error("Exception while loading the autogenerated id: "+e.getMessage());
}
jsonString = jsonString.replace(keyToReplace, props.getProperty(keyForIdProperty));
if(keyForIdProperty.contains("time_slot_from")) {
String time = props.getProperty(keyForIdProperty);
if(time.compareTo("12:00")>=0) time+=" PM";
else time+=" AM";
jsonString = jsonString.replace(keyToReplace, time);
}else jsonString = jsonString.replace(keyToReplace, props.getProperty(keyForIdProperty));

jsonString =replaceIdWithAutogeneratedId(jsonString, idKey, autoGenIdFileName);
}
return jsonString;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.MediaType;

Expand Down Expand Up @@ -99,6 +100,40 @@ public static Response postWithFormDataAndFile(String url, HashMap<String, Strin
RESTCLIENT_LOGGER.info("REST-ASSURED: the response time is: " + postResponse.time());
return postResponse;
}
public static Response postWithMultipartFormDataAndFile(String url, HashMap<String, String> formParams, /*File[] filePath,*/
String contentHeader, String cookie){
RESTCLIENT_LOGGER.info("REST:ASSURED:Sending post request with file to" + url);
//RESTCLIENT_LOGGER.info("Name of the file is" + file.getName());
Cookie.Builder builder = new Cookie.Builder("Authorization", cookie);
/*
* Response postResponse =
* given().cookie(builder.build()).relaxedHTTPSValidation()
* .contentType(contentHeader) .multiPart("files", filePath[0])
* .multiPart("files", filePath[1]) .multiPart("tableName",
* formParams.get("tableName")) .multiPart("operation",
* formParams.get("operation")) .multiPart("category",
* formParams.get("category"))
* .expect().when().post(url).then().log().all().extract().response();
*/


RequestSpecification requestSpecification = given().cookie(builder.build()).relaxedHTTPSValidation()
.contentType(contentHeader);
/*
* for (int i=0;i<filePath.length;i++) { requestSpecification.multiPart("files",
* filePath[i]); }
*/
for(Map.Entry<String, String> entry: formParams.entrySet()) {
requestSpecification.multiPart(entry.getKey(), entry.getValue());
}

Response postResponse =requestSpecification.expect().when().post(url).then().log().all().extract().response();

// log then response
RESTCLIENT_LOGGER.info("REST-ASSURED: The response from request is: " + postResponse.asString());
RESTCLIENT_LOGGER.info("REST-ASSURED: the response time is: " + postResponse.time());
return postResponse;
}
public static Response postWithFormDataAndMultipleFile(String url, HashMap<String, String> formParams, File[] filePath,
String contentHeader, String cookie){
RESTCLIENT_LOGGER.info("REST:ASSURED:Sending post request with file to" + url);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package io.mosip.testscripts;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.testng.ITest;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.internal.BaseTestMethod;
import org.testng.internal.TestResult;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import io.mosip.admin.fw.util.AdminTestException;
import io.mosip.admin.fw.util.AdminTestUtil;
import io.mosip.admin.fw.util.TestCaseDTO;
import io.mosip.authentication.fw.dto.OutputValidationDto;
import io.mosip.authentication.fw.util.AuthenticationTestException;
import io.mosip.authentication.fw.util.OutputValidationUtil;
import io.mosip.authentication.fw.util.ReportUtil;
import io.mosip.service.BaseTestCase;
import io.restassured.response.Response;

public class PostWithFormDataAndFileForNotificationAPI extends AdminTestUtil implements ITest {
private static final Logger logger = Logger.getLogger(PostWithFormDataAndFileForNotificationAPI.class);
protected String testCaseName = "";
String idKeyName = null;
public Response response = null;
/**
* get current testcaseName
*/
@Override
public String getTestName() {
return testCaseName;
}

/**
* Data provider class provides test case list
*
* @return object of data provider
*/
@DataProvider(name = "testcaselist")
public Object[] getTestCaseList(ITestContext context) {
String ymlFile = context.getCurrentXmlTest().getLocalParameters().get("ymlFile");
idKeyName = context.getCurrentXmlTest().getLocalParameters().get("idKeyName");
logger.info("Started executing yml: "+ymlFile);
return getYmlTestData(ymlFile);
}

/**
* Test method for OTP Generation execution
*
* @param objTestParameters
* @param testScenario
* @param testcaseName
* @throws AuthenticationTestException
* @throws AdminTestException
*/
@Test(dataProvider = "testcaselist")
public void test(TestCaseDTO testCaseDTO) throws AuthenticationTestException, AdminTestException {
testCaseName = testCaseDTO.getTestCaseName();
testCaseDTO=AdminTestUtil.filterHbs(testCaseDTO);

String inputJson = filterInputHbs(testCaseDTO);

response = postWithMultipartFormDataAndFile(ApplnURI + testCaseDTO.getEndPoint(), inputJson, COOKIENAME, testCaseDTO.getRole(), testCaseDTO.getTestCaseName(),idKeyName);

Map<String, List<OutputValidationDto>> ouputValid = OutputValidationUtil
.doJsonOutputValidation(response.asString(), getJsonFromTemplate(testCaseDTO.getOutput(), testCaseDTO.getOutputTemplate()));
Reporter.log(ReportUtil.getOutputValiReport(ouputValid));

if (!OutputValidationUtil.publishOutputResult(ouputValid))
throw new AdminTestException("Failed at output validation");

}

private String filterOutputHbs(TestCaseDTO testCaseDTO) {
String outputJson = getJsonFromTemplate(testCaseDTO.getOutput(), testCaseDTO.getOutputTemplate());

if (outputJson.contains("$1STLANG$"))
outputJson = outputJson.replace("$1STLANG$", BaseTestCase.languageList.get(0));
if (outputJson.contains("$2NDLANG$"))
outputJson = outputJson.replace("$2NDLANG$", BaseTestCase.languageList.get(1));
if (outputJson.contains("$3RDLANG$"))
outputJson = outputJson.replace("$3RDLANG$", BaseTestCase.languageList.get(2));
return outputJson;
}

private String filterInputHbs(TestCaseDTO testCaseDTO) {
String inputJson = getJsonFromTemplate(testCaseDTO.getInput(), testCaseDTO.getInputTemplate());

if (inputJson.contains("$1STLANG$"))
inputJson = inputJson.replace("$1STLANG$", BaseTestCase.languageList.get(0));
if (inputJson.contains("$2NDLANG$"))
inputJson = inputJson.replace("$2NDLANG$", BaseTestCase.languageList.get(1));
if (inputJson.contains("$3RDLANG$"))
inputJson = inputJson.replace("$3RDLANG$", BaseTestCase.languageList.get(2));


return inputJson;
}

/**
* The method ser current test name to result
*
* @param result
*/
@AfterMethod(alwaysRun = true)
public void setResultTestName(ITestResult result) {
try {
Field method = TestResult.class.getDeclaredField("m_method");
method.setAccessible(true);
method.set(result, result.getMethod().clone());
BaseTestMethod baseTestMethod = (BaseTestMethod) result.getMethod();
Field f = baseTestMethod.getClass().getSuperclass().getDeclaredField("m_methodName");
f.setAccessible(true);
f.set(baseTestMethod, testCaseName);
} catch (Exception e) {
Reporter.log("Exception : " + e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
GetAppointmentDetails:
Prereg_GetAppointmentDetails_All_Valid_Smoke_sid:
Prereg_GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid:
endPoint: /preregistration/v1/appointment/{preRegistrationId}
role: batch
restMethod: get
inputTemplate: preReg/GetAppointmentDetails/getAppointmentDetails
outputTemplate: preReg/GetAppointmentDetails/getAppointmentDetailsResult
input: '{
"preRegistrationId": "$ID:CreatePrereg_All_Valid_Smoke_BookByPRID_sid_preRegistrationId$"
}'
output: '{
"registration_center_id": "10003"
}'
Prereg_GetAppointmentDetails_AllValid_Smoke_sid:
endPoint: /preregistration/v1/appointment/{preRegistrationId}
role: batch
restMethod: get
Expand All @@ -11,7 +23,7 @@ GetAppointmentDetails:
output: '{
"registration_center_id": "10003"
}'
Prereg_GetAppointmentDetails_inValid_preRegistrationId_sid:
Prereg_GetAppointmentDetails_inValid_preRegistrationId:
endPoint: /preregistration/v1/appointment/{preRegistrationId}
role: batch
restMethod: get
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
SendNotifications:
Prereg_SendNotifications_All_Valid_Smoke:
endPoint: /preregistration/v1/notification
role: batch
restMethod: post
inputTemplate: preReg/SendNotifications/sendNotifications_$LANGNUMBER$
outputTemplate: preReg/SendNotifications/sendNotificationsResult
input: '{
"id":"mosip.pre-registration.notification.notify",
"version":"1.0",
"requesttime":"$TIMESTAMP$",
"name":"Test Book appointment",
"preRegistrationId":"$ID:CreatePrereg_All_Valid_Smoke_BookByPRID_sid_preRegistrationId$",
"appointmentDate":"$ID:GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid_appointment_date$",
"appointmentTime":"$ID:GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid_time_slot_from$",
"mobNum":"8249742850",
"emailID":"[email protected]",
"additionalRecipient":false,
"isBatch":false
}'
output: '{
"message": "Email and sms request successfully submitted"
}'
Prereg_SendNotifications_Notify_All_Valid_Smoke:
endPoint: /preregistration/v1/notification/notify
role: batch
restMethod: post
inputTemplate: preReg/SendNotifications/sendNotificationsNotify
outputTemplate: preReg/SendNotifications/sendNotificationsResult
input: '{
"id":"mosip.pre-registration.notification.notify",
"version":"1.0",
"requesttime":"$TIMESTAMP$",
"name":"Test Book appointment",
"preRegistrationId":"$ID:CreatePrereg_All_Valid_Smoke_BookByPRID_sid_preRegistrationId$",
"appointmentDate":"$ID:GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid_appointment_date$",
"appointmentTime":"$ID:GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid_time_slot_from$",
"mobNum":"8249742850",
"emailID":"[email protected]",
"isBatch":true
}'
output: '{
"message": "Email and sms request successfully submitted"
}'
Prereg_SendNotifications_InValid_id:
endPoint: /preregistration/v1/notification
role: batch
restMethod: post
inputTemplate: preReg/SendNotifications/sendNotifications_$LANGNUMBER$
outputTemplate: preReg/error
input: '{
"id":"mosip.pre-registration.notification.notifyasdf",
"version":"1.0",
"requesttime":"$TIMESTAMP$",
"name":"Test Book appointment",
"preRegistrationId":"$ID:CreatePrereg_All_Valid_Smoke_BookByPRID_sid_preRegistrationId$",
"appointmentDate":"$ID:GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid_appointment_date$",
"appointmentTime":"$ID:GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid_time_slot_from$",
"mobNum":"8249742850",
"emailID":"[email protected]",
"additionalRecipient":false,
"isBatch":false
}'
output: '{
"errors": [
{
"errorCode": "PRG_PAM_CORE_001",
"message": "Request id is invalid"
}
]
}'
Prereg_SendNotifications_InValid_preRegId:
endPoint: /preregistration/v1/notification
role: batch
restMethod: post
inputTemplate: preReg/SendNotifications/sendNotifications_$LANGNUMBER$
outputTemplate: preReg/error
input: '{
"id":"mosip.pre-registration.notification.notify",
"version":"1.0",
"requesttime":"$TIMESTAMP$",
"name":"Test Book appointment",
"preRegistrationId":"sadgf",
"appointmentDate":"$ID:GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid_appointment_date$",
"appointmentTime":"$ID:GetAppointmentDetails_BookByPRID_All_Valid_Smoke_sid_time_slot_from$",
"mobNum":"8249742850",
"emailID":"[email protected]",
"additionalRecipient":false,
"isBatch":false
}'
output: '{
"errors": [
{
"errorCode": "PRG_PAM_APP_005",
"message": "No data found for the requested pre-registration id"
}
]
}'
Loading

0 comments on commit 32e32d3

Please sign in to comment.