My Thoughts

Thursday, March 6

On test case failure take a screenshot with Selenium WebDriver


Don't you think "A picture is worth a thousand words.." :)

It is always(at least in most of the cases :P) better to take screenshot of webpage when the test run fails.

Because with one look at the screenshot we can get an idea of where exactly the script got failed. Moreover reading screenshot is easier compare to reading 100's of console errors :P

Here is the sample code to take screenshot of webpage
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File("PathOnLocalDrive")

To get screenshot on test failure , we should put the entire code in try-catch block . In the catch block make sure to copy the above screenshot code.

In my example I am trying to register as a new user. For both first and last name fields I have used correct locator element whereas for emailaddress field I have used wrong locator element i.e name("GmailAddress1").

So when I run the script , test failed and I got the screenshot with pre filled first and last names but not email address.

Here is the sample code :
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TakeScreenshot {
 
   WebDriver driver;
 
 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void Test() throws IOException{
 try{
  driver.get("https://mail.google.com/");
  driver.findElement(By.id("link-signup")).click();
  driver.findElement(By.name("FirstName")).sendKeys("First Name");
  driver.findElement(By.name("LastName")).sendKeys("Last Name");
  driver.findElement(By.name("GmailAddress1")).sendKeys("GmailAddress@gmail.com");
  
 }catch(Exception e){
  //Takes the screenshot  when test fails
     File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
     FileUtils.copyFile(scrFile, new File("C:\\Users\\Public\\Pictures\\failure.png"));
   
  }
 }
}
And here is the screenshot of webpage on test failure


Reference  :
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#taking-a-screenshot
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/TakesScreenshot.html

Between have a great day ...!!! :)


Sunday, December 29

Configure browser proxy settings using Selenium WebDriver

Most of software testers are familiar with the term "Changing proxy settings" :P .
The only reason ( atleast for me :P ) we change browser proxy settings is to verify "multilingual" and "multi-regional" websites .
  • A multilingual website is any website that offers content in more than one language (Facebook) .
  • A multi-regional website is one that explicitly targets users in different countries (Bwin).

If business is happened to spread in multiple countries then website has to offer content in more than one language.But it is always not so easy to test "multi-regional" websites.Sometimes we have to change the proxy settings of browser to verify the functionality.

Say if you directly access the bwin.com from India then we will get redirecte to http://help.bwin.com/closed   and we will see the below page.


But if you access the same bwin.com site from United States then you will see the below page.


Manually if we want to test this functionality then we will get proxy server details from online and change our browser proxy settings , before accessing the site from our browser.

But if we want to verify the same functionality through automation , then we must know way using which we can modify the proxy server settings of browser . And here is the sample program to do that  :)
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ProxySettings {
 
  WebDriver driver;
    String serverIP=199.201.125.147;
String port=199.201.125.147;   

@BeforeTest
    public void setUpDriver() {
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("network.proxy.type",1);
    profile.setPreference("network.proxy.ftp",serverIP);
    profile.setPreference("network.proxy.http",serverIP);
    profile.setPreference("network.proxy.socks",serverIP);
    profile.setPreference("network.proxy.ssl",serverIP);
    profile.setPreference("network.proxy.ftp_port",port);
    profile.setPreference("network.proxy.http_port",port);
    profile.setPreference("network.proxy.socks_port",port);
    profile.setPreference("network.proxy.ssl_port",port);
    driver = new FirefoxDriver(profile);
    }
   
   
   @Test
   public void start() throws IOException{
    driver.get("https://www.bwin.com/");
    driver.findElement(By.id("username")).sendKeys("MyUserName");
    driver.findElement(By.id("password")).sendKeys("MyTestPassword");
    driver.findElement(By.name("submit")).click();
   }
   

}

And last but not the least  ,
Advance Happy New Year ..!! Have fun :)


Wednesday, November 27

Download a file using Selenium WebDriver with AutoIt Integration


Selenium can not handle file downloading because browsers use native dialogs for downloading files which cannot be controlled by JavaScript .

There are some third party tools using which we can automate download functionality.Some of the tools are AutoIt  and Sikuli.

I have used AutoIt for downloading file . If you want to use AutoIt script in your selenium script then
  1. Get an exe file of AutoIt script 
  2. Call the exe file from Selenium script 

1. Get .exe file of AutoIt script :

Here is the AutoIt Script for downloading a  file from website.This script takes one parameter as an input i.e the exact location from where we would like to download the file .And the  output (downloaded file) will be stored at C:\Users\Public\Downloads.

Save the below script with extension as Download.au3 and run it  then it will generate  Download.exe file

