Sunday, November 8, 2015

Performing drag-and-drop operation

In Selenium WebDriver, dragAndDrop method available in Actions class. Actions class supports all advanced user interactions such as firing mouse and keyboard events on a web page.

Below is the sample logic to perform drag and drop operation on a page using Actions class.

Logic

    WebElement elementToDrag = driver.findElement(By.id("DragThis"));
    WebElement elementToDropAt = driver.findElement(By.id("DropHere"));
  
    Actions action = new Actions(driver);
    action.dragAndDrop(elementToDrag, elementToDropAt).perform();


dragAndDrop method in actions class accepts two parameters as input. One is the element to drag and another one is the destination to drop element.


Related Topic
Advanced User Interactions API

Saturday, November 7, 2015

Reading CSV, XLS files using java

 A CSV is a comma separated values file, which allows data to be saved in a table structured format. If we get each row stored in csv file as array we can easily get the required values using index.

There is one open-source jar to parse csv file which will make our job so simple

opencsv

opencsv is a simple CSV Parser for Java under a commercial-friendly Apache 2.0 license. Download it from below location.

OpenCSV : Download



jxl

JExcelApi is a java library which provides the ability to read, write, and modify Microsoft Excel spreadsheets.
JXL ; Download

After downloading the jars, include it in your classpath.
In Eclipsr IDE,
  • Right click on project
  • Build Path => Configure build path..

  • Libraries => Add External jar => Select the above downloaded jar file
  • Click Ok. Now It is ready to use in your eclipse.

Here is the content of my csv file & xls file



Here is the Java Code to read csv, xls files.

import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import com.opencsv.CSVReader;

public class FileReading {
 
    public static void main(String[] args){
  
        System.out.println("=====XLS=====");
        List xls=getRowsFromXLSFile("/home/test/Contacts.xls");
        for(String eachRow[]:xls) {
            System.out.println(Arrays.toString(eachRow));
        }
        
       System.out.println("=====CSV=====");
       List csv=getRowsFromCSVFile("/home/test/Contacts.csv");
       for(String eachRow[]:csv) {
           System.out.println(Arrays.toString(eachRow));
       }
    }
    
     /**
     * Method to read all rows from csv file using opencsv
     * @param path filePath
     * @return list of String arrays
     */
    public  static List getRowsFromCSVFile(String path)
    {
         List list=new LinkedList();
        try
        {
            CSVReader csvReader = new CSVReader(new FileReader(new File(path)));
            list = csvReader.readAll();
        }
        catch(Exception e)
        {
           e.printStackTrace();
        }
        return list;
    }
     /**
     * Method to read all rows from xls file using jxl
     * @param path filePath
     * @return list of String arrays 
     */
    public static List getRowsFromXLSFile(String path) // Print and get
    {
     List rows=new LinkedList();
     try
     {
         File inputWorkbook = new File(path);
         Workbook workbook = Workbook.getWorkbook(inputWorkbook);
         Sheet sheet = workbook.getSheet(0);
         int maxCols=sheet.getColumns();
         int maxRows=sheet.getRows();
   
      for(int i=0;i<maxRows;i++) {
         String erows[] = new String[maxCols];
         int k=0;
         for(int j=0;j<maxCols;j++) {
             Cell cell1 = sheet.getCell(j,i);
             erows[k]=cell1.getContents();
             k++;
         }
         rows.add(erows);
     }
    } catch(Exception e){
         e.printStackTrace();
    }
    return rows;
  }
}

//Here is output for above file
=====XLS=====
[Name, email, phone]
[Jhon, Jhon@test.com, 234789234]
[Smith, Smith@test.com, 234728934]
[Jack, jack@test.com, 234234234]
=====CSV=====
[Name, email, phone]
[Jhon, Jhon@test.com, 234789234]
[Smith, Smith@test.com, 234728934]
[Jack, jack@test.com, 2394728394]


Sending mail from Gmail using WebDriver

Gmail is the mostly used mail client. Here is the logic to send a mail from gmail using WebDriver.


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

