My Thoughts: 2012

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.

Sunday, August 12

WebDriver Tutorial Part 3 :Writing first script using Webdriver

If you have missed the previous post then you can have a look at here .

Now we are ready to start our first script in Webdriver using Eclipse .Open your Eclipse and follow the below steps

1.Create new Java Project
2.Add the Webdriver Jar files to the created Project
3.Create a new Package under Java Project
4.Create a Java class file under the Package
5.Write the code in the Java class file and run it.

1. Create a new Java project

Goto File >> New >>Java Project
We will get a popup which will prompt us to provide the project name.
Give the project name say "ExploreWebDriver" then click on Finish button.

Vamshi Kurra - New java project creation popup in Eclipse

2.Add the Webdriver Jar files to the created Project

Right click on created project then goto
Build Path>>Configure Build Path >>Select Libraries tab>>Add External jars
Which will open a folder search prompt , goto the locations where you have downloaded WebDriver jar files and add them .Then click on "Ok" button
You need to add below jar files.If you don't have these files downloaded on your computer then you can download them from the below pages :
http://seleniumhq.org/download/
http://code.google.com/p/selenium/downloads/list
You can also download all jars from my shared location
https://docs.google.com/folder/d/0B00rtzEfza2uZnRBZnNVWHFVNjA/edit
  • a.selenium-java-2.32.0-srcs.jar
  • b.selenium-java-2.32.0.jar
  • c.selenium-server-standalone-2.32.0.jar

Vamshi Kurra- Adding External jar files in Eclipse

3.Create a new Package under Java Project

 Goto creatd project  i.e. "ExploreWebDriver" and expand it.Now we will see a separate folder named "src". Right Click on it and then Goto
New>>Package>>Give the name of package in the "package creation" popup. Say "learning" is the name of the Package.Now click on finish button.

Vamshi Kurra - New Java Package popup

4.Create a Java class file under the Package

Right click on the created package i.e "Learing" and then goto
New>>Class>>we will get "New Java Class" popup. Enter the name of the class say "GoogleSearch" and click on Finish.

Vamshi Kurra- Adding new Java Class in Eclipse

5.Write the code in the Java class file and run it.

Copy the below code and paste it in the created Java class file.

package learning;

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

public class GoogleSearch {
 
 public static void main(String args[]){
  WebDriver driver=new FirefoxDriver();
  System.out.println("Loading Google search page");
  driver.get("http://google.com");
  System.out.println("Google search page loaded fine"); 
 }

}

Here is how your Eclipse project hierarchy looks like :

Vamshi Kurra- Eclipse project hierarchy

Now Click run .
Script will run successfully and a new firefox window will be opened with the Google.com .

Sunday, August 5

WebDriver Tutorial Part 2 : Installing Java and Eclipse IDE


Once we are familiar with selenium IDE , the next step is "Choosing a programnning language" and start scripting .

Selenium supports multiple languages like Java, C#, Phython, Ruby,Php, Perl . Depending upon your flexibility select any one of the language as your scripting langauge and install that language components.

Suppose If you are planning to use Java as your programming language (like me) then here are steps for installing it.

Step 1 : Installing Java:

Before installing check whether your computer already has Java or not , by visiting
http://java.com/en/download/installed.jsp

If you don't have Java istalled on your computer , then you can start installing Java by visiting
http://www.java.com/en/download/help/windows_manual_download.xml
 Above site will have step by step instructions on how to install Java.

Step 2: Set up Path and Class Path for Java :

Here are the step to step instructions on how to setup PATH variables in java (with screenshots :) )
http://www.roseindia.net/java/java-classpath.shtml

Here is the website which describes all the above details clearly
http://www.ugrad.cs.ubc.ca/~cs211/tutorials/Eclipse/Eclipse_Java_Windows_XP.html

Step 3 :Installing Eclipse 

Eclipse is an opensource IDE(Integrated Development Environment ). Download Eclipse from
http://www.eclipse.org/downloads

Follow the below tutorial which gives the basic idea on how to configure Eclipse and use it.
http://www.vogella.com/articles/Eclipse/article.html

Sunday, July 29

WebDriver Tutorial Part 1 : Overview on WebDriver and Selenium IDE


Before we start , quick details on WebDriver ( Selenium 2 )

Selenium is a Automation tool  for testing WebApplications. And using this we can automate ONLY web applications but not Windows based applications.

There are others tool which can be used to automate both web applications and windows applicaions like QTP(Quick Test Professional) .Unlike QTP , Selenium is freeware :) .

This is why most of the companies prefer Selenium whenever they want to automate Webbased applications ,between who hates to save money :) .