You can also download the .exe format of script from here .

#comments-start
InetGet ( "URL" ,"filename" , options , background)

>>URL URL of the file to download. The URL parameter should be in the form "http://www.somesite.com/path/file.html" - just like an address you would type into your web browser.

>>filename [optional] Local filename to download to. 

>>options [optional] 
0 = (default) Get the file from local cache if available.
1 = Forces a reload from the remote site.
2 = Ignore all SSL errors (with HTTPS connections).
4 = Use ASCII when transfering files with the FTP protocol (Can not be combined with flag 8).
8 = Use BINARY when transfering files with the FTP protocol (Can not be combined with flag 4). This is the default transfer mode if none are provided.
16 = By-pass forcing the connection online (See remarks). 

>>background [optional] 
0 = (default) Wait until the download is complete before continuing.
1 = return immediately and download in the background (see remarks). 

#comments-end


;Exact location of WebSite from where we would like to download the file.We are reading url from commandline
$URL =$CmdLineRaw 

;Local address to which we would like to download the file 
$filename = "C:\Users\Public\Downloads\Recognised_Student_Form.pdf"

InetGet ($URL, $filename , 1, 0)


2.Call the .exe file from Selenium script :

If you are using java then you can run the .exe file from your  selenium script using the below sample code:

Runtime.getRuntime().exec("Path of autoIt exe file");


Here is the Selenium code which will naviagte to the Oxford Application form .Then it will download  "Recognised Student 2013/14 - Application Form (230 kb)" file and save it at C:\Users\Public\Downloads with name as "Recognised_Student_Form.pdf".

import java.io.IOException;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FileDownload {
 
 WebDriver driver;
  
  @BeforeTest
   public void setUpDriver() {
    driver = new FirefoxDriver();
   }
  
  @Test
  public void start() throws IOException{
   driver.get("http://www.ox.ac.uk/admissions/postgraduate_courses/apply/application_forms.html");
   
   //Get the downloadable file location from the site with link name as "Recognised Student 2013/14 - Application Form (230 kb) "
   String href=driver.findElement(By.xpath(".//*[@id='aapplications_for_recognised_student_status']/div/ul/li[1]/a")).getAttribute("href");
   
   //Framing the command string which includes two parameters
   //Parameter 1-  Location where the Download.exe file is located
   //Parameter 2 - file location which we have stored in "href" variable 
   String command="Location where Download.exe file is saved"+" "+href;
   //If you happened to save Download.exe file  at "Public downloads" folder then command statement will be like 
      //String command="\"C:/Users/Public/Documents/Download.exe\""+" "+href;
   
      System.out.println("command is "+command);
      ArrayList argList = new ArrayList();
      argList.add(href);
      
      //Running the windows command from Java
      Runtime.getRuntime().exec(command);     
  }
  }
If you would like to verify the pdf content then check this article  ..!! :)



Saturday, October 5

Extract and Verify the text from image using Selenium WebDriver


Firstly WebDriver does not support the functionality of extracting text from an image , at least as of now  :) .
So if we would like to extract and verify text from an image then we should use OCR (Optical Character Recognition) technology.

Coming to OCR , here is one of the nice article , and it says :

OCR software extracts all the information from the image into easily editable text format.Optical character recognition (OCR) is a system of converting scanned printed/handwritten image files into its machine readable text format. OCR software works by analyzing a document and comparing it with fonts stored in its database and/or by noting features typical to characters. 

There are good no.of free OCR software tools . If your preferred program is Java then you can use one of the Java OCR libraries to extract text from an image. I used ASPRISE OCR java library in this article. To work with  ASPRISE OCR library , follow the below simple two steps.

  1. Download "Asprise OCR" libraries , depending on the operating system you are using .
  2. Unzip the downloaded  folder and add the aspriseOCR jar file to your working directory . If you want you can download the single jar file from here .
  3. Also Copy the "AspriseOCR.dll" file from unzipped downloaded folder and save it  under "C:\Windows\System32" .
Now you are ready to go  :P .

Look at the below sample image .



And here is the sample code to read the text from above image :

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.asprise.util.ocr.OCR;

public class ExtractImage {
 
 WebDriver driver;
 
 @BeforeTest
  public void setUpDriver() {
   driver = new FirefoxDriver();
  }
 