import java.util.concurrent.TimeUnit;

public class SendMailFromGmail {

 
 public static void main(String[] args) {
  
  String userName="<User name>";
  String password ="<password>";
  String toAddress="san******@***.com";
  String subject="WebDriver - Selenium Testing";
  
  //Initialising driver
  WebDriver driver = new FirefoxDriver();
  
  //setting timeout for page load & implicit wait
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
  
  //Call Url in get method
  driver.get("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/&hl=en");
  
  //Login
  driver.findElement(By.id("Email")).sendKeys(userName);
  driver.findElement(By.id("Passwd")).sendKeys(password);
  driver.findElement(By.id("signIn")).click();
  
  //click on Compose button
  driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
  
  
  //enter TO address & Subject
  driver.findElement(By.xpath("//*[text()='To']/../../..//textarea")).sendKeys(toAddress);
  driver.findElement(By.name("subjectbox")).sendKeys(subject);
  
  //click Send button
  driver.findElement(By.xpath("//div[text()='Send']")).click();
  
  //Logout from Gmail
  driver.findElement(By.xpath("//a[contains(.,'"+userName+"')]")).click();
  driver.findElement(By.xpath("//div[contains(.,'Add account')]//a[contains(text(),'Sign out')]")).click();
  
 }
 
}

Browser methods in WebDriver

WebDriver, The main interface to use for testing, which represents an idealised web browser. The methods in this class fall into three categories:

  1. Control of the browser itself
  2. Selection of WebElements
  3. Debugging aids

Key methods are get(String), which is used to load a new web page, and the various methods similar to findElement(By), which is used to find WebElements. In this post we are going to learn browser controlling methods.

get

void get(java.lang.String url)

Load a new web page in the current browser window. This is done using an HTTP GET operation, and the method will block until the load is complete. it is best to wait until this timeout is over, since should the underlying page change whilst your test is executing the results of future calls against this interface will be against the freshly loaded page.

      Usage

//Initialising driver
 WebDriver driver = new FirefoxDriver();
 
 //setting timeout for page load
 driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
 
 //Call Url in get method
 driver.get("https://www.google.com");
 //or
 driver.get("https://seleniumhq.org");

getCurrentUrl

java.lang.String getCurrentUrl()

Get a string representing the current URL that the browser is looking at. It returns the URL of the page currently loaded in the browser.

Usage

//Getting current url loaded in browser & comparing with expected url
 String pageURL = driver.getCurrentUrl();
 Assert.assertEquals(pageURL, "https://www.google.com");

getTitle

java.lang.String getTitle()

It returns the title of the current page, with leading and trailing whitespace stripped, or null if one is not already set.

Usage

//Getting current page title loaded in browser & comparing with expected title
 String pageTitle = driver.getTitle();
 Assert.assertEquals(pageTitle, "Google");

getPageSource

java.lang.String getPageSource()

Get the source of the last loaded page. If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page.

Usage

//get the current page source
     String pageSource = driver.getPageSource();

close

void close()

Close the current window, quitting the browser if it's the last window currently open. If there are more than one window opened with that driver instance this method will close the window which is having current focus on it.

Usage

//Close the current window
     driver.close();

quit


void quit()

Quits this driver, closing every associated window. After calling this method we can not use any other method using same driver instance.

Usage

//Quit the current driver session / close all windows associated with driver
     driver.quit();


These are all very useful methods available in Selenium 2.0 to control browser as required. 

Saturday, October 31, 2015

Selenium IDE Interview Questions - I


  1. What is Selenium IDE?
    Answer : Selenium IDE is a firefox  plug-in which is used to record and playback tests in firefox browser only.
  2. Can we see description of commands used in Selenium IDE?
    Answer : Yes, we can see description of commands in Reference area.

  3. How to handle JavaScript alert in Selenium IDE?
    Answer : By using verify/assertAlert we check the presence of an alert
  4. Can we generate WebDriver code from Selenium IDE?
    Answer : Yes, We can.

Program to remove duplicate numbers

