Sunteți pe pagina 1din 15

folder:convertJsonTOPojo

APIfunction.java
package com.convertJsonTOPojo;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.jsonschema2pojo.DefaultGenerationConfig;
import org.jsonschema2pojo.NoopAnnotator;
import org.jsonschema2pojo.SchemaGenerator;
import org.jsonschema2pojo.SchemaMapper;
import org.jsonschema2pojo.SourceType;
import org.jsonschema2pojo.rules.RuleFactory;

import com.sun.codemodel.JCodeModel;

public class APIfunction {

public static void createPOJOForJSON(URL path, String package1, String


className) throws IOException {
// TODO Auto-generated method stub
JCodeModel codeModel = new JCodeModel();
URL source = path;
RuleFactory ruleFactory = new RuleFactory();
ruleFactory.setAnnotator(new NoopAnnotator());
ruleFactory.setGenerationConfig(new DefaultGenerationConfig() {

@Override
public boolean isIncludeConstructors() {
return true;
}

@Override
public boolean isIncludeAdditionalProperties() {
return false;
}

@Override
public boolean isGenerateBuilders() { // set config option by
overriding method
return false;
}

@Override
public boolean isIncludeToString() {
return false;
}

@Override
public boolean isIncludeHashcodeAndEquals() {
return false;
}

public SourceType getSourceType() {

return SourceType.JSON;
}
});
SchemaMapper mapper = new SchemaMapper(ruleFactory, new
SchemaGenerator());
mapper.generate(codeModel, className, package1, source);
File outputPojoDirectory = new File("../MedApp-API/src/main/java");
codeModel.build(outputPojoDirectory);

}
}

JsonToPojo.java

package com.convertJsonTOPojo;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import org.testng.annotations.BeforeMethod;

