Tuesday 7 November 2017

How to Create Extent Reports 2.X in Selenium Webdriver

Extent Reports in Selenium

Pre-requisites to Generate Extent Reports:
1 Download  Extent Reports jar file and add it to the Project.

2. Create an ExtendReport object and give the path where you want to store the report
Ex: ExtentReports ext=new ExtentReports("C:\\Reports\\report1.html");

3. Retrive the ExtentTest object
Ex: ExtentTest logger=ext.startTest("Extend Report 2 Test");

4.Log the reports
Ex: logger.log(LogStatus.INFO, "Navigate to the URL");

5.End the Test and call flush().
Ex: ext.endTest(logger);
    ext.flush()

Sample Code: Senario Taken-- Type some text in the text box(Search box in this example) and perform Copy and Paste using Chord and Keys


package com.p1;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class ExtendReports2 {

public WebDriver driver;

ExtentReports ext=new ExtentReports("G:\\Selenium\\extendReports\\Reports\\report1.html");
    ExtentTest logger=ext.startTest("Extend Report 2 Test");

 
    @Test
    public void testKeys_Chord() {
     
     driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);   
   
     //Object for the search box
     WebElement sb=driver.findElement(By.xpath(".//*[@id='BlogSearch1_form']/form/table/tbody/tr/td[1]/input"));   
   
     //Type "The mouse-over using JavascriptExecutor and Actions in Selenium Webdriver" in search box
     sb.sendKeys("The mouse-over using JavascriptExecutor and Actions in Selenium Webdriver ");
     logger.log(LogStatus.INFO, "Typed the text in the search box");  
   
     //Perform Control A and C actions 
     sb.sendKeys(Keys.chord(Keys.CONTROL,"a"), "");
  logger.log(LogStatus.INFO, "Performed the keyboard action Control A");
     sb.sendKeys(Keys.chord(Keys.CONTROL,"c"), "");
  logger.log(LogStatus.INFO, "Performed the keyboard action Control C");
   
     //Clear the Text 'The mouse-over using JavascriptExecutor and Actions in Selenium Webdriver' typed in the Search box
     sb.clear();
  logger.log(LogStatus.INFO, "Cleared the search box");
   
       try {
           Thread.sleep(2000);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }

       // Perform paste action using CTRL+V in search box
       sb.sendKeys(Keys.chord(Keys.CONTROL, "v"), "");
logger.log(LogStatus.INFO, "Pasted the copied content in the search box");

       try {
           Thread.sleep(2000);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
     
       driver.findElement(By.xpath(".//*[@id='BlogSearch1_form']/form/table/tbody/tr/td[2]/input")).click();
logger.log(LogStatus.INFO, "Clicked the Search button");

    }


    @BeforeClass
    public void beforeClass()
       {


      System.setProperty("webdriver.gecko.driver", "G://Selenium//geckodriver-v0.19.1-win32//geckodriver.exe");

      driver = new FirefoxDriver();

      driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);

      driver.get("http://allthingsaboutuft.blogspot.in/");
logger.log(LogStatus.INFO, "Launched the URL");

      driver.manage().window().maximize();
logger.log(LogStatus.INFO, "Browser is maximized");
       }
   
     @AfterClass
     public void afterClass() throws Exception
        {
      logger.log(LogStatus.INFO, "Report is opened");
 
  ext.endTest(logger);
  ext.flush();
 
  driver.get("file:///G:/Selenium/extendReports/Reports/report1.html");
        }

}

Reprot:
extent report in selenium webdriver,extent report selenium jar, how to use extent reports, extent report testng, download extent report jar for selenium


Graphical Report:

extent report in selenium webdriver,extent report selenium jar, how to use extent reports, extent report testng, download extent report jar for selenium

Tuesday 26 September 2017

Chord and Keys in Selenium Webdriver to press multiple keys

Chord and Keys in Selenium WebDriver to press multiple keys




keys class in selenium webdriver, how to use keyboard keys in selenium webdriver, keys.control selenium, how to press Control a+c+v key using selenium, java key example





A good option to simulate multiple keys press can be achieved through Chord and Keys in Selenium Webdriver

Senario Taken: Type some text in the text box(Search box in this example) and perform Copy and Paste using Chord and Keys