 @Test
 public void start() throws IOException{
   
 /*Navigate to http://www.mythoughts.co.in/2013/10/extract-and-verify-text-from-image.html page
  * and get the image source attribute
  *  
  */  
 driver.get("http://www.mythoughts.co.in/2013/10/extract-and-verify-text-from-image.html");
 String imageUrl=driver.findElement(By.xpath("//*[@id='post-body-5614451749129773593']/div[1]/div[1]/div/a/img")).getAttribute("src");
 System.out.println("Image source path : \n"+ imageUrl);

 URL url = new URL(imageUrl);
 Image image = ImageIO.read(url);
 String s = new OCR().recognizeCharacters((RenderedImage) image);
 System.out.println("Text From Image : \n"+ s);
 System.out.println("Length of total text : \n"+ s.length());
 driver.quit();
    
 /* Use below code If you want to read image location from your hard disk   
  *   
   BufferedImage image = ImageIO.read(new File("Image location"));   
   String imageText = new OCR().recognizeCharacters((RenderedImage) image);  
   System.out.println("Text From Image : \n"+ imageText);  
   System.out.println("Length of total text : \n"+ imageText.length());   
      
   */ 
}

}

Here is the output of the above program:

Image source path :
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgB6j3Yn6-LlRNqfQp1QvtINI0H9YbPfzY228Qmt72DdJhfy3h9ort0tySJcwdX9KVZGOzR8XHHrIIRo18_VpmMsn8LtZuYAn1ulTP48R2qZKtDIp3JNX5LlR8IAE0a2CC0GN4ZWXOy3qnV/s1600/love.jpg

Never M2suse the O, ne
Who Likes You
Never Say Busy To Th,e One
Who Needs You
Never cheat The One
Who ReaZZy Trust You,
Never foJnget The One
Who Zways Remember You.

Length of total text :
175



Thats for now. Have a great weekend ..!! :)

Reference :
http://asprise.com/product/ocr/javadoc/index.html




Saturday, September 21

org.openqa.selenium.remote.SessionNotFoundException:Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones.

Sometimes when we are trying to load InternetExplorer from WebDriver we will get below error :


org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)

Command duration or timeout: 1.39 seconds
Build info: version: '2.34.0', revision: '11cd0ef', time: '2013-08-06 17:11:28'
System info: os.name: 'Windows 8', os.arch: 'amd64', os.version: '6.2', java.version: '1.7.0_09'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver 


This error is because of the security settings in IE. There is a permanent fix to this. :P

>> Open IE , then go to Tools>>Security tab .

>>Now either check or uncheck the "Enable Protected Mode" checkbox for all zones i.e Internet , Local internet, Trusted Sites, Restricted Sites.


We are done . Now start running your script , it will go great  without any issues :) 

Thursday, September 12

Seleinum Webdriver - Loading chrome browser with default extension

When we start chrome browser using webdriver then by default it will load with out any extensions. But we can also load chrome browser with some default extensions if we need . To do this we need to know .crx file path of chrome extension. Here are the steps to find out the .crx file path :

1.Open chrome browser and type chrome://extensions/ . Now note down the extension id that you would like to be loaded when your browser starts.

2.Check the "Developer Mode" checkbox.Now you will see "Pack Extension" button .

3.Go to Extenstion folder of chrome .You will see the list of other folders with unique id's. Go to folder with the id , which you got in Step 1. Go deep into the folder until you find the manifest.json file and then copy the location .
3.Click on "Pack Extension" button and enter the path of folder in which extension manifest.json file is located.

Click on Pack Extension button.

4.We will get confirmation alert which displays the path of .crx file of extension. Copy that path and use it in your script

Thats it. Now we are done with the .crx file path . Use that path in the below code to load chrome browser with the default extension.
import java.io.File;
	import org.openqa.selenium.WebDriver;
	import org.openqa.selenium.chrome.ChromeDriver;
	import org.openqa.selenium.chrome.ChromeOptions;
    import org.testng.annotations.Test;

	@Test
	public class Chrome {

		WebDriver  driver;  
		
		public void start(){	
			ChromeOptions options = new ChromeOptions();		
			options.addArguments("start-maximized");
			options.addExtensions(new File("CRX FILE PATH"));
			System.setProperty("webdriver.chrome.driver","PATH of chromedriver.exe");
			ChromeDriver driver = new ChromeDriver(options);
                        driver.get("http://mythoughts.co.in");		
		}
}

Referenes:
http://developer.chrome.com/extensions/packaging.html
http://www.chromium.org/user-experience/user-data-directory


Saturday, July 13

Verifying ToolTip information by enabling javascript in browser


These days most of websites are using the ToolTip to provide information to end user.

ToolTip(also known as ScrrenTip) will be visible to the user whenever he/she mouseovers on specific object and it just displays information about the object(button,textbox,link,image etc..).

These tooltips works only when javascript is enabled.

