My Thoughts: FirefoxDriver
Showing posts with label FirefoxDriver. Show all posts
Showing posts with label FirefoxDriver. Show all posts

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




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;
   }
  } 
 }
}