Write a program to remove duplicate numbers from given array.


public class RemoveDuplicateNumbers {

  public static void main(String a[]){
         int[] input1 = {2,3,6,6,8,9,10,10,10,12,12};
         int[] output = removeDuplicates(input1);
         for(int i:output){
             System.out.print(i+" ");
         }
     }

 private static int[] removeDuplicates(int[] input) {
   int j = 0;
         int i = 1;
         //return if the array length is less than 2
         if(input.length < 2){
             return input;
         }
         while(i < input.length){
             if(input[i] == input[j]){
                 i++;
             }else{
                 input[++j] = input[i++];
             }    
         }
         int[] op = new int[j+1];
         for(int k=0; k<op.length; k++){
             op[k] = input[k];
         }
         return op;
 }
}

Write a program to remove duplicate characters from array

public class RemoveDuplicateChars {

 public static void main(String[] args) {
  char c[]={'a','b','g','c','d','e','a','f','c','g'};
  RemoveDuplicateChars obj = new RemoveDuplicateChars();
  obj.method1(c);
 }

 public void method1(char a[]) {
  String s=new String(a);
  String temp="";
  for(int i=0;i<s.length();i++) {
   String s1=s.substring(i, i+1);
   if(temp.contains(s1)) {
    continue;
   } else {
    temp+=s1;
   }
  }
  System.out.println(temp);
 }
}

Checking text on web page using WebDriver

While testing any web application, we need to make sure that it is displaying correct text under given elements. Selenium WebDriver provides a method to achieve this. We can retrieve the text from any WebElement using getText() method.

Example
Lets create a test that check for the proper text in flipkart menu tab.


Code:
@Test
public void testFlipkartMenuText() {
    //Get Text from first item and store it in String variable
    String electronics = driver.findElement(By.cssSelector("li[data-key='electronics']>a>span")).getText();

    //Compare actual & required texts
    assertEquals("Electronics",electronics);  
}


The WebElement class' getText() method returns value of the innerText attribute
of the element.

P.S : Given script may not work on flipkart site. I've written this code just to give some basic idea of using getText() method.

Locating elements using findElements methods





Selenium WebDriver provides the findElements() method, which returns List of WebElements with matching criteria. This method is useful when we want to do some operation with each element with same locator.

Examples

  • Get all links on a page
  • Get all buttons on page
  • Get all options from dropdown
  • Get all rows in table and td s from tr 

Let's create a test to check no of rows in given table.
@Test
public void testFindElements() {
  //Get all the tr from table
  List allTrs = driver.findElements(By.cssSelector("table[id='myContacts'] tr"));

  //verify there are 3 trs under given table
  assertEquals(3,allTrs.size());

  //Iterate all tr tags and print no of td tags in each tr tag
  for(WebElement eachTr : allTrs) {
    System.out.println(eachTr.findElements(By.tagName("td")).size());
  }
}

WebDriver Interview Questions - III


  1. How do you handle JavaScript alert using WebDriver?
    Answer : It can be handled using alert interface. Refer this post for further details.


  2. What is implicitwait & explicitwait?
    Answer: Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for.

    Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling  WebDriver at the max it is to wait for X units of time before it gives up.
       Refer this post


  3. Can I navigate browser forward & backward?
    Answer : Yes, we can. Using methods available in Navigate interface we can navigate back and forth in a page.
       Refer this post

  4. How about handling iframes?
    Answer : We must switch the control to iframe before doing any operation with the elements within iframe. We can use switchTo method to switch the control to frame.
    • driver.switchTo().frame("<frame name>");
    • driver.switchTo().frame(frame index);
    • driver.switchTo().frame(<WebElement>);

  5. How to handle new windows?
    Answer : Refer this post

  6. Can we execute JavaScript using WebDriver?
    Answer : Yes, we can. Refer this post

  7. How can you perform mouse operations using WebDriver?
    Answer :  Refer this post

  8. How can I check for an element presence?
    Answer : Refer this - Method-I , Method- II

  9. How do you select options from dropdown?
    Answer : Refer this post

  10. Can we capture screenshot when case failed?
    Answer : Yes, we can take screenshot. Refer this post

