TESTEVERYTHING

Sunday, 13 November 2016

WebDriver Event Listeners


WebDriver Event Listeners

Selenium WebDriver provides a very good framework for tracking the various events that happen while you're executing your test scripts using WebDriver. Many navigation events that get fi red before and after an event occurs (such as before and after navigating to a URL, before and after browser back-navigation, and so on) can be tracked and captured


How it works?
The Listeners use to listen for the events in the registered webdriver.  It can be any type of event or action. Say, page navigation, element click, changing values in a text field (analogy to javascript onXYZ () series methods) and even exceptions.
To enable this feature,
  1. Create our own user defined Event listener class
  2. Create an EventFiringWebDriverobject by means of webdriver instance,
  3. And register the Listener to the EventFiringWebDriver instance.
How to create your own event listener classes:
You can create a  event listener class in two ways, those are
  • By implementing WebDriverEventListener interface
  • By extending AbstractWebDriverEventListener class


The following fl ow diagram explains what has to be done to capture all of the events
raised by EventFiringWebDriver during the execution of test cases:



like
// Creating webdriver  instance
WebDriver driver = new FirefoxDriver();
// Creating  EventFiringWebDriver instance
EventFiringWebDriver eventFiringWD= new EventFiringWebDriver(driver);
// Creating instance of eventListener, that we just defined
EventListenerCreated EventListenerobj =new EventListenerCreated ();
// Register the Listener with the event firing driver
eventFiringWD.register(EventListenerobj );
eventFiringWD.get("https://www.google.co.in/");
eventFiringWD.findElement(By.className("nosuchclassName"));


Step 1- Create a new Class that will implement WebDriverEventListener methods

package testcases;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;

public class ActivityCapture implements WebDriverEventListener {
@Override
public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {
}
@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
System.out.println("After click "+arg0.toString());
}

@Override
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
System.out.println("After FindBy "+arg0.toString());
}
@Override
public void afterNavigateBack(WebDriver arg0) {
System.out.println("After navigating back "+arg0.toString());
}

@Override
public void afterNavigateForward(WebDriver arg0) {
System.out.println("After navigating forword "+arg0.toString());
}
@Override
public void afterNavigateTo(String arg0, WebDriver arg1) {
System.out.println("After navigating "+arg0.toString());
System.out.println("After navigating "+arg1.toString());
}
@Override
public void afterScript(String arg0, WebDriver arg1) {
}
@Override
public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {
}
@Override
public void beforeClickOn(WebElement arg0, WebDriver arg1) {
System.out.println("before click "+arg0.toString());
}
@Override
public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {
System.out.println("before FindBY "+arg0.toString());
}
@Override
public void beforeNavigateBack(WebDriver arg0) {
System.out.println("Before navigating back "+arg0.toString());
}
@Override
public void beforeNavigateForward(WebDriver arg0) {
System.out.println("Before navigating Forword "+arg0.toString());
}
@Override
public void beforeNavigateTo(String arg0, WebDriver arg1) {
System.out.println("Before navigating "+arg0.toString());
System.out.println("Before navigating "+arg1.toString());
}
@Override
public void beforeScript(String arg0, WebDriver arg1) {
}
@Override
public void onException(Throwable arg0, WebDriver arg1) {
System.out.println("Testcase done"+arg0.toString());
System.out.println("Testcase done"+arg1.toString());
}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------


package testcases;

import testcases.ActivityCapture;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;

public class ListnerDemo {

public static void main(String []args){

System.out.println("Started");

WebDriver driver=new FirefoxDriver();

EventFiringWebDriver event1=new EventFiringWebDriver(driver);

ActivityCapture handle=new ActivityCapture();

event1.register(handle);

event1.navigate().to("http://www.facebook.com");

event1.findElement(By.id("email")).sendKeys("asdsadsa");

event1.findElement(By.id("loginbutton")).click();

event1.quit();

System.out.println("End");
}

}




Thursday, 10 November 2016

Webdriver/Selenium Difference between methods .isDisplayed() and .isEnabled()?

