Saturday, May 14, 2022

Reporting with Allure Report with Rest Assured

 To generate a better looking report with attachment is required in automation testing to know the details of the execution.

Allure report is a reporting api which can be used to get all the facility.

Now we can learn in details in the following steps:


Step 1:

Create a maven project and use the following pom.xml file.

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.blogspot.startingwithseleniumwebdriver</groupId>
    <artifactId>AllureReport</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <aspectj.version>1.9.5</aspectj.version>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>5.0.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.qameta.allure/allure-testng -->
        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-testng</artifactId>
            <version>2.17.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.qameta.allure/allure-rest-assured -->
        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-rest-assured</artifactId>
            <version>2.17.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.5</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
                <configuration>
                    <systemPropertyVariables>
                        <allure.results.directory>${project.build.directory}/allure-results</allure.results.directory>
                    </systemPropertyVariables>
                    <suiteXmlFiles>
                        <suiteXmlFile>${project.basedir}/testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                    <argLine>
                        -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                    </argLine>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjweaver</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
    <reporting>
        <excludeDefaults>true</excludeDefaults>
        <plugins>
            <plugin>
                <groupId>io.qameta.allure</groupId>
                <artifactId>allure-maven</artifactId>
                <version>2.11.2</version>
                <configuration>
                    <reportVersion>2.17.3</reportVersion>
                    <resultsDirectory>${project.build.directory}/allure-results</resultsDirectory>
                </configuration>
            </plugin>
        </plugins>
    </reporting>
</project>

Step 2:

package com.blogspot.startingwithseleniumwebdriver;

import org.testng.annotations.Test;

import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;

public class TestAllureReportRestAssured {

    @Test
    private void testAllureReportWithRestAssured() {

        RequestSpecBuilder reqSpecBuilder = new RequestSpecBuilder();

        //To add Request and Response in Report Add this Filter.
        reqSpecBuilder.addFilter(new AllureRestAssured());
        RequestSpecification reqSpec = reqSpecBuilder.build();
        
        RestAssured.given().spec(reqSpec).get("https://reqres.in/api/users?page=2");
    }
}

 

Step 3:

Below maven command is used to run the project it will create the allure-results folder in the configured destination.

clean install

 

 Below maven command is for after completion of the execution open browser and launch the report

clean install io.qameta.allure:allure-maven:serve

 Below maven command is to generate allure report under Project path\target\site\allure-maven-plugin

clean install io.qameta.allure:allure-maven:report

 

 Step 4:

Allure report will not open properly if we open index.html file from normal browser mode due to mordern browser restriction of external javascript execution from same origin.

So if we have a allure report which one previously generated then we need the following settings to open the report in browser.

chrome.exe --disable-web-security --user-data-dir=C:\Windows\Temp

                                                           Or

chrome.exe --allow-file-access-from-files

Step 5:

All the below commands executed after navigated to project directory\.allure\allure-2.13.9\bin in cmd and then use.

else we can download the allure command line from here and execute the below command from bin directory.













To generate report manually from cmd we need to use the below command

allure generate -c <path of allure result folder>  -o <path of allure report folder>

If already report generate and need to open in browser then need to execute the below command

allure open <path of allure report folder>

If directly open the report from allure result then need to use the below command

allure serve  <path of allure result folder>

Step 6:

Report Dashboard



Report generated with attachment of request and response details.

 




 


  


Wednesday, June 3, 2020

Store Chrome And Firefox Driver Log

Some time we need to write driver log to understand the issue in more deeply, for that reason we can write or store the driver log on any log file.

Step 1:

Create a driver service with log file path like below :

For Chrome

ChromeDriverService services = new ChromeDriverService.Builder().withSilent(false).withLogFile(new File("./src/test/resources/chrome.log")).build();

For Firefox

GeckoDriverService service = new GeckoDriverService.Builder().withLogFile(new File("./src/test/resources/firefox.log")).build();

Step 2:

Now pass the service parameter to WebDriver Instance.

WebDriver driver = new ChromeDriver(services);

Sunday, May 31, 2020

How to stop chrome timeout receiving message from renderer