Related Topics
WebDriver Interview Question - I
WebDriver Interview Question - II



WebDriver Interview Questions - II


  1. What are all classes implementing WebDriver interface?
    Answer : All the following classes implemented WebDriver Interface. ChromeDriver, EdgeDriver, EventFiringWebDriver, FirefoxDriver, HtmlUnitDriver, InternetExplorerDriver, MarionetteDriver, OperaDriver, RemoteWebDriver, SafariDriver.

  2. What are all different methods available in WebDriver?
    Answer : Some of the most important methods available in webDriver are
    • close()
    • findElement(By by)
    • findElements(By by)
    • get(String url)
    • quit()
  3. How will get the title of window?
    Answer : We can get window title using "getTitle()" method with is declared in WebDriver.

  4. What is the return type of "findElement(By by)" method?
    Answer : WebElement. findElement method will return the WebElement found in that page based on specified locator. If no matching elements are found it throws NoSuchElementException

  5. How do you clear content of a text box?
    Answer : Using "clear" method on text box we can clear the content in that.
       Example : driver.findElement(By.id("username")).clear();

  6. What is the submit method in WebElement?
    Answer : If this current element is a form, or an element within a form, then this will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded.

  7. How will you get the text from below tag?
          <div name='myDiv'>Hello</div>
    Answer : We can get the text of any tag using getText() method on that element. In this case
             String text = driver.findElement(By.name("myDiv")).getText();

  8. How do you refresh the browser?
    Answer : driver.navigate().refresh();

  9. Can we make WebDriver to wait until elements loaded fully?
    Answer : Yes, We can make WebDriver to wait until all the elements/ required elements loaded fully with some timeout condition.

  10. How can I type my text in input box?
    Answer : Using sendKeys method we can type the required text in specified input box
       example : driver.findElement(By.id("coursename")).sendKeys("Selenium-Webdriver");


Related Posts
WebDriver Interview Questions - I



WebDriver Interview Questions - I


  1. What is Selenium 2.0 ?
    Answer : Selenium 2.0 is the integration of the WebDriver API & Selenium RC. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API.

  2. What are different languages it supports ?
    Answer : Automation scripts can be written using WebDriver in any of the following languages. java, C#, Python, Ruby, Perl, PHP

  3. Is WebDriver class or interface?
    Answer : WebDriver is an interface. WebDriver is the name of the key interface against which tests should be written, but there are several implementations.

  4. What are all different classes implemented WebDriver interface?
    Answer : WebDriver implementations include
    • HtmlUnitDriver
    • FirefoxDriver
    • InternetExplorerDriver
    • ChromeDriver
    • OperaDriver

  5. What is HtmlUnitDriver ?
    Answer : It is the fastest and most lightweight implementation of WebDriver. As the name suggests, this is based on HtmlUnit. HtmlUnit is a java based implementation of a WebBrowser without a GUI.

  6.  Which WebDriver implementation is the fastest ?
    Answer : HtmlUnitDriver. Because it executes the tests without launching the browser (headless)

  7. How to launch firefox browser using WebDriver?
    Answer : Using FirefoxDriver we can launcg firefox browser.
             WebDriver driver = new FirefoxDriver();  // this will launch firefox browser

  8. How will you load URL in browser?
    Answer : We can loan an URL in browser by calling "get" method
                  driver.get("http://www.google.com");

  9. Tell me about different types of element locators?
    Answer : By mechanism used to locate elements within a document.
            By.id("<Element ID>")
            By.name("<Element Name>");
            By.cssSelector("<css selector>");
            By.xpath("<element xpath>");
            By.linkText("<Full content of link text >");
            By.partialLinkText("<Partial content of link text>");

  10. Can we load URL without using "get" method?
    Answer : Yes, we can do using navigate() method.
                   driver.navigate().to("http://www.example.com");




Friday, October 23, 2015