Hi All,
I have seen so many posts where people asked the differences between .isDisplayed() and .isEnabled() in Selenium/Webdriver automation and found mostly people are still confused.
The methods .isDisplayed() and .isEnabled() have nothing in common.
 Here I am trying to explain the read differences between .isDisplayed() and .isEnabled(). As name itself clearly says .isDisplayed() means is my object are visible or not on my webpage means Am I able to see my element through my eyes.


Method .isDisplayed() :


An element is considered displayed when it is perceptually visible to the human eye.
The element displayed algorithm is a boolean state where true signifies that the element is displayed and false signifies that the element is not displayed.

To compute the state on element:
  • ·         If the attribute hidden is set, return false.
  • ·         If the computed value of the display style property is "none", return false.

Like
<input type="hidden" name="abc" value="10" id="hiddenFiled1" />

Observe the output, since element with id hiddenField1 is hidden from web page, so isDisplayed method return false, whereas isEnabled() method return true.



OR

Refer below link


Try to run with display: block;  and display: none;




Method .isEnabled() :


An element is considered enabled if it's not a form control (button, input, textarea, select or option) or when the user interactions and focus are not blocked with the disabled attribute/property.
Is Element Enabled determines if the referenced element is enabled or not. This operation only makes sense on form controls.

Like
Last name: <input type="text" name="lname" disabled><br>













Last name: <input type="text" name="lname" enabled><br>


 
Refer below link


Last name: <input type="text" name="lname" disabled><br>



Monday, 1 August 2016

XPath unable to find text with   or   using webdriver /

Hi,

Some times we face issues to create XPath of  WebElement which have space in starting of it and then we check the element html source where we found &nbsp; or &nbsp is added before the element text while it display as space on UI. Normally we create the XPath to identify this element by adding space in the starting of it but his will not identify the element. There are another workaround to identify this element by contains text method. But if we have to identify the element with exact text having starting space or ending space  then we can use following way to do this.

lets see this example

<div class="myclass">
<label>AgendaShowCapacity&nbsp;</label>
</div>

OR

<div class="myclass">
<label>
&nbspAgendaShowCapacity</label>
</div>

Following XPath will not work for this

//label[text()='AgendaShowCapacity&nbsp;'] doesn't work


Here we have to use following text to identify the element

&nbsp; = \u00a0

&nbsp = \u0160


So XPath will be like this


//label[text()='AgendaShowCapacity\u00a0']


//label[text()='
\u0160AgendaShowCapacity']

Friday, 22 July 2016

Available Android app of Testeverything Site

Hi,

Now you view the TestEverything Site updates on your Android mobile.just download the android app

Please refer the below link to download the apk file of  Teverything Site.

https://drive.google.com/file/d/0B27kZ9NQHijSQnJtc1RYdGVyR2M/view?usp=sharing

Download TesteveryThing APK file
TesteveryThing APK



Sunday, 3 July 2016

Scroll the WebGrid using selenium webdriver

Hi,

Sometimes in webpage there is web table grid present on page and we need to scroll the grid to access the element information. Because of asynchronous call data will not load completely until unless you scroll the grid.

From wiki..

Synchronous means that you call a web service (or function or whatever) and wait until it returns - all other code execution and user interaction is stopped until the call returns. Asynchronous means that you do not halt all other operations while waiting for the web service call to return
Here I have written the method that will scroll your grid until it reach to end of data row.

Note: ElementXpath will be your data table rows xpath
like  ElementXpath = "//table//tr";



public static void ScrollView(WebDriver driver,String ElementXpath) throws