If you are the beginner and doesn't know anything about Selenium then please start using Selenium IDE which is a firefox addon, used to record and run the testcases.

Using Seleniun IDE , we can even export our testcases.

Install Selenium IDE and start playing with it. It is one of the simple tool which doesn't require much detailed explanations :)

But Selenium IDE itself is not enough for effective test script as it doesnt supports looping(for, while etc..) and our cusom needs.So we need to use other programming languages to customize testscript and achieve what our test senario demands.

Stay tuned lot more to discuss :)

Check Part 2  i.e  Installing Java and Eclipse IDE

Tuesday, June 19

Handling "drag and drop" actions using WebDriver(Selenium 2)


Automating rich web application is even more interesting since it involves advanced user interactions.

Say we have a web application which drag an item from one location and then drop it at another location.These kind of drag and drops are cant be automated with one single statement .In WebDriver we have a separatae "Actions" class to handle advanced user interactions(say drag and drop) on web page.

Here is the documentation on how to automate advanced user interactions :
http://code.google.com/p/selenium/wiki/AdvancedUserInteractions

Here is the sample code using TestNG framework
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class draganddrop {
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){
  FirefoxProfile profile = new FirefoxProfile();
  profile.setEnableNativeEvents(true);
  driver = new FirefoxDriver(profile);
 }

 @Test
 public void start1(){
  driver.get("http://jqueryui.com/droppable/");
  driver.switchTo().frame(0);  
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  WebElement dragElement=driver.findElement(By.id("draggable"));
  WebElement dropElement=driver.findElement(By.id("droppable"));
    
  Actions builder = new Actions(driver);  // Configure the Action
  Action dragAndDrop = builder.clickAndHold(dragElement)
    .moveToElement(dropElement)
    .release(dropElement)
    .build();  // Get the action
    dragAndDrop.perform(); // Execute the Action
 }
}

Monday, June 11

Apple Store is down

Hey guys did you visit "Apple Store" today ? Right now it is down.

They are updating Apple Store for us .Let us hope to see some good stuff .. :)




Sunday, June 10

List of supported Google country specific(regional) domain list

When we type google world wide domain address (www.google.com) in the browser address bar then we will automatically get redirected to country specific domain. Do you have any idea how many supported regional domains google has ?
Well, If you don't know then here is the list of Google country specific domains list :
www.google.com
www.google.ad 
www.google.ae
www.google.com.af
www.google.com.ag
www.google.com.ai
www.google.am
www.google.co.ao
www.google.com.ar
www.google.as
www.google.at
www.google.com.au
www.google.az
www.google.ba
www.google.com.bd
www.google.be
www.google.bf
www.google.bg
www.google.com.bh
www.google.bi
www.google.bj
www.google.com.bn
www.google.com.bo
www.google.com.br
www.google.bs
www.google.co.bw
www.google.by
www.google.com.bz
www.google.ca
www.google.cd
www.google.cf
www.google.cg
www.google.ch
www.google.ci
www.google.co.ck
www.google.cl
www.google.cm
www.google.cn
www.google.co.cr
www.google.com.cu
www.google.cv
www.google.com.cy
www.google.cz
www.google.de
www.google.dj
www.google.dk
www.google.dm
www.google.com.do
www.google.dz
www.google.com.ec
www.google.ee
www.google.com.eg
www.google.es
www.google.com.et
www.google.fi
www.google.com.fj
www.google.fm
www.google.fr
www.google.ga
www.google.ge
www.google.gg
www.google.com.gh
www.google.com.gi
www.google.gl
www.google.gm
www.google.gp
www.google.gr
www.google.com.gt
www.google.gy
www.google.com.hk
www.google.hn
www.google.hr
www.google.ht
www.google.hu
www.google.co.id
www.google.ie
www.google.co.il
www.google.im
www.google.co.in
www.google.iq
www.google.is
www.google.it
www.google.je
www.google.com.jm
www.google.jo
www.google.co.jp
www.google.co.ke
www.google.com.kh
www.google.ki
www.google.kg
www.google.co.kr
www.google.com.kw
www.google.kz
www.google.la
www.google.com.lb
www.google.li
www.google.lk
www.google.co.ls
www.google.lt
www.google.lu
www.google.lv
www.google.com.ly
www.google.co.ma
www.google.md
www.google.me
www.google.mg
www.google.mk
www.google.ml
www.google.mn
www.google.ms
www.google.com.mt
www.google.mu
www.google.mv
www.google.mw
www.google.com.mx
www.google.com.my
www.google.co.mz
www.google.com.na
www.google.com.nf
www.google.com.ng
www.google.com.ni
www.google.ne
www.google.nl
www.google.no
www.google.com.np
www.google.nr
www.google.nu
www.google.co.nz
www.google.com.om
www.google.com.pa
www.google.com.pe
www.google.com.ph
www.google.com.pk
www.google.pl
www.google.pn
www.google.com.pr
www.google.ps
www.google.pt
www.google.com.py
www.google.com.qa
www.google.ro
www.google.rw
www.google.com.sa
www.google.com.sb
www.google.sc
www.google.se
www.google.com.sg
www.google.sh
www.google.si
www.google.sk
www.google.com.sl
www.google.sn
www.google.so
www.google.sm
www.google.st
www.google.com.sv
www.google.td
www.google.tg
www.google.co.th
www.google.com.tj
www.google.tk
www.google.tl
www.google.tm
www.google.tn
www.google.to
www.google.com.tr
www.google.tt
www.google.com.tw
www.google.co.tz
www.google.com.ua
www.google.co.ug
www.google.co.uk
www.google.com.uy
www.google.co.uz
www.google.com.vc
www.google.co.ve
www.google.vg
www.google.co.vi
www.google.com.vn
www.google.vu
www.google.ws
www.google.rs
www.google.co.za
www.google.co.zm
www.google.co.zw
www.google.cat
Reference :
1.http://www.google.com/supported_domains
2.http://en.wikipedia.org/wiki/List_of_Google_domains