So automating tooltip involves :

  •  Verifying that tooltip presents when we mouse over on specific object 
  •  Verifying that the text that present in the tooltip is correct.
In this site  if you mouse over on "Download" link we will see a tooltip.

ToolTip Screenshot


Here is the program which will check the existence of tooltip and also the text present in the tooltip. In this program I have used HtmlDriver because it provides inbuilt methods for enabling and disabling of javascript.

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class HTMLdriver {
 public static void main(String args[]){
 
 HtmlUnitDriver driver = new HtmlUnitDriver();
 driver.setJavascriptEnabled(true);
 driver.get("http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/");
 WebElement element=driver.findElement(By.linkText("Download"));
 Actions builder = new Actions(driver);  // Configure the Action  
 Action mouseOver =builder.moveToElement(element).build(); // Get the action  
 mouseOver.perform(); // Execute the Action 
   if(driver.findElement(By.id("tooltip")).isDisplayed()){
    System.out.println("Tooltip is coming up fine");
    System.out.println("Here is the tool tip text : "+driver.findElement(By.id("tooltip")).getText());
   }else{
    System.out.println("There is no Tool tip text");
   }

 }
}

If you want to check the correctness of the program then disable javascript and run the program.In this case script will fail as tooltip failed to appear when we mouseover on Download link.
driver.setJavascriptEnabled(false);

Tuesday, April 9

Selecting a date from Datepicker using Selenium WebDriver


Calendars look pretty and of course they are fancy too.So now a days most of the websites are using advanced jQuery Datepickers instead of displaying individual dropdowns for month,day,year. :P

Datepicker

If we look at the Datepicker, it is just a like a table with set of rows and columns.To select a date ,we just have to navigate to the cell where our desired date is present.

Here is a sample code on how to pick a 13th date from the next month.
import java.util.List;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;;

public class DatePicker {

 WebDriver driver;
 
 @BeforeTest
 public void start(){
 System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");  
 driver = new FirefoxDriver();
 }
 
 @Test
 public void Test(){
 
  driver.get("http://jqueryui.com/datepicker/");
  driver.switchTo().frame(0);
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  //Click on textbox so that datepicker will come
  driver.findElement(By.id("datepicker")).click();
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  //Click on next so that we will be in next month
  driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();
  
  /*DatePicker is a table.So navigate to each cell 
   * If a particular cell matches value 13 then select it
   */
  WebElement dateWidget = driver.findElement(By.id("ui-datepicker-div"));
  List rows=dateWidget.findElements(By.tagName("tr"));
  List columns=dateWidget.findElements(By.tagName("td"));
  
  for (WebElement cell: columns){
   //Select 13th Date 
   if (cell.getText().equals("13")){
   cell.findElement(By.linkText("13")).click();
   break;
   }
  } 
 }
}


Tuesday, March 5

org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed.

If you running webdriver scripts on Windows 8 then the below error is the first one you will encounter. Atleast it happened for me :) .


org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: WIN8
Build info: version: '2.31.0', revision: '1bd294d', time: '2013-02-27 20:53:56'
System info: os.name: 'Windows 8', os.arch: 'amd64', os.version: '6.2', java.version: '1.7.0_09'
Driver info: driver.version: FirefoxDriver



The solution to the above problem is to specify the location of firefox in your script .
System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");

Here is my modified script.And it went through without any errors :)

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FacebookRegistration {

WebDriver driver;
 
 @BeforeTest
 public void start(){
  System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
  driver = new FirefoxDriver();
 }
 

 @Test
 public void run(){
  driver.get("http://facebook.com");
 }
}

Saturday, February 2

Executing javascript using Selenium WebDriver

Using webdriver sometimes we need to run javascript code dircetly from our script.

In one of the previous post we have discussed how to break catcha on webpage . To break captcha we need to run javascript code directly from our script .So it is important to know how to run javacript code using WebDriver. Here are the steps:

1.Cast the WebDrier instance to a  JavascriptExecutor
WebDriver driver;
JavascriptExecutor js = (JavascriptExecutor) driver;
2.Use executeScript method to run the script
js.executeScript("return document.title");
Here is the sample script using TestNG.
import java.util.ArrayList;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Reporter;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ExecuteJavascript {
	
 WebDriver driver;

 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void javaScriptExec(){
  
  driver.get("http://duckduckgo.com/");
  JavascriptExecutor js=(JavascriptExecutor) driver;
  
  String readyState=(String)js.executeScript("return document.readyState");
  System.out.println("readyState  : "+readyState);

  String title=(String)js.executeScript("return document.title");
  System.out.println("title  : "+title);
		  
  String domain=(String)js.executeScript("return document.domain");
  System.out.println("domain  : "+domain);
		  
  
  String lastModified=(String)js.executeScript("return document.lastModified");
  System.out.println("lastModified  : "+lastModified);
		  
  String URL=(String)js.executeScript("return document.URL");
  System.out.println("Full URL  : "+URL);

 String error=(String) ((JavascriptExecutor) driver).executeScript("return window.jsErrors");
  System.out.println("Windows js errors  :   "+error);
		   
   }

@AfterTest
 public void stop(){
 driver.quit();
 }

}
If you run the above program then the output will come like below :