Exception {

int elemntCountBeforeScroll= driver.findElements(By.xpath(ElementXpath)).size();

if (elemntCountBeforeScroll>0){


WebElement element = driver.findElements(By.xpath(ElementXpath)).get(elemntCountBeforeScroll-1);

JavascriptExecutor jse = (JavascriptExecutor) driver;

jse.executeScript("arguments[0].scrollIntoView(true);", element);

Thread.sleep(8000);


int elemntCountAfterScroll= driver.findElements(By.xpath(ElementXpath)).size();

for (int i = 0; i < elemntCountBeforeScroll; i++) {
if(elemntCountAfterScroll>elemntCountBeforeScroll)
{ elemntCountBeforeScroll = elemntCountAfterScroll;
 element = driver.findElements(By .xpath(ElementXpath)).get(elemntCountAfterScroll-1);
 jse = (JavascriptExecutor) driver;
 jse.executeScript("arguments[0].scrollIntoView(true);", element); 
Thread.sleep(8000);
elemntCountAfterScroll = driver.findElements(By .xpath(ElementXpath)).size(); }
}
}
}

Tuesday, 17 May 2016

Verify Broken Links

Verify Broken Links
Hi All,
Now we will learn how to validate broken links on page using WebDriver and java http methods. There are so many open source free tools available in market. Like Xenu we can validate the same but if we have to validate multiple web pages like >300 then it will be very tiresome task to enter each page URL.

Approach:

First we will open the webpage using web driver and get all the links having <A> tag. For finding the link URL, we will get the “href” property value of all the links present in webpage. In this way we will store the all the links URL present on webpage. We  have to exclude those links which having href property value like java script, hash(#) or mail to etc… because these links either referring to same page or refer to outlook mail like mail to link present in contact section.
Now we have the entire link’s URL, one way to open each URL using WebDriver but it is not advisable to use this approach because it will take too much time to perform. Instead of this we can use http method technique to test this. If my response code is 200 that means it is valid request else not. Note: Sometimes URL asks for certification acceptance, for handling this we are using SSL manager. For authentication URLs we can also use authentication methods

Below is the code where we getting the page URLs from excel sheet and validating the broken links. Results are saving in notepad.  Please do the modifications as per your need.

##################################################################

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrokenLinks {
 public static void main(String[] args) throws Exception {
  WebDriver driver = new FirefoxDriver();
  String urlxpath = "//a";
  List<WebElement> elements;
  Map<String, String> AllLinksURL = new HashMap<String, String>();
  Map<Integer, String> m = new HashMap<Integer, String>();
  try {
   // Open the Excel file
   FileInputStream fis = new FileInputStream(
     "D:\\url.xlsx");
   // Access the required test data sheet
   XSSFWorkbook wb = new XSSFWorkbook(fis);
   XSSFSheet sheet = wb.getSheet("url");
   // Loop through all rows in the sheet
   // Start at row 1 as row 0 is our header row
   File file = new File("Output.txt");
   // creates the file
   file.createNewFile();
   // creates a FileWriter Object
   FileWriter writer = new FileWriter(file);
   int i = 0;
   try {
    for (int count = 0; count <= sheet.getLastRowNum(); count++) {

     XSSFRow row = sheet.getRow(count);
     String page = row.getCell(0).toString();
     m.put(i, page);
     i++;
    }
   } catch (Exception e) {
    System.out.println(e);
   }
   fis.close();

   Collection<String> keyset = m.values();
   System.out.println(keyset);
   try {
    for (String page : keyset) {

     driver.get(page);
     Thread.sleep(5000);
     elements = driver.findElements(By.xpath(urlxpath));
     System.out.println(elements.size());
     // System.out.println(elements);
    
      for (WebElement ele : elements) {
       try {
        String temp = ele.getAttribute("href");
        // System.out.println(temp);

        if (temp != null) {
         if (!temp.contains("javascript")
           && (!temp.contains("tel://"))&& (!temp.contains("mailto:"))&& (!temp.equalsIgnoreCase("#")))
          
         AllLinksURL.put(temp, temp);

        }
       } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
     
     

     
      for (String urlVal : AllLinksURL.keySet()) {
       try {
        String res = check(urlVal);
        // System.out.println(res);
        if (!res.equals("OK")) {

         // Writes the content to the file
         writer.write(page + "\t" + urlVal + "\t" + res
           + "\n");
         writer.flush();

        }
       } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
      AllLinksURL.clear();

    }
   } catch (Exception e) {
    System.out.println(e);
   }
   writer.close();
  } catch (IOException e) {
   System.out.println(e);
   System.out.println("Url file not found");
  }
 }

 public static String check(String urlString) throws Exception {
  String response = "";
  TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
   public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return null;
   }

   public void checkClientTrusted(X509Certificate[] certs,
     String authType) {
   }

   public void checkServerTrusted(X509Certificate[] certs,
     String authType) {
   }
  } };

  // Install the all-trusting trust manager
  SSLContext sc = SSLContext.getInstance("SSL");
  sc.init(null, trustAllCerts, new java.security.SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

  // Create all-trusting host name verifier
  HostnameVerifier allHostsValid = new HostnameVerifier() {
   public boolean verify(String hostname, SSLSession session) {
    return true;
   }
  };

  // Install the all-trusting host verifier
  HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

  URL url = new URL(urlString);
  URLConnection con = url.openConnection();
  HttpURLConnection connection = (HttpURLConnection) con;
  connection.connect();

  response = connection.getResponseMessage();
  System.out.println("Response : " + response);
  connection.disconnect();
  return response;
 }
}


########################################################################
########################################################################

Wednesday, 16 March 2016

Webdriver | Implicit wait vs Explicit wait vs Fluentwait

Implicit Wait:
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));