package com.p1;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class chord {
   
    public WebDriver driver;
   
     @Test
     public void testKeys_Chord() {
       
       driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);   
     
      //Object for the search box
      WebElement sb=driver.findElement(By.xpath(".//*[@id='BlogSearch1_form']/form/table/tbody/tr/td[1]/input"));   
     
      //Type "The mouse-over using JavascriptExecutor and Actions in Selenium Webdriver" in search box
      sb.sendKeys("The mouse-over using JavascriptExecutor and Actions in Selenium Webdriver "); 
    
      //Perform Control A and C actions  
      sb.sendKeys(Keys.chord(Keys.CONTROL,"a"), "");
      sb.sendKeys(Keys.chord(Keys.CONTROL,"c"), "");
     
      //Clear the Text 'The mouse-over using JavascriptExecutor and Actions in Selenium Webdriver' typed in the Search box
      sb.clear();
     
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Perform paste action using CTRL+V in search box
        sb.sendKeys(Keys.chord(Keys.CONTROL, "v"), "");

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
        driver.findElement(By.xpath(".//*[@id='BlogSearch1_form']/form/table/tbody/tr/td[2]/input")).click();

     }

      @BeforeClass
      public void beforeClass()
         {
        System.setProperty("webdriver.gecko.driver", "C://Selenium//geckodriver-v0.18.0-win64//geckodriver.exe");
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
        driver.get("http://allthingsaboutuft.blogspot.in/");
        driver.manage().window().maximize();
         }


      @AfterClass
      public void afterClass() throws Exception
         {
          driver.quit();
         }

}

Friday 22 September 2017

SOAP UI – Automation using Groovy Scripting



SOAP UI – Automation using Groovy Scripting

 

groovy script in soapui examples, soapui global properties, script assertion in soapui examples, messageexchange groovy example soapui validate json response, contains assertion in groovy script, soapui groovy set property, property transfer in soapui using groovy, soapui properties

 


·        SaopUI is open source tool and there is also advanced version available i.e ReadyAPI which is licensed version.

·        Groovy scripting will be necessary if you are working with open version and little pinch is need in the ReadyAPI.

·        Here we will explore the Groovy Scripting which are necessary for SoapUI Automation.

·        In Groovy scripting most of the java libraries are included, henceforth all the functions and keywords can also be used in the Groovy scripting.

·        Groovy Scripting is dynamic language for the Java virtual machine, it is not a separate language. It is similar to java. There are no specific standards.     

·        It is loosely coupled language such as no need to mention the datatype, using “def” any variable can be defined

Comments in Groovy:


Single Line comment:

“// Sample Script”

Multiple Line Comment:

/*
Here we will see examples of Groovy
*/

Debugging:


log.info “debug”: This will print the string

Variable Declaration


def Auto = "Groovy Automation"
def day= 7
log.info Auto
log.info day
log.info "Number of days required to learn " + Auto + " is : " + day
log.info "Number of days required to learn  $Auto   is : $day"
Output:
INFO: Groovy Automation
 INFO: 7
INFO:Number of days required to learn Groovy Automation is : 7
INFO:Number of days required to learn  Groovy Automation   is : 7

Conditional Statements
IF Else:
if(day<=7)
{
               log.info "Completed"
}else
{
               log.info "Not Completed"
}

Output:
INFO:Completed

Assertion
Without the conditional statement too, the condition can be verified such as using the Assertion
assert day == 8 (Here the assertion will fail)

groovy script in soapui examples, soapui global properties, script assertion in soapui examples, messageexchange groovy example soapui validate json response, contains assertion in groovy script, soapui groovy set property, property transfer in soapui using groovy, soapui properties


assert day == 7 (Here the assertion will pass)


groovy script in soapui examples, soapui global properties, script assertion in soapui examples, messageexchange groovy example soapui validate json response, contains assertion in groovy script, soapui groovy set property, property transfer in soapui using groovy, soapui properties


For Loop
for(int K=0;K<=10;K++){
               log.info K
}

Note: without declaration, also this will work and with def also it will work

for(def K=0;K<=10;K++){
               log.info K
}