readyState  : complete
title  : DuckDuckGo
domain  : duckduckgo.com
lastModified  : 02/02/2013 13:11:42
Full URL  : https://duckduckgo.com/
Windows js errors  :   null

Reference :

http://code.google.com/p/selenium/wiki/WebDriverJs#Getting_Started
http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_How_do_I_execute_Javascript_directly?
http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/JavascriptExecutor.html


Saturday, January 5

Maximize browser window using webdriver


There are times when we want to to maximize the browser window during the execution of our script .For this purpose webdriver providers a built-in method and here is the syntax :

WebDriver driver;
driver.manage().window().maximize();

Here is the sample code using TestNG framework. :
import java.awt.Toolkit;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Reporter;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class MaximizeWindow {

WebDriver driver;

@BeforeTest
public void setUpDriver() {
driver = new FirefoxDriver();
      }
  

@Test
public void maximize() {
 //declare varibales for windows
org.openqa.selenium.Dimension defaultDim;
org.openqa.selenium.Dimension maximizeDim;
//Load google website on browser
driver.get("http://google.com");
//Display the current screen dimensions
defaultDim=driver.manage().window().getSize();
System.out.println("screenHeight before maximizing"+defaultDim.getHeight());
System.out.println("screenWidth before maximizing"+defaultDim.getWidth());
//maximize the window using webdriver method
driver.manage().window().maximize();
//Display the maximized window dimensions
maximizeDim=driver.manage().window().getSize();
System.out.println("screenHeight after maximizing:"+maximizeDim.getHeight());
System.out.println("screenWidth after maximizing:"+maximizeDim.getWidth());

      }


  }
Last but not the least

Belated Happy New Year All..!!

Have fun..!! :)

Sunday, December 16

Sending special characters and key events to WebDriver using sendKeys() method

There are times at which we would like to send special characters (Enter , F5, Ctrl, Alt etc..) to webdriver from our script. This can be done by using sendKeys method itself. For this purpose we will use the Keys  method as parameter to the sendKeys method.

Syntax :
//Sending F5 key
driver.findElement(By.id("name")).sendKeys(Keys.F5);

//Sending arrow down key 
driver.findElement(By.id("name")).sendKeys(Keys.ARROW_DOWN);

//sending pagedown key from keyboard
driver.findElement(By.id("name")).sendKeys(Keys.PAGE_DOWN);

//sending space key 
driver.findElement(By.id("name")).sendKeys(Keys.SPACE);

//sending tab key
driver.findElement(By.id("name")).sendKeys(Keys.TAB);

//sending alt key
driver.findElement(By.id("name")).sendKeys(Keys.ALT);
We can also send the pressable keys as Unicode PUA(Privtae User Area)  format . So the above samples can be rewritten as below :
sendKeys(Keys.F5) == sendKeys("\uE035")

sendKeys(Keys.PAGE_DOWN) == sendKeys("\uE00F")

sendKeys(Keys.ARROW_DOWN) == sendKeys("\uE015")

sendKeys(Keys.SPACE) == sendKeys("\uE00D")

sendKeys(Keys.TAB) == sendKeys("\uE004")

sendKeys(Keys.ALT) == sendKeys("\uE00A")
Here is the sample program for logging into Facebook :
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Sendkeys {
 
WebDriver driver;
 
@BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }

@Test
public void sendkeysmethod(){
 //Load facebook login page
 driver.get("https://facebook.com");
 
 //Refresh the page 
 //We can also refresh like below 
 //driver.findElement(By.name("email")).sendKeys("\uE035")
 driver.findElement(By.name("email")).sendKeys(Keys.F5);
 
 //Fillup Emailadress and Password fields
 driver.findElement(By.name("email")).sendKeys("EmailAddress");
 driver.findElement(By.name("pass")).sendKeys("password");
 
 //Sending Enter key so that facebook login credentials will be authenticated
 driver.findElement(By.name("pass")).sendKeys(Keys.ENTER);
 
    }
}

Reference :