When to use: Not recommended

Explicit wait:
An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully.

WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
WebDriver Explicit Waits
Explicit Waits

When to use: If element takes a long time to load. Also, used to check property of an element (presence, clickability. etc).

FluentWait:
For each FluentWait instance, you can specify:

  1. Frequency with which FluentWait has to check the conditions defined.
  2. Ignore specific types of exception waiting such as NoSuchElementExceptions while searching for an element on the page.
  3. Maximum amount of time to wait for a condition

When to use FluentWait: When you try to test the presence of an element that may appear after every x seconds/minutes (Just an example, this is my guess of where such a thing can be used).

// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function<WebDriver, WebElement>() 
{
  public WebElement apply(WebDriver driver) {
  return driver.findElement(By.id("foo"));
}
});

Difference Between Implicit, Explicit and Fluent Wait
Implicit Wait:
1.      During Implicit wait if the Web Driver cannot find it immediately because of its availability,
2.      The WebDriver will wait for mentioned time and it will not try to find the element again during the specified time period.
3.      Once the specified time is over, it will try to search the element once again the last time before throwing exception.
4.      The default setting is zero.
5.      Once we set a time, the Web Driver waits for the period of the WebDriver object instance.
Explicit Wait:
·         Suppose there is a scenario, when a particular element takes more than a minute to load.
·         In that case we would definitely not like to set a huge time to implicit wait, as if we do this, Browser will go to wait for the same time for every element.
In order to avoid such situation,
1.      Introduce a separate time on the required element only.
2.      By following this browser implicit wait time would be short for every element and it would be large for specific element.
Fluent Wait:
Scenario:  Suppose there is an element which takes some time to appear may be in just 1 second & some time it takes minutes to appear.
In that case it is better to use fluent wait,  1 .As this will try to find element again and again until it find it or until the final timer runs out.
Solutions: We always get confuse when it comes to using Wait commands, to better understand it we need to remember that there is a difference between several scenarios:
An element not being present at all in the DOM.
An element being present in the DOM but not visible.
An element being present in the DOM but not enabled. (i.e. clickable)
There are pages which get displayed with the JavaScript, the elements are already present in the browser DOM, but are not visible. The implicit wait only waits for an element to appear in the DOM, so it returns immediately, but when you try to interact with the element you get aNoSuchElementException. You could test this hypothesis by writing a helper method that explicit wait for an element to be visible or clickable.
public WebElement getWhenVisible(By locator, int timeout) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(driver, timeout);
element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
return element;
}
public void clickWhenReady(By locator, int timeout) { WebElement element = null; WebDriverWait wait = new WebDriverWait(driver, timeout); element = wait.until(ExpectedConditions.elementToBeClickable(locator)); element.click(); }

Translate







Tweet