for(K=0;K<=10;K++){
               log.info K
}
Output:
INFO:0
INFO:1
INFO:2
INFO:3
INFO:4
INFO:5
INFO:6
INFO:7
INFO:8
INFO:9
INFO:10

While Loop
def K=0

while(K<=10){
               log.info K
               K++;
}
Output:
INFO:0
INFO:1
INFO:2
INFO:3
INFO:4
INFO:5
INFO:6
INFO:7
INFO:8
INFO:9
INFO:10

TestRunner Variables
We can create testrunner variables for the Test case, Test suite and project level and these can be obtained using the below methods.
Note: These methods will work only in groovy script
// Create a variable in TestCase-TestRunner variable and set and a value to it and get it
testRunner.testCase.setPropertyValue( "UID", "Sekar.Vadivel" )


groovy script in soapui examples, soapui global properties, script assertion in soapui examples, messageexchange groovy example soapui validate json response, contains assertion in groovy script, soapui groovy set property, property transfer in soapui using groovy, soapui properties


//Get the TestCase-Custom variable
def UID = testRunner.testCase.getPropertyValue( "UID" )
log.info UID
Output:
INFO:Sekar.Vadivel

// Create a variable in TestSuite-TestRunner Variable and set and a value to it and get it
testRunner.testCase.testSuite.setPropertyValue( "UID-TS", "Sekar.Vadivel_TS" )


groovy script in soapui examples, soapui global properties, script assertion in soapui examples, messageexchange groovy example soapui validate json response, contains assertion in groovy script, soapui groovy set property, property transfer in soapui using groovy, soapui properties


//Get the TestSuite-TestRunner variable
def TS = testRunner.testCase.testSuite.getPropertyValue( "UID-TS" )
log.info TS
Output:
INFO: Sekar.Vadivel_TS

// Create a variable in Project Variable and set and a value to it and get it
testRunner.testCase.testSuite.project.setPropertyValue( "UID-PJ", "Sekar.Vadivel_PJ" )


groovy script in soapui examples, soapui global properties, script assertion in soapui examples, messageexchange groovy example soapui validate json response, contains assertion in groovy script, soapui groovy set property, property transfer in soapui using groovy, soapui properties


//Get the Project-TestRunner variable
def PJ = testRunner.testCase.testSuite.project.getPropertyValue( "UID-PJ" )
log.info PJ
Output:
INFO: Sekar.Vadivel_PJ

//Global Properties
com.eviware.soapui.SoapUI.globalProperties.setPropertyValue( "UIDG", "Global" )
def globalProperty = com.eviware.soapui.SoapUI.globalProperties.getPropertyValue( "UIDG" )
log.info globalProperty
Output:
INFO: Global
Note: This will work both in Groovy script as well as in Script assertion

MessageExchange variable
Note: This will work only in Script Assertion

//TestSuite Message exchange variable
messageExchange.modelItem.testStep.testCase.testSuite.setPropertyValue( "UID-TS-SA", "Script Assertion" )
 def UID = messageExchange.modelItem.testStep.testCase.testSuite.getPropertyValue( "UID-TS-SA" )
log.info UID

Output:
INFO: Script Assertion
Similarly these can be used for test case and project

Tuesday 19 September 2017

The mouse-over using JavascriptExecutor and Actions in Selenium Webdriver

 
mouse hover using javascript, mouseover and click in selenium webdriver using javascript, javascript code for mouseover in selenium, mouseover in selenium webdriver, selenium hover over element and click, movetoelement javascript, action interface in selenium

 

JavascriptExecutor:

In selenium JavascriptExecutor is an interface.

This is available in org.openqa.selenium.JavascriptExecutor  and provides mechanism to execute Javascript through selenium driver.

It provides “executescript” to run JavaScript in current frame or window.

We can use JavascriptExecutor to perform actions such as mouse-over, click and get title of browser etc.. using selenium Webdriver.

mouse hover using javascript, mouseover and click in selenium webdriver using javascript, javascript code for mouseover in selenium, mouseover in selenium webdriver, selenium hover over element and click, movetoelement javascript, action interface in selenium

Actions:

Through Actions special keyboard and mouse events are done such as moveToElement(toElement), keyUp(modifier _key) and doubleClick() etc..

The bellow example demonstrates both JavascriptExecutor and Actions