Sunday, June 3

Checking the Web Page load time using WebDriver

Most of the time we would like to check the performance of site like the page load time. But in WebDriver we don't have any direct method to do this. So here is the sample code to achieve this using TestNG framework:
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.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class CheckPageLoadTime{
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){ 
  driver = new FirefoxDriver();
 }
 
 @Test
 public void LoadTime(){
  
 long startTime = System.currentTimeMillis()/1000;
 System.out.println("The startTime is "+startTime);
 //Set the acceptable Page load time to 60 sec
 driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); 
 driver.get("http://google.com/");  
 WebElement search = driver.findElement(By.name("q"));
 //Iterate through the loop as long as time(60sec) is with in the acceptable Page load time
 while(((System.currentTimeMillis()/1000)-startTime)<60){
         if(search.isDisplayed()){
  long endTime = System.currentTimeMillis()/1000;
  System.out.println("The endTime is "+endTime);
  long loadTime = endTime - startTime;
  System.out.println("Totaltime: " +loadTime + " seconds"); 
      break;
  }  
   }     
     }
    
}
Here is the output of above program(It may vary for you)
The startTime is 1338712185
The endTime is 1338712215
Totaltime: 30 seconds

Thursday, May 31

WebDriver(Selenium2) : Extract text from PDF file using java


Verifying PDF content is also part of testing.But in WebDriver (Selenium2) we don't have any direct methods to achieve this.

If you would like to extract pdf content then we can use Apache PDFBox  API.

Download the Jar files and add them to your Eclipse Class path.Then you are ready to extract text from PDF file .. :)

Here is the sample script which will extract text from the below PDF file.
http://www.votigo.com/pdf/corp/CASE_STUDY_EarthBox.pdf
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.util.PDFTextStripper;
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 ReadPdfFile {
 
 WebDriver driver;
 
  @BeforeTest
  public void setUpDriver() {
   driver = new FirefoxDriver();
   Reporter.log("I am done");
     }
  
  @Test
  public void start() throws IOException{
  driver.get("http://votigo.com/overview_collateral.pdf");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  URL url = new URL(driver.getCurrentUrl()); 
  BufferedInputStream fileToParse=new BufferedInputStream(url.openStream());

  //parse()  --  This will parse the stream and populate the COSDocument object. 
  //COSDocument object --  This is the in-memory representation of the PDF document

  PDFParser parser = new PDFParser(fileToParse);
  parser.parse();

  //getPDDocument() -- This will get the PD document that was parsed. When you are done with this document you must call    close() on it to release resources
  //PDFTextStripper() -- This class will take a pdf document and strip out all of the text and ignore the formatting and           such.

  String output=new PDFTextStripper().getText(parser.getPDDocument());
  System.out.println(output);
  parser.getPDDocument().close(); 
  driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
  }

}
Here is the output of above program :
EarthBox a Day Giveaway 
Objectives 
EarthBox wanted to engage their Facebook 
audience with an Earth Day promotion that would 
also increase their Facebook likes. They needed a 
simple solution that would allow them to create a 
sweepstakes application themselves. 
 
 
Solution 
EarthBox utilized the Votigo 
platform to create a like-
gated sweepstakes. Utilizing a 
theme and uploading a custom graphic they 
were able to create a branded promotion. 
 
 
Details 
• 1 prize awarded each day for the entire Month of April  
• A grand prize given away on Earth Day  
• Daily winner announcements on Facebook 
• Promoted through email newsletter blast  
 