Some time we got this message in our editor when we execute our script from our IDE.

Even if it does not create any problem to execute our script but if we are interested to resolve this we need to follow the following steps.

Step 1 :

Create a ChromeDriverService with silent mode.

ChromeDriverService services = new ChromeDriverService.Builder().withSilent(true).build();

Step 2 :

Create a WebDriver instance and pass the ChromeDriverService as a parameter in constructor.

WebDriver driver = new ChromeDriver(services);

Saturday, April 18, 2020

Added Text in label using JavascriptExecutor in Selenium WebDriver

Here we will discuss how we can put some text in html field. It is require to add some data within html field.

Steps: 1 

                JavascriptExecutor executor = (JavascriptExecutor)driver;

 Steps: 2

            executor.executeScript("arguments[0].innerHTML = '" + text +"';", element);

Here we set the innerHTML value and added some extra text.


public static void addText(WebElement element, String text) {
        try
        {
            JavascriptExecutor executor = (JavascriptExecutor)driver;
            executor.executeScript("arguments[0].innerHTML = '" + text +"';", element);
        }
        catch (Exception e)
        {
            log.error("Couldnot able to send text on element: " + element);
            throw e;
        }
    }

Remove Readonly attribute using JavascriptExecutor in Selenium WebDriver

   
In automation we need to type some value in readonly field. Though we should not do that for proper validation but to achieving some goal or to reducing the line of code or may be to be over sure those steps will never fail.


It can be achieved using the following line

Steps: 1
             JavascriptExecutor executor = (JavascriptExecutor)driver;

Step: 2
            executor.executeScript("arguments[0].removeAttribute('readonly',0);", element); 

Here we are using removeAttribute('readonly',0) method to remove the attribute from html element


We are trying to make our element editable so 'readonly' field removed from here.

Second parameter of removeAttribute method of java script is optional we are mentioning it as '0' here for non case sensitive search, meaning of the different values are described below.

0      It is the default value and performs the non case sensitive search
1      It performs the case sensitive property search
2      It returns the property value as it is set in the script or html code

public static void removeReadOnly(WebElement element) {
        try
        {
            JavascriptExecutor executor = (JavascriptExecutor)driver;
            executor.executeScript("arguments[0].removeAttribute('readonly',0);", element);
        }
        catch (Exception e)
        {
            log.error("Couldnot able to remove readonly from element: " + element);
            throw e;
        }
    }

Saturday, March 21, 2020

Resst Assured Custom Filter

We can log all Request And Response using log.all() method in console but we can't log it within log file or can't customize the log what we need to print.

Here we will learn how we can configure the filter to store the request and response in logfile for future purpose like debug.

We will follow the below steps for creating the CustomFilter.

Step 1:

Below pom.xml file is required for sample RestAssured project

<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>com.api.automation</groupId>
    <artifactId>APITest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.1.1</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</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.10</version>
        </dependency>

    </dependencies>
</project>



Step 2:

Now we will create a class for CustomLoggingFilter, this class implements Filter class and override the filter method of Filter class.

package com.api.automation.test;

import java.io.PrintStream;
import java.io.StringWriter;
import java.nio.charset.Charset;

import org.apache.commons.io.output.WriterOutputStream;

import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.filter.log.LogDetail;
import io.restassured.internal.print.RequestPrinter;
import io.restassured.internal.print.ResponsePrinter;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;

public class CustomLoggingFilter implements Filter {

   

    public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec,FilterContext ctx) {
      
        Response response = ctx.next(requestSpec, responseSpec);

        


        // Storing Request in String
        String requestString = RequestPrinter.print(requestSpec, requestSpec.getMethod(), requestSpec.getURI(), LogDetail.ALL, new PrintStream(new WriterOutputStream(new StringWriter(),Charset.defaultCharset())), true);
        


        // Storing Response in String
        String responseString = ResponsePrinter.print(response, response, new PrintStream(new WriterOutputStream(new StringWriter(),Charset.defaultCharset())), LogDetail.ALL, true);
        


        // Print request in String
        System.out.println("Print Request: " + requestString);
        


        // Print response in String
        System.out.println("Print Response: " + responseString);
        


        /*
         * Logging the response depends on response status code
         */

        


        /*
         * int statusCode = response.getStatusCode(); if (statusCode >= 400 &&
         * statusCode <= 500) {
         * System.out.println("****************************************" +
         * responseString); } else { System.out.println(" (" + statusCode+ ")"); }
         */

      
        return response;
    }
}

 
 

