Skip to main content

RestAssured rest API test framework for GET & POST API json verification with Extent report

package com.resttest;
import static io.restassured.RestAssured.given;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.collections.iterators.EntrySetMapIterator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.ExtentLoggerReporter;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class testRestAPI {
public static String Cookie;
public static int res;
public static String mfr="ptc";
public static String prod="ptc";
public static String sch="podis";
ExtentLoggerReporter logger = new ExtentLoggerReporter("/ebs/is/build/");
static ExtentReports extent;

@BeforeSuite
public static void httplogin() throws JSONException,InterruptedException, IOException{
HashMap<String,String> postcred = new HashMap<String,String>();
postcred.put("email","userid@company.com");
postcred.put("password","password");
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
RequestSpecification requestSpec = builder.addFormParams(postcred).build();
Response response = given().spec(requestSpec.accept(ContentType.JSON)).post("pass the login API which gives PLAY cookie");
JsonPath jp=new JsonPath(response.body().asString());
Cookie = jp.get("Session");
    }

    public void test(Map<Integer,String> map) throws IOException, JSONException {
EntrySetMapIterator itr=new EntrySetMapIterator(map);
while(itr.hasNext()) {
    int i=Integer.parseInt(itr.next().toString());
if(itr.getValue().toString().startsWith("GET")) {
System.out.println("=========================================\n"+"GET API TC"+(i+1)+" => "+itr.getValue().toString());
getapi(itr.getValue().toString());
System.out.println("=========================================\n");
}else if(itr.getValue().toString().startsWith("POST")) {
System.out.println("=========================================\n"+"POST API TC"+(i+1)+" => "+itr.getValue().toString());
postapi(itr.getValue().toString());
System.out.println("=========================================\n");
}else if(itr.getValue().toString().startsWith("STRING")) {
System.out.println("=========================================\n"+"STRING TYPE API TC"+(i+1)+" => "+itr.getValue().toString());
getstringapi(itr.getValue().toString());
System.out.println("=========================================\n");
}
}
} */

@BeforeTest
public void nothing() {
logger.config().setAutoCreateRelativePathMedia(true);
extent = new ExtentReports();
ExtentHtmlReporter html = new ExtentHtmlReporter("Extent.html");
extent.attachReporter(logger);
    extent.attachReporter(html);
}
 
@Test(dataProvider = "hashmap")
public void getstringapi(String url) throws IOException, JSONException{
    try{
    String[] str=url.split("\\|");
        HttpHeaders requestHeaders1 = new HttpHeaders();
            requestHeaders1.set("Cookie", Cookie);
            HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders1);
        ResponseEntity<String> response2 = new RestTemplate().exchange(str[1], HttpMethod.GET, requestEntity, String.class);
        Assert.assertTrue(str[2].equals(response2.getBody().toString()),"\n\n*********************\nSTRING API TC Failed\n*********************\n\n");
    }catch(Exception e){
    e.printStackTrace();
    System.out.println("*** TC failed due to some exception");
    }
    }