Results (4 weeks) 
• 6,550 entries 
 
Facebook  

Monday, May 28

Getting google search auto suggestions using Webdriver(Selenium 2)

In the google search when we start typing any search query google will start auto suggestions. All these search suggestions are part of a WebTable. If we would like to capture all these search suggestions then we have to just iterate through the table.

Here is the sample code which will start typing "vam" and then capture all search suggestions .
import java.util.Iterator;
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 SearchSuggestion {
 
WebDriver driver;
 
 @BeforeTest
 public void start(){
   driver = new FirefoxDriver(); 
 }
  
 @Test
  public void SearchSuggestion() {
  
  driver.get("http://google.com");
  driver.findElement(By.id("gbqfq")).sendKeys("vam");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
   WebElement table = driver.findElement(By.className("gssb_m")); 
   List rows = table.findElements(By.tagName("tr")); 
   Iterator i = rows.iterator(); 
   System.out.println("-----------------------------------------"); 
   while(i.hasNext()) { 
           WebElement row = i.next(); 
           List columns = row.findElements(By.tagName("td")); 
           Iterator j = columns.iterator(); 
           while(j.hasNext()) { 
                   WebElement column = j.next(); 
                   System.out.println(column.getText()); 
           } 
           System.out.println(""); 
            
   System.out.println("-----------------------------------------"); 
   } 
  } 
}

Here is what we will see in the browser after running the above code.




Friday, May 25

Selenium WebDriver : getSize() Vs getLocation() functions

Here are the difference between getSize() and getLocation() methods :

getSize() : 
  1. It will returns the "Dimension" object.
  2. If you want to get the width and Height of the specific element on the webpage then use "getsize()" method.
Sample code to get the width and height :
WebDriver driver = new FirefoxDriver(); 
driver.get("https://google.com");
Dimension dimesions=driver.findElement(By.id("gbqfsa")).getSize();
System.out.println("Width : "+dimesions.width);
System.out.println("Height : "+dimesions.height);
Note:
Makesure to import "org.openqa.selenium.Dimension;" package.

getLocation() :
  1. It will return the "Point" object.
  2. If you want to get the exact "x" and "y" coordinates of the element then use "getLocation()"  method.

Sample code to get the "x" and "y" coordinates :
WebDriver driver = new FirefoxDriver(); 
driver.get("https://google.com");
Point point=driver.findElement(By.id("gbqfsa")).getLocation();
System.out.println("X Position : "point.x);
System.out.println("Y Position : "point.y);
Note:
Makesure to import "org.openqa.selenium.Point;" package.

Wednesday, May 23

Starting Opera Browser and Internet Explorer (IE) using WebDriver(Selenium2) with example


In the previous Post we have discussed how to Open Chrome Browser using WebDriver.

Now it is time for Opera :)

Opera and IE browers are as easy as you work with Firefox Browser.

Opera Browser :

Use the below code to start Opera Browser:
DesiredCapabilities capabilities = DesiredCapabilities.opera();
capabilities.setCapability("opera.binary","Absolute Path of Opera browser"); 
//Path will be something like
//C:\Users\\AppData\Local\Programs\Opera\opera.exe 
driver = new OperaDriver(capabilities);
Here is the sample code using TestNG framework
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.opera.core.systems.OperaDriver;

public class opera {
 
 WebDriver driver;
 
 @BeforeTest
 public void open(){ 
  DesiredCapabilities capabilities = DesiredCapabilities.opera();
  capabilities.setCapability("opera.binary", " Absolute Path of Opera browser ");
  driver = new OperaDriver(capabilities); 
 }
 
 @Test
 public void startit(){
  driver.get("http://google.com/");  
 }
 
}

Internet Explorer:

First download  IEDriverServer.exe file from here and save it on your local disk.

Now use the below code to start Internet Explorer 
System.setProperty("webdriver.ie.driver", "Path to IEDriverServer.exe");
driver = new InternetExplorerDriver();
Here is the sample code using TestNG framework.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class IeBrowser {
 
 WebDriver driver;

 @BeforeTest
 public void start(){
   System.setProperty("webdriver.ie.driver", "Path to IEDriverServer.exe");
   driver = new InternetExplorerDriver();
 }
 
 @Test
 public void startit(){
  driver.get("http://google.com");
  
 }

}