Sample Code:

package com.p1;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
   
public class MouseHoverByJavaScript {
   
   
    public static void main(String[] args) {
        WebDriver driver;
       
         System.setProperty("webdriver.gecko.driver", "C://Selenium//geckodriver-v0.18.0-win64//geckodriver.exe");
         driver=new FirefoxDriver();
         driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
         driver.get("https://www.ebay.com/");
         driver.manage().window().maximize();

         try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
         //Object for the MenuItem 'Electronics'
         WebElement ele=driver.findElement(By.xpath(".//*[@id='s0-container']/li[6]/a"));
       
         //Object for JavascriptExecutor
         JavascriptExecutor jse = (JavascriptExecutor) driver;
       

         try {
           
            //Highlight the menu item 'Electronics' in green color using the JavaScript
           
            jse.executeScript("arguments[0].style.border='4px groove green'", ele);
           
            //Perform Mouse-Over    on menu item 'Electronics'    using javascript   
            String mouseOverScript = "if(document.createEvent)"
                    + "{"
                        + "    var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover',true, false); arguments[0].dispatchEvent(evObj);"
                    + "} "
                    + "else if(document.createEventObject) "
                    + "{ "
                        + "    arguments[0].fireEvent('onmouseover');"
                    + "}";
            jse.executeScript(mouseOverScript, ele);
           
            //Click the menu item 'Electronics' using the JavaScript
            jse.executeScript("arguments[0].click();", ele);
           
        }
         catch (Exception e) {
            e.printStackTrace();
        }
       
         driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
       
         //Navigating to the Home page
         driver.findElement(By.xpath(".//*[@id='bc']/li[1]/a")).click();
       
         driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
       
         //Object for the MenuItem 'Motors'
         WebElement mot=driver.findElement(By.xpath(".//*[@id='s0-container']/li[4]/a"));
       
         //Highlight the menu item 'Motors' in red color
         jse.executeScript("arguments[0].style.border='4px groove red'", mot);
       
       
        try {
            //Perform Mouse-Over on menu item 'Motors' using Actions
            Actions action = new Actions(driver);
            action.moveToElement(mot).build().perform();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
       
         try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
       
        driver.close();


    }

}

Friday 7 July 2017

Selenium - Optional in Java 8--Streams filter(), findAny(), Maps and orElse() with compound conditions

Selenium java 8 optional, java optional if present, Optional isPresen,t and ifPresent, optional found.orElse, Optional findFirst(), max(), min(), Streams filter(), findAny(), Maps and orElse() with compound conditions


Selenium - Optional in Java 8


  • When Optional is used there will be no need for “Null Checks” and “NullPointerException” at run-time will not occur.
  • It may contain a value or it will be empty.
  • Optional Stream API contain methods such as “findAny”, “findFirst”, “max” and “min”
  • In selenium it will be used in scenarios such as the “DropDownBox” or “ListBox”



Prerequisite:


package streamFilters;

 public class Student {

    private String student;
    private int id;
    public int result2;

    public Student(String student, int id) {
        this.student = student;
        this.id = id;
    }

       public String getStudent() {
              return student;
       }

       public void setStudent(String student) {
              this.student = student;
       }

       public int getId() {
              return id;
       }