http://www.w3.org/TR/2012/WD-webdriver-20120710/#typing-keys
http://code.google.com/p/selenium/wiki/GettingStarted
http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/Keys.html

Monday, November 26

Automating(Breaking) captcha using Selenium Webdriver

Usually most of the companies either use their own captchas or one of the third party captchas(GooglejQuery plugins) in the user registration page of their sites .So these pages can't be automated fully.Infact Captcha itself is implemented to prevent automation. As per official captcha site

A CAPTCHA is a program that  protects  websites against bots  by generating and grading tests that humans can pass but current computer programs cannot.

Captchas are not brakeable but there are some third party captchas that can be breakable and one of the example for it is "jQuery Real Person" captcha . Here is the documentation  :)

Vamshi Kurra- Real Person Captcha


Here is the sample code to brake the "jQuery Real Person" Captcha using Selenium WebDriver.

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class captchaAutomtion { 
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void Test(){ 
  //Loading jQuery Real Person Captcha demonstration page
  driver.get("http://keith-wood.name/realPerson.html");
  JavascriptExecutor js = (JavascriptExecutor) driver;
  //Setting the captcha values
  js.executeScript("document.getElementsByName('defaultRealHash')[0].setAttribute('value', '-897204064')");
  driver.findElement(By.name("defaultReal")).sendKeys("QNXCUL");
  //Submit the form
  driver.findElement(By.xpath(".//*[@id='default']/form/p[2]/input")).submit(); 
 }

}

Do share some of the captcha plugins that can be breakable with me :P

org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

 I am using selenium 2.24 jar files.But today , I got below errors when I ran one of my sample script.
org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
*** LOG addons.manager: Application has been upgraded
*** LOG addons.xpi: startup
*** LOG addons.xpi: Skipping unavailable install location app-system-local
*** LOG addons.xpi: Skipping unavailable install location app-system-share
*** LOG addons.xpi: Ignoring file entry whose name is not a valid add-on ID: C:\Users\vkurra\AppData\Local\Temp\anonymous4553384920216924839webdriver-profile\extensions\webdriver-staging
*** LOG addons.xpi: checkForChanges
*** LOG addons.xpi-utils: Opening database
*** LOG addons.xpi-utils: Creating database schema
*** LOG addons.xpi: New add-on fxdriver@googlecode.com installed in app-profile
*** LOG addons.xpi: New add-on {972ce4c6-7e08-4474-a285-3208198ce6fd} installed in app-global
*** LOG addons.xpi: Updating database with changes to installed add-ons
*** LOG addons.xpi-utils: Updating add-on states
*** LOG addons.xpi-utils: Writing add-ons list
*** LOG addons.xpi: shutdown
*** LOG addons.xpi-utils: shutdown
*** LOG addons.xpi-utils: Database closed
*** LOG addons.xpi: startup
*** LOG addons.xpi: Skipping unavailable install location app-system-local
*** LOG addons.xpi: Skipping unavailable install location app-system-share
*** LOG addons.xpi: Ignoring file entry whose name is not a valid add-on ID: C:\Users\vkurra\AppData\Local\Temp\anonymous4553384920216924839webdriver-profile\extensions\webdriver-staging
*** LOG addons.xpi: checkForChanges
*** LOG addons.xpi: No changes found


Immidiate thing I have done is , selenium jars updation. I have downloaded latest selenium 2.25 jars and added them to my project buildpath. Now things are going smooth :)

Saturday, November 17

5 different ways to refresh a webpage using Selenium Webdriver

Here are the 5 different ways, using which we can refresh a webpage.There might be even more :)

There is no special extra coding. I have just used the existing functions in different ways to get it work. Here they are :

1.Using sendKeys.Keys method
driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);

2.Using navigate.refresh()  method
driver.get("https://accounts.google.com/SignUp");  
driver.navigate().refresh();

3.Using navigate.to() method
driver.get("https://accounts.google.com/SignUp");  
driver.navigate().to(driver.getCurrentUrl());

4.Using get() method
driver.get("https://accounts.google.com/SignUp");  
driver.get(driver.getCurrentUrl());

5.Using sendKeys() method
driver.get("https://accounts.google.com/SignUp"); 
driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");

See you in next post.

Have a great weekend..!!

Tuesday, November 13

Happy Diwali all..!!


May all your happiness light up and sorrows burn out. 
♥  Happy Diwali all..!!  





Monday, November 12

Null point exception while running webdriver script


Sometimes simple mistakes will take lot of time in debugging . I can bet on it :P
Today while runing a sample script I got errors like below :

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