Note :
Even if you are using 64-bit operating system try to use 32 bit version of IEDriver as there are some known issues with the 64-bit version of IEDriver.  Especially 64 bit driver is too slow .

https://code.google.com/p/selenium/issues/detail?id=5116#makechanges
https://code.google.com/p/selenium/issues/detail?id=3072

Sunday, May 20

Handling Security Certificates in Firefox using WebDriver

In the Previous Post we have discussed how to handle Security Certificates in IE using WebDriver.

Now it is time for Firefox :)

Handling SSL issues in firefox are easy too. This can be done easily by setting
setAcceptUntrustedCertificates=true

Here is the sample code using TestNG framework :
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 void SecurityAlerts(){

WebDriver driver;

@BeforeTest
public void setUpDriver() {
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("setAcceptUntrustedCertificates","true");
driver = new FirefoxDriver(profile);
         }

@Test
public void Start(){
driver.get(URL);
         }
 }



Friday, May 18

Changing the User Language Locale using WebDriver (Selenium2)


Most of the time Websites use the User "Default Language Settings" to display the website look and feel.

If we want to check whether our application is properly internationalized , then we will manually change the language preferences in the browser itself.

But if we want to check the same using webDriver then we have programatically change the user language preferences. And it's simple :)

If you are using Firefox then you can change the Language preferences by the below code

intl.accept_languages= "Language Code"

Here is the sample code using TestNG framework.
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.WebDriver;

public void UserLocale(){

WebDriver  driver;

@BeforeTest
public void setUpDriver() {
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("intl.accept_languages","sl");   
driver = new FirefoxDriver(profile);
}

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

}
If you run the above code then google will be opened in Sloveninan Language and here is the output .. !! :)

Google.com in Sloveninan Language

Tuesday, May 15

Permission denied for to get property Window.frameElement Command duration or timeout: 12 milliseconds

I used to get the below error when I try to switch to iframe ( driver.switchTo().frame("iframe_canvas") ).


Permission denied for <https://apps.facebook.com> to get property Window.frameElement Command duration or timeout: 12 milliseconds Build info: version: '2.21.0', revision: '16552', time: '2012-04-11 19:09:00' System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.6.0_23' Driver info: driver.version: RemoteWebDriver
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
at java.lang.reflect.Constructor.newInstance(Unknown Source)


Seems this issue is happening because of Cross Origin .
Solution to this problem is set the below settings in Firefox Profile.
capability.policy.default.Window.QueryInterface='allAccess'

capability.policy.default.Window.frameElement.get='allAccess'

I changed my code as below. Now it is working fine :)
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
 
public void IframeTest(){

 WebDriver driver;

@BeforeTest
  public void setUpDriver() {
   FirefoxProfile profile = new FirefoxProfile();
   profile.setPreference("capability.policy.default.Window.QueryInterface", "allAccess");
   profile.setPreference("capability.policy.default.Window.frameElement.get","allAccess");
   driver = new FirefoxDriver(profile);
     }

@Test
 public void delete(){
   Common.FBLogin(fbUsername, fbPassword, driver);
   driver.get("appURL");
   driver.switchTo().defaultContent();
   driver.switchTo().frame("iframe_canvas");  
  }

}
For more details check this one  :
http://code.google.com/p/selenium/issues/detail?id=2863


If you ever happened to get the above error then change your Firefox preferences from code :)


Friday, May 11

Handling Security Cerificates(UntrustedSSLCertificates) in Internet Explorer (IE) using WebDriver(selenium2)

In automating web based application we will find problem with Security Cerificates(UntrustedSSLCertificates).

And here is a simple solution for this.Just use the below code to cross the SSL page :)

driver.navigate().to("javascript:document.getElementById('overridelink').click()");


If you are using TestNG framework then here is the sample code :

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class SecurityCerts {

 WebDriver  driver;

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

 @Test
 public void start(){
 driver.get("https://www.hs.facebook.com/help/community/question/?id=648015478541882");  
 driver.navigate().to("javascript:document.getElementById('overridelink').click()"); 
 }

}


Thursday, May 10

Starting Chrome Browser using WebDriver(Selenium2) with example


If we would like to run our scripts on Chrome we need "chromedriver"along with the actual Chrome Browser.If you try to start the Chrome Browser with the below statement alone
WebDriver driver = new ChromeDriver();

Then you will notice below error statements

"You need to have both chromedriver and a version of chrome browser installed
@BeforeTest setUpDriver
java.lang.IllegalStateException: The path to the chromedriver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
at com.google.common.base.Preconditions.checkState(Preconditions.java:172)
atorg.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:114)"

In our scripts if we dont specify where is chromedriver is located then we cant start chrome browser using WebDriver.