       public void setId(int id) {
              this.id = id;
       }

}


1. Optional Examples

package streamFilters;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class OptionalEg{

       public static void main(String[] args) {

               List<Student> students = Arrays.asList(
                       new Student("Kellby", 4),
                       new Student("rose", 5),
                       new Student("warner", 8),
                       new Student("RVS", 3),
                       new Student("SS", 13)
               );


               // Optional isPresent and ifPresent

               Optional<Student> result1 = students.stream().filter(x -> "RVS".equals(x.getStudent())).findAny();
               Optional<Student> result2 = students.stream().filter(y -> "SS".equals(y.getStudent())).findAny();
               Optional<String> result3 = Optional.empty();

               if (result1.isPresent()) {
                   System.out.println("Student name: "+ result1.get().getStudent()+" "+"Student ID: "+ result1.get().getId());

               } else {
                   System.out.println("Value not available.");
               }

                result1.ifPresent(g -> System.out.println("Student name: " +result1.get().getStudent()+ " "+"Student ID: " +result1.get().getId()));


               // E.g. found.orElse

                  String st1 = result1.orElse(new Student("No value",0)).getStudent();
                  String st2 = result2.orElse(new Student("No value",0)).getStudent();

                  System.out.println("The matched name is: "+st1);
                  System.out.println("The matched name is: "+st2);

           // If input value is empty o/p value would be empty

           System.out.println(result3.orElse("<Empty>"));            

             

           // Compound Conditions
     
           Optional<Student> result5 = students.stream().filter((z) -> "RVS".equals(z.getStudent()) && 3 == z.getId()).findAny();
           result5.ifPresent(g -> System.out.println("Student name: " +result5.get().getStudent()+ " "+"Student ID: " +result5.get().getId()));
   

              // E.g findFirst(), max(), min()

              Optional<Student> result4 = students.stream().findFirst();        
             System.out.println("First Student Name: "+ result4.get().getStudent() +" "+"First Student ID: "+ result4.get().getId());

           Optional<Student> max = students.stream().max(comparing(students));
           System.out.println("The Max student ID: " + max.get().getId());        

           Optional<Student> min = students.stream().min(comparing(students));
           System.out.println("The Min student ID: " + min.get().getId());        

       }

       private static Comparator<? super Student> comparing(Object object) {
              Comparator <Student> comparator = (p1, p2) -> Integer.compare(p1.getId(), p2.getId());
              return comparator;
       }

}

Output:

Student name: RVS Student ID: 3

Student name: RVS Student ID: 3

The matched name is: RVS

The matched name is: SS

<Empty>

Student name: RVS Student ID: 3

First Student Name: Kellby First Student ID: 4

The Max student ID: 13

The Min student ID: 3


2. Optional Map


package streamFilters;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class FilterMap {

       public static void main(String[] args) {

        List<Student> students = Arrays.asList(
                new Student("Kellby", 4),
                new Student("rose", 5),
                new Student("warner", 8),
                new Student("RVS", 3),
                new Student("SS", 13)
        );


        // Optional isPresent and ifPresent

        Optional<String> result1 = students.stream().filter(x -> "RVS".equals(x.getStudent())).map(Student::getStudent).findAny();
        Optional<Integer> result2 = students.stream().filter(y -> "RVS".equals(y.getStudent())).map(Student::getId).findAny();
        Optional<String> result3 = Optional.empty();

       

        if (result1.isPresent()) {
            System.out.println("Student name1: "+result1+" "+"Student ID: "+result2);
        } else {
            System.out.println("Value not available.");
        }    

        result1.ifPresent(g -> System.out.println("Student name1: "+result1+" "+"Student ID: "+result2));    


        // E.g. found.orElse      

        System.out.println("The matched name is: "+ result1.orElse("<Empty>") + "  Name would be Empty if value not matched");
        System.out.println("The matched id is: "+ result2.orElse(1) + "  Id would be one if value not matched");

        // As input value is empty o/p value would be empty

        System.out.println("When Empty object is pass: " + result3.orElse("<Empty>"));

        // E.g findFirst(), max(), min()

     
        Optional<String> result4 = students.stream().map(Student::getStudent).findFirst();
        Optional<Integer> result5 = students.stream().map(Student::getId).findFirst();
        System.out.println("First Student name: "+ result4 + "First Student id: "+ result5);

        Optional<Student> max = students.stream().max(comparing(students));
        System.out.println("The Max student ID: " + max.map(Student::getId));

        Optional<Student> min = students.stream().min(comparing(students));
        System.out.println("The Min student ID: " + min.map(Student::getId));  

    }    

       private static Comparator<? super Student> comparing(Object object) {
              Comparator <Student> comparator = (p1, p2) -> Integer.compare(p1.getId(), p2.getId());
              return comparator;
       }

}

Output:

Student name1: Optional[RVS] Student ID: Optional[3]

Student name1: Optional[RVS] Student ID: Optional[3]

The matched name is: RVS  Name would be Empty if value not matched

The matched id is: 3  Id would be one if value not matched

When Empty object is pass: <Empty>

First Student name: Optional[Kellby]

First Student id: Optional[4]

The Max student ID: Optional[13]

The Min student ID: Optional[3]