Here is the script with syntax error:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class AutoComplete {
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){
 WebDriver driver = new FirefoxDriver();
 }
 
 @Test
 public void AutoComplete()
 {
 driver.get("http://mythoughts.co.in/");
 driver.manage().window().maximize();
 }

}


I just overlooked the above script and thought everything is fine. But the issue got fixed when I remove the "WebDriver" statement from the line 13 and script ran successfully.

Here is the script which ran successfully.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class AutoComplete {
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){
 driver = new FirefoxDriver();
 }
 
 @Test
 public void AutoComplete()
 {
 driver.get("http://mythoughts.co.in/");
 driver.manage().window().maximize();
 }

}


Sunday, October 14

WebDriver Tutorial Part 6 : Working with the different types of web elements

From the previous post , it was clear on how to identify the webelements on webpage. In this post we will see how to work with different webelemts.

By default , selenium defines predefined functions which we can use on different types of webelemts.
Here are some of the predefinied functions:

                driver.findElement(By.id("WebelemntId")).clear();
driver.findElement(By.id("WebelemntId")).isEnabled();
driver.findElement(By.id("WebelemntId")).isDisplayed();
driver.findElement(By.id("WebelemntId")).submit();
driver.findElement(By.id("WebelemntId")).sendKeys("test");
driver.findElement(By.id("WebelemntId")).isSelected();
driver.findElement(By.id("WebelemntId")).getAttribute("");
driver.findElement(By.id("WebelemntId")).getLocation();
driver.findElement(By.id("WebelemntId")).getTagName();
driver.findElement(By.id("WebelemntId")).getText();
driver.findElement(By.id("WebelemntId")).getSize();

All the functions canot be used for every webelement.

Say  "sendKeys()" method is sending text to a webelement .This method can be used with textboxes but we can't use it on images , links. These are all basic things which we will learn through experience.

Here are the samples , on how to achieve basic functionality of different webelements using webdriver functions:

Textboxes :Send text
Sending text to Textboxes can be done by using "sendKeys()" method. Here is how it works:
driver.findElement(By.id("textBoxId")).sendKeys("sending text");
RadioButtons :Select an option
Selecting an option from Radio button can be done by using "click()" method.Here is how it works:
driver.findElement(By.id("radioButtonId")).click();
Hyperlinks :Click on links
Clicking on link can be done by using "click()" method.Here is how it works:
driver.findElement(By.id("linkId")).click();
Checkboxes :Check the checkboxes
Selecting options from Checkboxes can be done by using "click()" method.Here is how it works:
driver.findElement(By.id("checkBoxId")).click();
Drop-down List :Select an option
Selecting an option from Dropdown list  can be done by using  "sendKeys()" method.Here is how it works:
driver.findElement(By.id("dropdownListId")).sendKeys("SelectOption1");
Textarea :Send text
Sending text to Textboxes can be done by using "sendKeys()" method.Here is how it works:
driver.findElement(By.id("textAreaId")).click();
Button :click on it.
Submitting button can be done by using either "click()" or "submit()" mrthods.Here is how it works:
driver.findElement(By.id("butonId")).click();
Below example is the working code for "submitting a form which has most of the webelements like textbox, textarea, radiobutton, checkboxe and dropdown list".
package blog;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class DocumentIdentifiers {
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){
 driver = new FirefoxDriver();
 }
 
 @Test
 public void ok(){
 driver.get("https://docs.google.com/spreadsheet/viewform?fromEmail=true&formkey=dGp5WEhMR0c1SzFTRFhmTjJNVk12T1E6MQ");
//Send text to firstname, lastname and email address fields
 driver.findElement(By.id("entry_0")).sendKeys("First Name");
 driver.findElement(By.id("entry_3")).sendKeys("Last Name");
 driver.findElement(By.id("entry_13")).sendKeys("Emailaddress");
//Setting value for Gender radiobutton
 driver.findElement(By.id("group_2_1")).click();
//Selecting values for "Your preferred Programming language" checkbox
 driver.findElement(By.id("group_5_1")).click();
 driver.findElement(By.id("group_5_2")).click();
 driver.findElement(By.id("group_5_3")).click();
//Setting value for "your Location" dropdown list
 driver.findElement(By.id("entry_6")).sendKeys("Non India");
//Giving the value for user rating radiobutton
 driver.findElement(By.id("group_7_3")).click();
//sending value to feedback textarea elemenet
 driver.findElement(By.id("entry_8")).sendKeys("Adding new comments ");
//Submitting the form
 driver.findElement(By.name("submit")).submit();   
 }
 
 @AfterTest
 public void close(){
 driver.quit();
 }
}