Here are steps to setup chromedriver

1.Download chromedriver from
http://code.google.com/p/chromedriver/downloads/list
2.Unzip the file .Say you downloaded it on your desktop folder named "Automation" and unzipped it then location will be like
C:\\Users\\<<User Name>>\\Desktop\\Automation\chromedriver_win_19.0.1068.0\\chromedriver.exe
3.Use the below code to start chrome
System.setProperty("webdriver.chrome.driver","C:\\Users\\<<UserName>>\\Desktop\\Automation\\chromedriver_win_19.0.1068.0\\chromedriver.exe"); 
ChromeDriver driver = new ChromeDriver();

Now you are done. :)

If you are using the TestNG framework then here is the sample code :

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class chromeDriver {
 
WebDriver  driver;

@BeforeTest
 public void setUpDriver(){
   System.setProperty("webdriver.chrome.driver",
"C:\\Users\\<>\\Desktop\\Automation\\chromedriver_win_19.0.1068.0\\chromedriver.exe");  
   driver = new ChromeDriver(); 
     }

 @Test
 public void start(){
 driver.get("http://www.google.com/"); 
   }

}


TestNG XMLfile preparation and error messages


Here is the sample TestNG file :

  
  
   
               
        
     
   
   
           
        
     
   


It is also important to know about error messages.Sometimes we learn more from errors :)
I have put some of the error messages we get when we go wrong in the above TestNG XML file .

Here are the error codes we will see when we have done any error in the above XML file.

1.If two tests are having the same name then we see below error
Ex :  
<test name="Testing the Google"> 
        <classes>       
        <class name="com.google.UI"/>
     </classes>
  </test> 
  <test name=" Testing the Google "> 
    <classes>       
        <class name="com.google.gmail"/>
     </classes>
  </test> 
Two tests in the same suite cannot have the same name: <<Test anme>>
at org.testng.TestNG.checkTestNames(TestNG.java:981)
at org.testng.TestNG.sanityCheck(TestNG.java:970)
at org.testng.TestNG.run(TestNG.java:1002)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:109)

2.If the testname doesnot elclosed in double quotes("") then we wills ee below error
Ex :  <test name=Testing the Google> 
The value of attribute "name" associated with an element type "null" must not contain the '<' character.
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: The value of attribute "name" associated with an element type "null" must not contain the '<' character.
atcom.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)

3.If the class name doesnt end with "/" character then we will see below error
org.testng.TestNGException: org.xml.sax.SAXParseException: The end-tag for element type "class" must end with a '>' delimiter.
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: The end-tag for element type "class" must end with a '>' delimiter.

4. If there is no space between parameter name and value  fields then we will see below error 
Ex   :  <parameter name="googleURL"value="http://google.com"/>
org.testng.TestNGException: org.xml.sax.SAXParseException: Element type "parameter" must be followed by either attribute specifications, ">" or "/>".
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: Element type "parameter" must be followed by either attribute specifications, ">" or "/>".

5.If the parameter attribute doesnt end with "/" character then we will see below error
Ex   :  <parameter name="googleURL"value="http://google.com">
org.testng.TestNGException: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".


6. If the two parameters have the same name and value attributes then we will see below error
Ex   :  <parameter name="googleURL"value="http://google.com"/>
          <parameter name="googleURL"value="http://google.com"/>
org.testng.TestNGException: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".

7.Make sure there are no spaces between "/" and  ">".If there are any spaces then we will see below error.
Ex   :  <parameter name="googleURL"value="http://google.com"/                >
org.testng.TestNGException: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".

Wednesday, May 9

Getting total no.of Checkboxes/Textboxes/Dropdowns/iframes/Links on a web page



In one of the Previous Post we had details about WebDriver findElements() method. This is very useful to find the total no.of  desired elements on a wepage .

Here are some of the examples :

Getting total no.of Links on a Webpage :
Here is the sample code to get the total no.of links on facebook registration page:
driver.get("http://facebook.com");
List  totalLinks=driver.findElements(By.tagName("a"));
System.out.println("total links "+totalLinks.size());

Getting total no.of checkboxes on a Webpage :
Here is the sample code to get the total no.of checkboxes on facebook registration page:
driver.get("http://facebook.com");
List checkboxes=driver.findElements(By.xpath("//input[@type='checkbox']"));
System.out.println("total checkboes "+checkboxes.size());



Getting total no.of dropdown menus on a Webpage :
Here is the sample code to get the total no.of dropdown menus on a facebook registration page:
driver.get("http://facebook.com");
List dropdown=driver.findElements(By.tagName("select"));
System.out.println("total dropdown lists "+dropdown.size());