Step 3:

Now we will write the test class to implement the CustomLoggingFilter.

We will add this custom filter in RequestSpecification.

package com.api.automation.test;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;


public class ValidateAPI {

    @Test
    public void validateSimpleAPI() {
      
        RequestSpecification requestSpecification = new RequestSpecBuilder().setBaseUri("http://restapi.demoqa.com/utilities/weather/city/")
                .setContentType(ContentType.JSON)

                .addFilter(new CustomLoggingFilter())
                .build();
      
        RestAssured.given(requestSpecification).when().get("/Hyderabad").then();
        
    }
}

 
 

Sunday, March 1, 2020

DataTable Handling With Cucumber 4

Previously in older version of  Cucumber we can transform Datatable as per our own object easily but now we need to implement TypeRegistryConfigurer in our code.

Here we will discuss on it.

Step 1:

Create a Employee class as below

public class EmployeeDTO {

    private String username;
    private String password;

    public EmployeeDTO(String username, String password) {
        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 setPasword(String password) {
        this.password = password;
    }

}


Step 2: 

Now we need to implemnt TypeRegistryConfigurer as below

import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.cucumber.core.api.TypeRegistry;
import io.cucumber.core.api.TypeRegistryConfigurer;
import io.cucumber.datatable.DataTableType;
import io.cucumber.datatable.TableEntryTransformer;
import io.cucumber.datatable.TableRowTransformer;
import io.cucumber.datatable.TableCellTransformer;

public class EmployeeRegistryConfigurer implements TypeRegistryConfigurer {


    @Override
    public Locale locale() {
        // TODO Auto-generated method stub
        return Locale.ENGLISH;
    }

//RowTransformer is List of Objects List<EmployeeDTO>  
    @Override
    public void configureTypeRegistry(TypeRegistry typeRegistry) {
        typeRegistry.defineDataTableType(new DataTableType(EmployeeDTO.class,new TableRowTransformer<EmployeeDTO>() {

            @Override
            public EmployeeDTO transform(List<String> row) throws Throwable {
                // TODO Auto-generated method stub
                return new EmployeeDTO(row.get(0), row.get(1));
            }
        }));
    }


//CellTransformer is List of List of Objects List<List<EmployeeDTO>> employeeDetails  
//    @Override
//    public void configureTypeRegistry(TypeRegistry typeRegistry) {
//        typeRegistry.defineDataTableType(new DataTableType(EmployeeDTO.class, new TableCellTransformer<EmployeeDTO>() {
//            @Override
//            public EmployeeDTO transform(String cell) throws Throwable {
//                return new EmployeeDTO(cell, cell);
//            }
//          
//        }));
      
  
//EntryTransformer is List of Maps of Keys to Values List<EmployeeDTO>  
//        @Override
//        public void configureTypeRegistry(TypeRegistry registry) {
//            registry.defineDataTableType(new DataTableType(EmployeeDTO.class, new TableEntryTransformer<EmployeeDTO>() {
//                @Override
//                public EmployeeDTO transform(Map<String, String> entry) throws Throwable {
//                    return new EmployeeDTO(entry.get("username"),entry.get("password"));
//                }
//            }));
//
//    }

}
Step 3:

Now we can call this as below:

public class Steps {

    @Given("UserName and Password.")
    public void username_and_Password() {
        System.out.println("Test");
    }

    @Given("UserName and Password as below.")
    public void username_and_Password_as_below(List<EmployeeDTO> employeeDetails) {
        System.out.println(employeeDetails.get(0).getUserName());
        System.out.println(employeeDetails.get(0).getPassword());
        System.out.println(employeeDetails.get(1).getUserName());
        System.out.println(employeeDetails.get(1).getPassword());
    }
}