Create and Delete Cookies with Selenium IDE

Create Cookie

Cookies can be created in Selenium-IDE using createCookie Method.





createCookie(nameValuePair, optionsString)
    Arguments:
   nameValuePair - name and value of the cookie in a format "name=value"
   optionsString - options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a subset of the current domain will usually fail.

    Create a new cookie whose path and domain are same with those of current page under test, unless you specified a path for this cookie explicitly.

Delete Cookie

Cookies can be deleted in Selenium-IDE using deleteCookie Method.



deleteCookie(name, optionsString)
    Arguments:
     name - the name of the cookie to be deleted
    optionsString - options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail.

    Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you need to delete it using the exact same path and domain that were used to create the cookie. If the path is wrong, or the domain is wrong, the cookie simply won't be deleted. Also note that specifying a domain that isn't a subset of the current domain will usually fail. Since there's no way to discover at runtime the original path and domain of a given cookie, we've added an option called 'recurse' to try all sub-domains of the current domain with all paths that are a subset of the current path. Beware; this option can be slow. In big-O notation, it operates in O(n*m) time, where n is the number of dots in the domain name and m is the number of slashes in the path.



Tuesday, October 20, 2015

Latest Selenium-Server-Standalone Jar




Selenium latest version jar is available now with many issues fixes. Java change log available here.





Released on : 09-Oct-2015
Version : 2.48
Download Link : Click Here

Released on : 30-Jul-2015
Version : 2.47
Download Link : Click Here

Released on : 04-Jun-2015
Version : 2.46
Download Link : Click Here





Friday, May 23, 2014

Selecting options from dropdown using partial text


    Selecting option(s) from dropdown is the one of the more frequent action while automating web application.

  I've written already detailed post for usage of Select class available in WebDriver. You can find that here.

 Here I'm going to write how to choose options using partial text or partial values.

HTML CODE
      <select id="city">
             <option value="City: Chennai">Chennai</option>
             <option value="City: Hyd">Hyderabad</option>
             <option value="City: Blore">Bangalore</option>
     </select>



Choose option using partial & full value

Select Chennai using its partial value.

driver.findElement(By.id("city")).findElement(By.cssSelector("option[value*='Chennai']")).click();

Select Chennai using its value

new Select(driver.findElement(By.id("city"))).selectByValue("City: Chennai");

Choose option using partial & full Text

Select Hyderabad using its partial text.

driver.findElement(By.id("city")).findElement(By.xpath("//option[contains(text(),'Hyd')]")).click();

Select Hyderabad using its text

new Select(driver.findElement(By.id("city"))).selectByVisibleText("Hyderabad");


Related Topics
Select options from dropdown
WebElement & Locators






Monday, October 14, 2013

Scroll Function in WebDriver

Sometimes we would like to scroll webpage to particular WebElement or press Keyboard DOWN button to scroll the page. We can achieve scroll pages with below code snippets. 

Scrolling Using javascript

Code :

       WebElement ele = driver.findElement(By.id("test"));
       ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView()",ele);

Using Actions Class

package name  : org.openqa.selenium.interactions.Actions

java code :

                          Actions action=new Actions(driver);
                          action.sendKeys(Keys.DOWN).perform();

Without Using Actions Class

java code :

                     driver.findElement(By.tagName("body")).sendKeys(Keys.DOWN);



Related Topics





Sunday, September 15, 2013

Executing javascript using WebDriver

  You can execute required javascript call using WebDriver in your automation code using JavaScriptExecutor.

Example
  • you may want to fire an event on a particular element. (calling blur event directly)
  • you may want to execute some script which will do some other operation. (instead of clicking directly call onclick targeted script)
Steps
  • Cast the WebDriver instance to JavaScriptExecutor 
  • Execute the script using executeScript() method
WebDriver-JavaScriptExecutor
Logic

WebDriver driver = new FirefoxDriver();
JavaScriptExecutor js=(JavaScriptExecutor)driver;  //casting driver instance
String title=(String)js.executeScript("return document.title");  //for getting window tile
String name=(String)js.executeScript("return window.name");  //for getting window name
js.executeScript("$('#elementId').blur()");  //firing blur event on an element