Getting total no.of textboxes on a Webpage :
Here is the sample code to get the total no.of textboxes on facebook registration page:
driver.get("http://facebook.com");
List  textboxes=driver.findElements(By.xpath("//input[@type='text'[@class='inputtext']"));
System.out.println("total textboxes "+textboxes.size());

Here is the sample code to get the total no.of textboxes on hotmail registration page:
driver.get("https://signup.live.com");
List  totalTextboxes=driver.findElements(By.xpath("//input[@type='text']"));
System.out.println("total textboxes "totalTextboxes.size());

Getting total no.of iframes on a Webpage :
Here is the sample code to get the total no.of iframes :
driver.get("https://www.facebook.com/googlechrome/app_158587972131");
List  totaliFrames=driver.findElements(By.tagName("iframe"));
System.out.println("total links "+totaliFrames.size());



Monday, May 7

Missing requirement: Jetty Server Adaptor Plug-in 1.0.4 (org.mortbay.jetty.serveradaptor 1.0.4) requires 'bundle org.eclipse.wst.server.core 0.0.0' but it could not be found


Today I tried to install Jetty plugin in Eclipse using the below URL
http://www.webtide.com/eclipse

But my installation failed with the below error

"Cannot complete the install because one or more required items could not be found.
Software currently installed: Jetty Generic Server Adaptor 1.0.
(org.mortbay.jetty.serveradaptor.feature.group 1.0.4)
Missing requirement: Jetty Server Adaptor Plug-in 1.0.4 
(org.mortbay.jetty.serveradaptor 1.0.4) requires 'bundle org.eclipse.wst.server.core 
0.0.0' but it could not be found
Cannot satisfy dependency:
From: Jetty Generic Server Adaptor 1.0.4 
(org.mortbay.jetty.serveradaptor.feature.group 1.0.4)
To: org.mortbay.jetty.serveradaptor [1.0.4] "

Solution to this problem is very simple .

Install Jetty plugin with the below URL
http://download.eclipse.org/jetty/updates/jetty-wtp

Steps :

  1. Open Eclipse.
  2. click Help -> Install New Software. The Available Software dialog box opens.
  3. Add the plugin using below URl  http://download.eclipse.org/jetty/updates/jetty-wtp


Detailed steps with instructions can be found at :
http://wiki.eclipse.org/Jetty_WTP_Plugin/Jetty_WTP_Install

Saturday, May 5

RCT (Root Canal Therapy) - First Appointment with less Pain


Monday -April 30,2012 :
I had severe tooth pain so I left office early for checkup.After going through the initial checkup and X-ray , doctor suggested me to go through RCT ( Root Canal Therapy ) as one of my right tooth decayed and the process will be finished in two appointments. I got my first appointment with surgeon on Friday at 7.30PM ( May 04, 2012).


Friday - May 04, 2012 :
I couldnt make it on friday so I got my treatment to be postponed to Saturday at 6.00PM ( May 05, 2012 ).


Saturday - May 05, 2012 at 6.00 PM :

I was in Hospital.I was very sick and afraid of pain. I am still so much depend on my parents especially when I am sick :P.

I wish my parents could be just beside me so that I can hold their hands when I felt pain.Luckily Dentist friendly smile comfort me little bit.But I know he can never never replace my parents.This Process includes  three steps.



First step is giving anesthetic injection very near to my right decayed tooth which makes of half of my right face numb.

Now the second step is cleaning the tooth which is of no pian :)

And  third step is removing the nerve which is little painy. Dentist told me to raise my hand whenever I felt Pain. In the middle of the process I raised my handas  it is little paining so he stopped for sometime and then started again. Seriously I myself didn't realize what is really happening .The only one thing I know at that time was dentise was just doing something in my mouth and playing with my tooth :)

Entire process was done with in 20 mins.Dentist told me that "my right cheeck will be heavy for another one hour as I have been given anesthetic injection  and he suggested me not to take anything for another one hour".

I was told I can eat whatever I want including chocolates and Icecreams except too much hot and sticky food  :P

And my next treatment will be on Tuesday at 6.30 PM ( May 08,2012) that process will take around 45 mins.

And overall what I can say is "RCT is not painful ". There will be very very very less pain.

Waiting for my next appointment on Tuesday at 6.30 PM ( May 08,2012) :)

Selenium WebDriver : findElement() Vs findElements() functions



It is very important to know the difference between findElement() and findElements() functions and here you go for it :

findElement() :

  1. Find the first element within the current page using the given "locating mechanism".
  2. Returns a single WebElement.
  3. Syntax: WebElement findElement(By by)