@Test(dataProvider = "hashmap")
public void getapi(Map<Integer,String> map) throws IOException, JSONException{
    try{
    EntrySetMapIterator itr=new EntrySetMapIterator(map);
    while(itr.hasNext()) {
    int i=Integer.parseInt(itr.next().toString());
if(itr.getValue().toString().startsWith("GET")) {
System.out.println("=========================================\n"+"GET API TC"+(i+1)+" => "+itr.getValue().toString());
    String[] str=itr.getValue().toString().split("\\|");
            HttpHeaders requestHeaders1 = new HttpHeaders();
            requestHeaders1.setContentType(MediaType.APPLICATION_JSON);
            requestHeaders1.set("Cookie", Cookie);
            HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders1);
        ResponseEntity<HashMap> response2 = new RestTemplate().exchange(str[1], HttpMethod.GET, requestEntity, HashMap.class);
        JSONObject jsonobjexpected1 = new JSONObject(IOUtils.toString(new FileInputStream(new File(str[2])), "UTF-8"));     
        JSONObject tmp=new JSONObject(response2.getBody());
        FileUtils.writeStringToFile(new File(System.getProperty("user.dir")+"/src/main/resources/expected/temp.json"),tmp.toString(),("UTF-8"));
        JSONObject jsonobjactual1 = new JSONObject(IOUtils.toString(new FileInputStream(System.getProperty("user.dir")+"/src/main/resources/expected/temp.json"), "UTF-8"));
        try {
        JSONAssert.assertEquals(jsonobjexpected1.toString(), jsonobjactual1.toString(), JSONCompareMode.LENIENT);
        System.out.println("*** test passed");
        extent.createTest(str[0]).pass(str[0]+" Test passed");
        }catch(AssertionError ae) {
        ae.printStackTrace();
        System.out.println("*** test failed");
        extent.createTest(str[0]).fail(str[0]+" Test failed");
        }
        FileUtils.forceDeleteOnExit(new File(System.getProperty("user.dir")+"/src/main/resources/expected/temp.json"));
  }
else {
System.out.println("As API is not GET API, skipping it");
break;
}
     }
    }catch(Exception e){
System.out.println("*** TC failed due to following printed Exception");
        e.printStackTrace();
    }
}
 
@Test(dataProvider = "hashmap")
    public static void postapi(Map<Integer,String> map) throws IOException, JSONException{
    try{
    EntrySetMapIterator itr=new EntrySetMapIterator(map);
    while(itr.hasNext()) {
    int i=Integer.parseInt(itr.next().toString());
if(itr.getValue().toString().startsWith("POST")) {
System.out.println("=========================================\n"+"POST API TC"+(i+1)+" => "+itr.getValue().toString());

String[] str=itr.getValue().toString().split("\\|");
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        requestHeaders.set("Cookie", Cookie);
    HttpEntity<String> requestEntity = new HttpEntity<String>(str[3],requestHeaders);
    ResponseEntity<HashMap> response3 = new RestTemplate().exchange(str[1], HttpMethod.POST, requestEntity, HashMap.class);
    JSONObject jsonobjexpected1 = new JSONObject(IOUtils.toString(new FileInputStream(new File(str[2])), "UTF-8"));
        JSONObject tmp=new JSONObject(response3.getBody());
    FileUtils.writeStringToFile(new File(System.getProperty("user.dir")+"/src/main/resources/expected/temp.json"),tmp.toString(),("UTF-8"));
    JSONObject jsonobjactual1 = new JSONObject(IOUtils.toString(new FileInputStream(System.getProperty("user.dir")+"/src/main/resources/expected/temp.json"), "UTF-8"));
    try {
    JSONAssert.assertEquals(jsonobjexpected1, jsonobjactual1, JSONCompareMode.LENIENT);
    extent.createTest(str[0]).pass(str[0]+" Test passed");
        }catch(AssertionError ae) {
        ae.printStackTrace();
        System.out.println("*** test failed");
        extent.createTest(str[0]).fail(str[0]+" Test failed");
        }
    FileUtils.forceDeleteOnExit(new File(System.getProperty("user.dir")+"/src/main/resources/expected/temp.json"));
  }
else {
System.out.println("As API is not POST API, skipping it");
break;
}
     }
    }catch(Exception e){
System.out.println("*** TC failed due to following Exception");
e.printStackTrace();
    }
    }

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

    public static String getfoldername(String name) {
String res="";
Pattern ptn = Pattern.compile("TC\\d+");
String[] parts = ptn.split(name);
for(String p:parts){
res=p;
}
return res;
}

