My Thoughts: 2013

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..!! :)