executeScript() will return java.lang.Object, from that you can get your required data.


 While returning values from the JavaScript code, need to use the return keyword. Based on the type of return value, need to type cast the executeScript() method.



  • For decimal values, Double can be used, 
  • for non-decimal numeric values Long can be used,  
  • for Boolean values Boolean can be used. 
  • JavaScript code is returning an HTML element, then WebElement can be used. 
  • For text values, String can be used. 
  • If a list of objects is returned, then any of the values will work based on type of objects. Otherwise, a null will be returned.


Related Topics
Handling JavaScript Alerts
Taking Screenshots

Browser Navigation Using WebDriver





Browser Navigation.

Browser navigation
Do you want to automate any browser action (Ex: forward, back, refresh) using WebDriver ?

Cases where we need this type of operations

  • You need to verify your web-application going to previous page if you click on browser back button.
  • Sometimes you may want to refresh the browser to complete some action.
Its pretty simple with WebDriver. Here is the logic to do browser navigation operations.

//TO perform browser back button action
driver.navigate().back();
//TO perform browser forward button action
driver.navigate().forward();

//To refresh bowser
driver.navigate().refresh();

//To navigate to particular URL
driver.navigate().to("url");
//You can give url in String or java.net.URL url format


I hope this would be helpful for beginners.


Regards,
SantoshSarma 


Related Topics
Selecting options from dropdown
Selecting options from dropdown using partial text


Handling JavaScript alerts using WebDriver

   It is very simple to handle javascript alerts in WebDriver. If we don't handle the alerts properly WebDriver will throw UnhandledAlertException .

Handling javascript alerts
  In web application mostly we see two types of pop-ups, 1. alerts 2. confirm popup




  Handling both alerts & confirms popup WebDriver has a Alert interface. Using WebDriver you can click on OK or Cancel button and also can get alert message also to verify.

Logic 

//First we need switch the control to alert.
       Alert alert = driver.switchTo().alert();

//Getting alert text
       alert.getText();

//Click on OK
       alert.accept();

//Click ok Cancel
      alert.dismiss();



I hope this would help you to handle javascript alerts.

Happy coding :)

Regards,
SantoshSarma


Related topics
Executing Java script using selenium


Saturday, September 14, 2013

Locating WebElements Using XPath







   In automation locating web elements in DOM is one of the important task. In DOM, if all the elements have unique ids then no problem but, if not we need to go for xpath for locating elements in DOM.

  Say for example generally we don't see any ids for the table rows & columns, in that case we need to locate table data using some other attributes. Ex: name, position, innerText.

  Below I'm writing simple example to understand the different options available in xpath. (Place mouseover the locator to see which element it will locate in table)

HTML Elements


Above html in browser

One Bike
Two Car
Three Bus
Four Jeep

Locating elements using Attributes

AttributeUsage
idBy.xpath("//table[@id='tableId']")
idBy.xpath("//td[@id='car']")
nameBy.xpath("//td[@name='Chk3']")


Locating Rows using index

RowAs a child As a sub-child
1By.xpath("//table[@id='tableId']/tbody/tr[1]")By.xpath("//table[@id='tableId']//tr[1]")
2By.xpath("//table[@id='tableId']/tbody/tr[2]")By.xpath("//table[@id='tableId']//tr[2]")
3By.xpath("//table[@id='tableId']/tbody/tr[3]")By.xpath("//table[@id='tableId']//tr[3]")
4By.xpath("//table[@id='tableId']/tbody/tr[4]")By.xpath("//table[@id='tableId']//tr[4]")

Locating Rows using functions

FunctionAs a child
position()By.xpath("//table[@id='tableId']//tr[position()=1]")
position()By.xpath("//table[@id='tableId']//tr[position()=3]")
last()By.xpath("//table[@id='tableId']//tr[last()]")
last()By.xpath("//table[@id='tableId']//tr[last()-1]")