Starting from next post , I will concentrate more on live problems. See you all in next post ..!! :)

Between Advance happy dasara to you and your family. Have a great year ahead..!!:)

Sunday, September 2

WebDriver Tutorial Part 5 : Locating WebElemnts on the Webpage

Every webpage is nothing but the set of of different elments. So we need to have idea on the following things before we start building the script.
1.Knowing the different elements  on WebPage
2.Locating the elements on web page
3.Working wth the elemets

1. Knowing the different typesof  elements  on WebPage
By looking at the webpage we should be able to identify the type of element it consists.Sometimes we can check elements types by viewing the source code.Here are the common elements most of the time we encounter in the process of automation.
Text box 
Drop-down List
Checkbox
Radio button 
TextArea  
Hyperlink
Image
Button
Frames
Alert dialog box
Window

2.Locating the elements on web page 
Before starting let us have a look at the below sample form which consists of "First Name, Last name , Email address, Sex, Submit button".

First name:


Last name:


Email Address:


Your Sex :
Male
Female



Above form has 5 elements, three textboxes, one radio button and one submit button.We have successfully identified the elements type.Now we need to locate the elements on webpage using Selenium.

If we see the viewsource of "First Name" textbox , it will look like
<input id="firstname" maxlength="45" name="firstname" type="text" />

It means we can locate the "First Name" text box on the webpage using 4 different locators i.e  id, name, Xpath, CSS.
WebDriver driver=new FirefoxDriver()
WebElement textbox=driver.findElement(By.name("firstname"));
OR
WebElement textbox=driver.findElement(By.id("firstname")); 
We can easily get the Xpath and CSS values of an element using firefox addons like Firebug and  FirePath.

In selenium we can identify the elements on the webpage with the following locators.
Locating By Id 
Locating By Name
Locating By Xpath 
Locating Hyperlinks by LinkText
Locating By DOM
Locating By CSS

3.Working wth the elemets
Knowing the element type and locating the element is not what we actually want. We want to work with those elements to perform some action on the webpage say "locate the submit button on webpage and click on it".

In the next post , we will see how we can work with the different elements using selenium ...!! :)

Saturday, August 18

WebDriver Tutorial Part 4 : Working with TestNG framework in Eclipse


Writing a script in plain Java is simple like what we have done in the previous post. But there is more we can do using WebDriver.

Say If you want to run multiple scripts at a time ,better reporting and you want to go for datadriven testing (Running the same script with multiple data) then plain Java script is not enough .

So it is recommended to use any of the existing frameworks like TestNG or JUnit. Select one of the framework and start using it.

In this post , I start with TestNG. If you are planning to use TestNG then you need to
  • 1.Install TestNG Eclipse plug-in 
  • 2.Customize the output directory path
  • 3.Start writing scripts
1.Install TestNG Eclipse plug-in 

Detailed instruction on how to install TestNG plug-in can be found here

2.Customize the output directory path

This is not a mandatory step. But it is good to have it.Using this you can tell TestNG where to store all the output results files. 

In Eclipse Goto Window>>Preferences>>TestNG>>
Set the Output Direcory location as per your wish and click on "Ok".

Vamshi Kurra -TestNG

3.Start writing scripts
Writing scripts using TestNG is so simple. We will start with the editing of script we have written in the previous post .
Here is the edited script using TestNG.
package learning;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class GoogleSearchTestNG {

 WebDriver driver;
 
 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void Test(){ 
  System.out.println("Loading Google search page");
  driver.get("http://google.com");
  System.out.println("Google search page loaded fine");
 }
 
 @AfterTest
 public void close(){
  driver.quit(); 
 }
}

If you look at the above code the main chnages we have done is 
1.Imported new TestNG files

2.Now there is no main function.We removed it.

3.We have split the single main function into 3 functions. i.e start(), test(), close()
start()  -- Initialize the WebDriver
Test()  -- Perform our exact requirement.
close() -- Close the Browser once

4.There are 3 different annotations named "BeforeTest" , "Test" , "AfterTest".
@BeforeTest -- Keep this annotaion before a method which has to be called initially when you run the script. In our script ,we put it before start() method because we want to initialize the WebDriver first.
@Test    -- Keep this annotation before a method which will do the exact operation of your script.
@AfterTest -- Keep this annotation before mehod which has to run at the end. In our script , closing browser has to be done at the end. So we put this annotation before close() method.

TestNG is so powerful . But now we stop here :) and experiment more on WebDriver functions. Once that is done we will come back to TestNG.

Can't wait and learn more ?? , you can always refer documents here

Going forward all the example scripts in this site will refer to TestNG.