@DataProvider(name = "hashmap")
public static Object[][] hashmap() {

String restdomain="http://domain.company.com:port";

Map<Integer, String> map = new HashMap<Integer, String>();

map.put(0,"POSTSectionViewTC1|"+restdomain+"/postAPIFullURL/arg1/arg2...|"+System.getProperty("user.dir")+"/src/main/resources/expected/POST_TC/POST_TC1.json|{\"sendname\":\"ByPOSTreq\",\"versioing\":\"{'version:true'}\"}");//make sure you will create this expected POST_TC1.json file with valid json content.

map.put(1,"GETSectionViewTC2|"+restdomain+"/v1/getAPIFullURL/arg1/arg2...|"+System.getProperty("user.dir")+"/src/main/resources/expected/GET_TC/GET_TC2.json");//make sure you will create this expected GET_TC1.json file with valid json content.

map.put(2,"STRINGSTRING_TCTC3|"+restdomain+"/v1/getStringAPIFullURL/arg1/arg2...|"+System.getProperty("user.dir")+"/src/main/resources/expected/STRING_TC/STRING_TC3.txt");//make sure you will create this expected STRING_TC3.txt file with valid string content.

return new Object[][] {{map}};
}
}

Note:
Add a testng.xml and pass above class name to <test> tag to invoke tests from above class & run that testng.xml with testng to see results.

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false" group-by-instances="true">
   <test name="metadata">
<classes>
<class name="com.resttest.testRestAPI" />
</classes>
   </test>
</suite>

==============================================
Maven pom.xml requirements:

<repositories>
   <repository>
        <id>codelds</id>
        <url>https://code.lds.org/nexus/content/groups/main-repo</url>
    </repository>
    <repository>
        <id>central</id>
        <url>http://repo.maven.apache.org/maven2/</url>
    </repository>
</repositories>
<dependencies>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
    <groupId>org.skyscreamer</groupId>
    <artifactId>jsonassert</artifactId>
    <version>1.5.0</version>
<exclusions>
        <!-- Exclude Groovy because of classpath issue -->
        <exclusion>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
        </exclusion>
    </exclusions>
    <scope>compile</scope></dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-path -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-path</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>com.aventstack</groupId>
    <artifactId>extentreports</artifactId>
    <version>4.0.9</version>
</dependency>
</dependencies>

Comments

Popular posts from this blog

javamail jdk11(11.0.10 and above) needs tls upgrade from 1.1 to 1.2

ISSUE 1: Unable to send/read mails using javamail/javaxmail after you upgraded your jdk to 11.0.10 or above?  The reason is they came up with higher security level for SSL with TLS 1.2 which is dependency for latest jdk, find the solution below: Possible Exception if you used older version TLS-1.1:  javax.net.ssl.sslhandshakeexception Solution: Add below property to your existing Properties. properties.put("mail.imaps.ssl.protocols","TLSv1.2");(IMAP used to read mail) properties.put("mail.smtp.ssl.protocols","TLSv1.2");(SMTP used to send mail) ISSUE 2: Unable to type case Multipart to String? From jdk11(latest version) onwards multipart and string cant be type casted, so we need to use Object to store message content. Solution: for (int i = 0; i < messages.length; i++) { Message message = messages[i]; Object content = message.getContent(); if (content instanceof String) { String body = (String)content; System.out.println...

Extent report for Rest API test

Below code helps in failing or passing your Rest API test case & updating result to Extent report. Maven dependency(pom.xml): <dependency>     <groupId>com.aventstack</groupId>     <artifactId>extentreports</artifactId>     <version>4.0.9</version> </dependency> code: import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import com.aventstack.extentreports.reporter.ExtentLoggerReporter; public class A{ ExtentLoggerReporter logger = new ExtentLoggerReporter("dir path to store extent result"); static ExtentReports extent; @Test public void testname(){ //Your code to capture json from get/post/put/delete API to "JSONObject jsonobjexpected" field. //your code to read actual json content from file/anywhere to "JSONObject jsonobjactual" field. try {         JSONAssert.assertEquals(jsonobjexpected.toString(...