Ex:
driver.get("https://signup.live.com");
WebElement firstName=driver.findElement(By.id("iFirstName"));
firstName.sendKeys("Automated First Name");



findElements() :

  1. Find all elements within the current page using the given "locating mechanism".
  2. Returns List of WebElements.
  3. Syntax:  java.util.List<WebElement> findElements(By by)

Ex:
driver.get("https://signup.live.com");
List  textboxes1=driver.findElements(By.xpath("//input[@type='text']"));
System.out.println("total textboxes "+textboxes1.size());

Tuesday, May 1

TestNG : The reference to entity "tab" must end with the ';' delimiter.


Today I have faced problem while running the below TestNg XML file .

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="testing test suite">
  <parameter name="googlePlayUrl" value="https://play.google.com/store?hl=en&tab=w8"/>
  <test name="checking the Google play">
    <classes>
       <class name="com.google.play.UrlVerification"/>
    </classes>
  </test>
</suite>

When I run the above TestNG XML file I got bellow error

org.testng.TestNGException: org.xml.sax.SAXParseException: The reference to entity "tab" must end with the ';' delimiter.
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: The reference to entity "tab" must end with the ';' delimiter.

Solution to the above problem is very simple. Replace the "&" symbol with "&amp;"

I have changed my XML file like below and it was successed.

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="testing test suite">
  <parameter name="googlePlayUrl" value="https://play.google.com/store?hl=en&amp;tab=w8"/>
  <test name="checking the Google play">
    <classes>
       <class name="com.google.play.UrlVerification"/>
    </classes>
  </test>
</suite>

Thursday, April 26

FAILED CONFIGURATION: @BeforeTest setUpDriver java.lang.NoSuchMethodError: org.openqa.selenium.os.CommandLine.executeAsync()V



Today we have noticed the below errors while running our test scripts.


FAILED CONFIGURATION: @BeforeTest setUpDriver
java.lang.NoSuchMethodError: org.openqa.selenium.os.CommandLine.executeAsync()V
at org.openqa.selenium.firefox.FirefoxBinary.startFirefoxProcess(FirefoxBinary.java:92)
at org.openqa.selenium.firefox.FirefoxBinary.startProfile(FirefoxBinary.java:87)
at org.openqa.selenium.firefox.FirefoxBinary.clean(FirefoxBinary.java:225)
atorg.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:76)
at org.openqa.selenium.firefox.FirefoxDriver.startClient(FirefoxDriver.java:157)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:93)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:136)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:78)



So we have removed Android jars(android_webdriver_library-srcs.jar ,android_webdriver_library ) from our project Build path , then all the scripts started working fine.

We are still searching why this conflict happened and how to overcome this :)

Wednesday, April 25

Setup of Android WebDriver in Eclipse



Here are the Instruction for how to setup Android driver in Eclipse

1. Install  Android SDK 
Download the SDK zip file and unzip in your local computer.
Say download at “C:\android ” location
Go to unzipped folder and click on “Android SDK Manager” and install the following:
         a.Tools
         b.Extras
         c.Android API’s as per your choice (Say Android 2.2 , Android 4.0)

2. Install the ADT Plugin for Eclipse-
Goto Help > Install New Software....>> Add

3.Configure ADT Plugin
Window > Preferences...>>Android
Set the SDK location to where is your Android SDK has been installed.
Location will be something like:  C:\android\android-sdk-windows

4. Add the new AVD
In Eclipse goto Window >>AVD Manager>>
Create new AVD by clicking on “New” button.(Give the AVD  name  and select the Target)

5.Now download the Android APK 
Copy the file and paste it in the “Platform-tools” folder of the unzipped Android SDK.
Location will be something like “C:\android\android-sdk-windows\platform-tools

6. Now start the Android AVD (Which has been created in Step 4) by following below in your Eclipse
Window >>AVD Manager>> Select the created AVD and click on “Start”

7.  Find the installed emulator device id .
open the command prompt ( cmd ) and run the following command 
adb devices
Emulator device id will be something like “emulator-5554

8. Now from the command prompt, go to the “Platform-tools” folder of the unzipped Android SDK
cd "C:\android\android-sdk-windows\platform-tools"

9. Install the Android server by running the following command
adb -s <<emulator-id>> -e install -r  android-server-2.21.0.apk

10. Start the Android WebDriver application by running the following command
adb -s <<emulator-id>> shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity -e debug true

11. Now setup the port forwarding in order to forward traffic from the host machine to the emulator by running the following command
adb -s <<emulator-id>> forward tcp:8080 tcp:8080

If you have any problem then here is the official Reference :