Locating Rows using String functions

FunctionUsage
text()By.xpath("//table[@id='tableId']//tr/td[text()='One']")
contains()By.xpath("//table[@id='tableId']//tr/td[contains(text(),'hre')]")
starts-with()By.xpath("//table[@id='tableId']//tr/td[start-with(text(),'Fo')]")

Locating Columns using Xpath Axes

AxesUsage
childBy.xpath("//table[@id='tableId']//tr/child::td[text()='One']")
parentBy.xpath("//td[@id='car']/parent::tr")
preceding-siblingBy.xpath("//td[contains(@id,'bus')]/preceding-sibling::td/input")
following-siblingBy.xpath("//td[text()='Four']/following-sibling::td[@id='jeep']")
  • Child : Selects all children of the current node.
  • Parent : Selects the parent of the current node.
  • preceding-sibling:Selects all siblings before the current node.
  • following-sibling:Selects all siblings after the current node.

Happy Coding :)


Regards,
SantoshSarma



Friday, September 13, 2013

Generating Random Data





Generating Random Data
Say , you are running RecordCreate/FormFilling automation for 100 times.
  1. Passing every time same values (Hardcoded values)
  2. Passing randomly generated values from allowed characters
Which one is more reliable ? 

How will you verify forms by filling allowed max length values ?


Let's see how to fill the forms in web application with random & specified length values.

Consider below form

You want to fill below form with randomly generated values with specified lengths.

Register here

First Name
Last Name
Email
Phone
Income


See below testcase to know how can we pass random & specified length values to different fields.

RegistrationForm.java


package com.test.registration;

import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.test.general.GenerateData;

public class RegistrationForm {
 
 WebDriver driver;
 GenerateData genData;
 
 @Before
 public void before(){
  driver=new FirefoxDriver();
  genData=new GenerateData();
 }
 
 @Test
 public void testRegistrationForm() {
  driver.findElement(By.id("f_name")).sendKeys(genData.generateRandomAlphaNumeric(30));    
  driver.findElement(By.id("l_name")).sendKeys(genData.generateRandomString(20));
  driver.findElement(By.id("email")).sendKeys(genData.generateEmail(30));
  driver.findElement(By.id("skype")).sendKeys(genData.generateStringWithAllobedSplChars(30, "abc123_-."));
  driver.findElement(By.id("phone")).sendKeys(genData.generateRandomNumber(10));
  driver.findElement(By.id("income")).sendKeys(genData.generateRandomNumber(9));
  driver.findElement(By.id("submit")).click();
  assertEquals("Success", driver.getTitle());
 }
 
 @After
 public void after(){
  driver.quit();
 }

}




GenerateData.java


package com.test.general;

import org.apache.commons.lang3.RandomStringUtils;

public class GenerateData {

 public String generateRandomString(int length){
  return RandomStringUtils.randomAlphabetic(length);
 }
 
 public String generateRandomNumber(int length){
  return RandomStringUtils.randomNumeric(length);
 }
 
 public String generateRandomAlphaNumeric(int length){
  return RandomStringUtils.randomAlphanumeric(length);
 }
 
 public String generateStringWithAllobedSplChars(int length,String allowdSplChrs){
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    allowdSplChrs;
  return RandomStringUtils.random(length, allowedChars);
 }
 
 public String generateEmail(int length) {
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    "_-.";   //special characters
  String email="";
  String temp=RandomStringUtils.random(length,allowedChars);
  email=temp.substring(0,temp.length()-9)+"@test.org";
  return email;
 }
 
 public String generateUrl(int length) {
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    "_-.";   //special characters
  String url="";
  String temp=RandomStringUtils.random(length,allowedChars);
  url=temp.substring(0,3)+"."+temp.substring(4,temp.length()-4)+"."+temp.substring(temp.length()-3);
  return url;
 }
}
 

    While doing web application automation make a habit of passing random data with different lengths (<= Allowed max length) every time to improve reliability.


Related Topics
Generating Dynamic Dates