public class JsonToPojo {

@BeforeMethod
public void generatePojo(String path, String packageName, String className)
throws MalformedURLException, IOException {
String jsonPath = System.getProperty("user.dir") + path;
File jsonFile = new File(jsonPath);
APIfunction.createPOJOForJSON(jsonFile.toURL(), packageName,
className);
}

Folder: generatedpojo

login.java

package com.generatedpojo;

public class Loginclass {

private String userName;


private String password;

/**
* No args constructor for use in serialization
*
*/
public Loginclass() {
}

/**
*
* @param password
* @param userName
*/
public Loginclass(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}

public String getUserName() {


return userName;
}

public void setUserName(String userName) {


this.userName = userName;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

RoleClass.java

package com.generatedpojo;

public class Roleclass {

private String roleName;


private Boolean isActive;

/**
* No args constructor for use in serialization
*
*/
public Roleclass() {
}

/**
*
* @param roleName
* @param isActive
*/
public Roleclass(String roleName, Boolean isActive) {
super();
this.roleName = roleName;
this.isActive = isActive;
}

public String getRoleName() {


return roleName;
}

public void setRoleName(String roleName) {


this.roleName = roleName;
}

public Boolean getIsActive() {


return isActive;
}

public void setIsActive(Boolean isActive) {


this.isActive = isActive;
}

folder:httpclient
Restclient.java
package com.httpclient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class Restclient {

public CloseableHttpResponse post(String url ,String


entityString,HashMap<String , String> headerMap) throws ClientProtocolException,
IOException
{

CloseableHttpClient httpClient = HttpClients.createDefault();


HttpPost httppost = new HttpPost(url);
httppost.setEntity(new StringEntity(entityString));
for(Map.Entry<String, String>entry : headerMap.entrySet()) {
httppost.addHeader(entry.getKey(),entry.getValue());
}
CloseableHttpResponse closeableHttpresponse =
httpClient.execute(httppost);
return closeableHttpresponse;

Test.java
package com.httpclient;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;

public class Test {

public static void main(String[] args) {


report();

public static void report() {

ExtentHtmlReporter report = new ExtentHtmlReporter("/home/cnt-


dev/Documents/API-WP/MedApp-API/ExtentReports/sample.html");

System.out.println(report);
/*report.config().setDocumentTitle("API Automation Testing Report");
report.config().setReportName("Arjun");
report.config().setTestViewChartLocation(ChartLocation.TOP);
report.config().setTheme(Theme.DARK);
report.config().setChartVisibilityOnOpen(true);*/

ExtentReports info = new ExtentReports();


info.attachReporter(report);

info.setSystemInfo("Host", "Ubuntu");
info.setSystemInfo("Environment", "QA");
info.setSystemInfo("User Name", "Mansa");

folder:qa/util
Testutil.java

package com.qa.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Testutil {

public static String getValueByJPath(JSONObject prettyJson, String jpath)


throws JSONException{
Object obj = prettyJson;
for(String s : jpath.split("/"))
if(!s.isEmpty())
if(!(s.contains("[") || s.contains("]")))
obj = ((JSONObject) obj).get(s);
else if(s.contains("[") || s.contains("]"))
obj = ((JSONArray) ((JSONObject) obj).get(s.split("\\
[")[0])).get(Integer.parseInt(s.split("\\[")[1].replace("]", "")));
return obj.toString();
}
}

folder:responsestatus
GenerateExtentReport.java
package com.responsestatus;

import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;

public class GenerateExtentReport {

ExtentHtmlReporter htmlReporter;
protected ExtentReports extent;
protected ExtentTest test;

@BeforeTest
public void startReport()
{
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")
+"/ExtentReports/LoginValidations.html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);

extent.setSystemInfo("OS", "windows");
extent.setSystemInfo("Host", "Manasa");
extent.setSystemInfo("Environment", "QA");
extent.setSystemInfo("User Name", "Mansa");

htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setDocumentTitle("AutomationTesting Demo Report");
htmlReporter.config().setReportName("My Own Report");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}

@AfterMethod
public void getResult(ITestResult result)
{
if(result.getStatus() == ITestResult.FAILURE)
{
test.log(Status.FAIL, MarkupHelper.createLabel(result.getName()+" Test
case FAILED due to below issues:", ExtentColor.RED));
test.fail(result.getThrowable());
}
else if(result.getStatus() == ITestResult.SUCCESS)
{
test.log(Status.PASS, MarkupHelper.createLabel(result.getName()+" Test
Case PASSED", ExtentColor.GREEN));
}
else
{
test.log(Status.SKIP, MarkupHelper.createLabel(result.getName()+" Test
Case SKIPPED", ExtentColor.ORANGE));
test.skip(result.getThrowable());
}
}

@AfterTest
public void tearDown()
{
extent.flush();
}
}

Testbase.java
package com.responsestatus;

import java.io.FileInputStream;
import java.util.Properties;

public class Testbase {

//Logger log = Logger.getLogger(report.class.getName());

public int RESPONSE_STATUS_CODE_200 = 200;


public int RESPONSE_STATUS_CODE_500 = 500;
public int RESPONSE_STATUS_CODE_400 = 400;
public int RESPONSE_STATUS_CODE_401 = 401;
public int RESPONSE_STATUS_CODE_201 = 201;

public String getAppProperty(String object) throws Exception {


FileInputStream fs = new FileInputStream("../MedApp-
API/Prop/config.properties");
Properties app = new Properties();
app.load(fs);
return app.getProperty(object);

folder:src\test\java\com\qa\post
Login.java
package com.qa.post;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

import com.aventstack.extentreports.Status;
import com.convertJsonTOPojo.JsonToPojo;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.generatedpojo.Loginclass;
import com.httpclient.Restclient;
import com.qa.util.Testutil;
import com.responsestatus.GenerateExtentReport;
import com.responsestatus.Testbase;

public class Login extends GenerateExtentReport {

Testbase TB = new Testbase();


String baseurl;
String apiUrl;
String url;
Restclient conc;
CloseableHttpResponse closeableHttpResponse;

@BeforeSuite
public void pojodynamically() throws MalformedURLException, IOException {
JsonToPojo jsonToPojo = new JsonToPojo();
jsonToPojo.generatePojo("/Testjson/login.json", "com.generatedpojo",
"Loginclass");

@BeforeMethod
public void setup() throws Exception {

TB = new Testbase();
baseurl = TB.getAppProperty("URL");
System.out.println(baseurl);
apiUrl = TB.getAppProperty("serviceURL");
System.out.println(apiUrl);

url = baseurl + apiUrl;


System.out.println(url);
}

@Test
public void validLogin() throws JsonGenerationException,
JsonMappingException, IOException, JSONException {
test = extent.createTest("validLogin", "Check with Valid Details");
Assert.assertTrue(true);

conc = new Restclient();


HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Content-Type", "application/json");

ObjectMapper mapper = new ObjectMapper();


Loginclass pojoclass = new Loginclass("", "");

// Object to JSON
mapper.writeValue(new File("../MedApp-
API/src/main/java/com/generatedpojo/resp.json"), pojoclass);

// Java object to JSON in String:


String pojoJsonString = mapper.writeValueAsString(pojoclass);
System.out.println(pojoJsonString);

closeableHttpResponse = conc.post(url, pojoJsonString, headerMap); //


call the API

test.log(Status.INFO, "POST API passed within the request");


test.log(Status.INFO, "Payload json added in the request");
test.log(Status.INFO, "Headers added to the request");
test.log(Status.INFO, "request sent successfully");

// Validate response from API:


// 1. Status code:
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();

System.out.println(statusCode);
Assert.assertEquals(statusCode, TB.RESPONSE_STATUS_CODE_200);

test.log(Status.PASS, "Response json received");


test.log(Status.INFO, "status code : " + statusCode + "");

// 2. JsonString:
String responseString =
EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
Object jsonObject = mapper.readValue(responseString, Object.class);
String prettyJson =
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(prettyJson);
JSONObject responseJson = new JSONObject(prettyJson);
test.log(Status.INFO, "response json : " + responseJson + "");

//Validate Headers in Response


Header[] headersArray = closeableHttpResponse.getAllHeaders();
for (Header header : headersArray) {
System.out.println(header);
test.log(Status.INFO,"Display Response Headers" + header + "");
}

String message = Testutil.getValueByJPath(responseJson,


"/status/message");
System.out.println("value of message is : " + message);
Assert.assertEquals(message, "User Found");

@Test
public void invalidpassword() throws JsonGenerationException,
JsonMappingException, IOException, JSONException {
test = extent.createTest("invalidpassword","check with Invalid
Password");
Assert.assertTrue(true);
conc = new Restclient();
test.log(Status.INFO, "Login with invalid password testcase");

HashMap<String, String> headerMap = new HashMap<String, String>();


headerMap.put("Content-Type", "application/json");

ObjectMapper mapper = new ObjectMapper();


Loginclass pojoclass = new Loginclass("haripriya.p@cloudnowtech.com",
"Hms@123123");

// Object to JSON
mapper.writeValue(new File("../MedApp-
API/src/main/java/com/generatedpojo/resp.json"), pojoclass);

// Java object to JSON in String:


String pojoJsonString = mapper.writeValueAsString(pojoclass);
System.out.println(pojoJsonString);

closeableHttpResponse = conc.post(url, pojoJsonString, headerMap); //


call the API

// validate response from API:


// 1. status code:
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
Assert.assertEquals(statusCode, TB.RESPONSE_STATUS_CODE_200);

test.log(Status.PASS, "Response json received");


test.log(Status.INFO, "status code : " + statusCode + "");

// 2. JsonString:
String responseString =
EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
Object jsonObject = mapper.readValue(responseString, Object.class);
String prettyJson =
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(prettyJson);
JSONObject responseJson = new JSONObject(responseString);
System.out.println("The response from API is:" + responseJson);
test.log(Status.INFO, "response json : " + responseJson + "");

String message = Testutil.getValueByJPath(responseJson,


"/status/message");
System.out.println("value of message is : " + message);
Assert.assertEquals(message, "User Not Found");

}
}
Role.Java

package com.qa.post;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.convertJsonTOPojo.JsonToPojo;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.generatedpojo.Roleclass;
import com.httpclient.Restclient;
import com.qa.util.Testutil;
import com.responsestatus.Testbase;

public class Role {


Testbase TB = new Testbase();
String baseurl;
String apiUrl;
String url;
Restclient conc;
CloseableHttpResponse closeableHttpResponse;

@BeforeSuite
public void pojodynamically() throws MalformedURLException, IOException {
JsonToPojo jsonToPojo = new JsonToPojo();
jsonToPojo.generatePojo("/Testjson/roleParams.json",
"com.generatedpojo", "Roleclass");

@BeforeTest
public void setup() throws Exception {

TB = new Testbase();
baseurl = TB.getAppProperty("URL");
System.out.println(baseurl);
apiUrl = TB.getAppProperty("roleparamURL");
System.out.println(apiUrl);

url = baseurl + apiUrl;


System.out.println(url);
}

@Test
public void addRole() throws JsonGenerationException, JsonMappingException,
IOException, JSONException {
conc = new Restclient();

HashMap<String, String> headerMap = new HashMap<String, String>();


headerMap.put("Content-Type", "application/json");

ObjectMapper mapper = new ObjectMapper();


Roleclass RP = new Roleclass("Admin", true);
// Object to JSON
mapper.writeValue(new File("../MedApp-
API/src/main/java/com/generatedpojo/resp.json"), RP);

// Java object to JSON in String:


String pojoJsonString = mapper.writeValueAsString(RP);
System.out.println(pojoJsonString);

closeableHttpResponse = conc.post(url, pojoJsonString, headerMap); //


call the API

// Validate response from API:


// 1. Status code:
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
System.out.println(statusCode);
Assert.assertEquals(statusCode, TB.RESPONSE_STATUS_CODE_200);

// 2. JsonString:
String responseString =
EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
Object jsonObject = mapper.readValue(responseString, Object.class);
String prettyJson =
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(prettyJson);
JSONObject responseJson = new JSONObject(prettyJson);

String message = Testutil.getValueByJPath(responseJson,


"/status/message");
System.out.println("value of message is : " + message);
Assert.assertEquals(message, "Role Found");

// All Headers
Header[] headersArray = closeableHttpResponse.getAllHeaders();
for (Header header : headersArray) {
System.out.println(header);
}

}
}

Config.extend
<?xml version="1.0" encoding="UTF-8"?>
<extentreports>
<configuration>
<!-- report theme -->
<!-- standard, dark -->
<theme>standard</theme>

<!-- document encoding -->


<!-- defaults to UTF-8 -->
<encoding>UTF-8</encoding>

<!-- protocol for script and stylesheets -->


<!-- defaults to https -->
<protocol>https</protocol>

<!-- title of the document -->


<documentTitle>Extent</documentTitle>

<!-- report name - displayed at top-nav -->


<reportName>Automation Report</reportName>

<!-- location of charts in the test view -->


<!-- top, bottom -->
<testViewChartLocation>bottom</testViewChartLocation>

<!-- custom javascript -->


<scripts>
<![CDATA[
$(document).ready(function() {

});
]]>
</scripts>

<!-- custom styles -->


<styles>
<![CDATA[

]]>
</styles>
</configuration>
</extentreports>

Login.xml
<?xml version="1.0" encoding="UTF-8"?>

<suite name="example suite 1" verbose="1" >


<test name="Regression suite 1" >
<classes>
<class name="com.qa.post.Login"/>

</classes>
</test>
</suite>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Gsonrest</groupId>
<artifactId>restapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>restapi</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>

<dependency>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-core</artifactId>
<version>0.4.35</version>

</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
</dependency>

<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>3.0.2</version>
</dependency>

<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>3.0.2</version>
</dependency>

<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.0.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.0.0</version>
</dependency>

<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.2</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!--
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>

<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>

</dependencies>
</project>

S-ar putea să vă placă și