Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Sunday, November 25, 2012

Selenium - java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.ie.driver system property;

Selenium - java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.ie.driver system property;

IE browser will fail with the above mentioned exception if we upgrade the Selenium webdriver with 2.26.

Reason?
From 2.26 vesrion, IE driver got decoupled from selenium jar file and entire IE driver software is stored in a separate exe file, there are 32 and 64 bit versions.
You need to download the exe file similar to chrome driver and use the following code to run the test.

Sample code Java/TestNG

  WebDriver driver;
@BeforeMethod public void StartDriver() { File file = new File("C:/Seleniumjars/IEDriverServer.exe"); System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); driver = new InternetExplorerDriver(); } @AfterMethod(alwaysRun = true) public void StopDriver() throws Exception { driver.quit(); } @Test(groups = { "GoogleTest" }, enabled = true,timeOut = 90000) public void Test_TC_01_1() throws Exception { driver.get("www.google.com"); }

Technical Reason?
IE driver original implementation was in dll using native C++. As per the client language bindings .dll was extracted during run-time.
For Java extracting from the .jar file.
For .NET extracting it from resource package into WebDriver.dll assembly.
Ruby and Python directly relied on the files, no extraction is required, just reference to the path.
The language bindings would use following method to load the dll and expose the API
JNI for Java
P/Invoke for .NET
ctypes for Python
FFI for Ruby
It works fine for simple scenarios, but due to above differences, IEdriver was showing different behavior between language bindings.
The way .NET bindings loading and managing the .dll, it was able to support multiple instances of IE.
Java bindings was not able to support multiple instances.

In order to unify the experience across all the languages, separate process was created IEDriverServer.exe because now the process management is defined my the operating system (Different version of Windows) and client bindings can interact directly with the process API.

As there is windows limitation where 32 bit process can't be loaded with 64 bit dll, separate 32 and 64 bit process are created.

As the IE driver got decoupled from the selenium release, it is possible to ship the fixes of IE driver without having to wait for complete selenium release.

It is easy to debug a standalone dll then dll loaded by the laungage binding.

Thanks a lot to Jim Evans (IE driver and .NET bindings project lead) for sharing the details and contributing to the open source community.

---

Thursday, November 8, 2012

Selenium 2.26 is ready for download.

Selenium 2.26
Download from this link.
Following are the major bug fixes and enhancements.
Hats-off to the development team for frequent releases and you determination to enhance the tool.

v2.26.0
=======
WebDriver:
* Updated OperaDriver to 0.15.
* Added transparency support to the Color class.
* Increased lock time a bit for the FirefoxDriver to make tests more
stable on Windows.
* Added the enablePersistenHover capability to allow the user to specify
whether to use the persistent hover thread in the IE driver. Defaults
to true for IE.
* Added support for native events for Firefox 15 and 16.
* Removed deprecation from ChromeDriver constructors that take a Capabilities
object. Also added a method to set experimental options in ChromeOptions
which may be used to set options that aren't exposed through the ChromeOptions
API.
* Fixed SafariDriver to allow calling .quit() consecutively without error.
* Modified FirefoxDriver to use atoms to switch between frames.
* FIXED: 4535: Hover still does not work perfectly in IE.
* FIXED: 4676: Unable to fire javascript events into SVG's.
* FIXED: 4320: Impossible to IE run tests in parallel via TestNG.
* FIXED: 4309: 'Could not convert Native argument arg 0' error with Firefox.
* FIXED: 4593: Alert.accept() Cancels the Resend Alert/Dialog Box.
* FIXED: 4321: Upgrade HtmlUnitDriver to HtmlUnit 2.10.
* FIXED: 4639: Webdriver 2.25 fails to quit on Windows.
* FIXED: 3774: New SafariDriver sessions do not come with a clean profile.
* FIXED: 4375: Executing javascript hangs Firefox.
* FIXED: 4203: Java SafariDriver has limited websocket frame size.
* FIXED: 4165: WebDriver fails on a machine with no IP address.
* FIXED: 3969: SafariDriver should auto-dismiss alerts.

WebDriverJS:
* FIXED: 4648: findElement errros not helpful.
* FIXED: 4687: webserverjs cannot find module in node.js.
* FIXED: 4649: Wrong Content-Length calculation in webdriverjs.
* FIXED: 4425: Webdriver.js regression: webdriver.By.* selectors defect when
using Node.js.

Grid:
* FIXED: 4433: NPE at grid launch if invalid servlet class name is specified.
* FIXED: 4526: elenium node stop responding when there are 2 or more tests
waiting for a specific node.
* FIXED: 2549: "-role hub" doesn't allow Firefox to starts. ---

Thursday, September 6, 2012

Selenium - java.lang.NullPointerException

Selenium - java.lang.NullPointerException

When do we get this exception?

If we don't initialize the driver object and start using it in the code we can notice this exception.
In the below screen shot I have commented the initialize code and started running the test, system displayed  NullPointerException. In my case, unknowing commented it while debugging the code.

When you get this king of exception, check the driver object initialization.


---
  

Friday, June 29, 2012

Webdriver - Calculate Page Load Time

Webdriver - Calculate Page Load Time

I have a similar post for Selenium1.
Selenium2 automatically wait during page load this is an awesome feature not required to write explicit wait or sync statement, but for AJAX calls need to write extra line of code.
How to calculate the page load time? Using java timers.

You can implement the following code in 3 different ways.

long start;
start = System.currentTimeMillis();
driver.get(url); or click();
Print (driver.getTitle() + " - " + (System.currentTimeMillis() - start) + " MilliSec");

1. Copy the above code where page response calculation is required, but it create redundancy.

2. Implement the code in page object. Below code contain 3 classes, 1 test class and 2 page objects. This code will help you to understand page object implementation and calculate the page download time.

package MercuryTours;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import MercuryTours.PageObjects.UtilityScript;
import MercuryTours.PageObjects._01_Initilize;
import MercuryTours.PageObjects._02_Login;

public class MercuryTours_TC_05 extends UtilityScript {

private static WebDriver driver;
@BeforeMethod
public static void StartDriver() {
      driver = new InternetExplorerDriver();
}

@AfterMethod(alwaysRun = true)
public void StopDriver() {
driver.quit();
}

@Test(groups = { "MercuryToursTestCases" }, enabled = true,timeOut = 90000)
public void Test_TC_01() throws Exception {
_01_Initilize Initilize = PageFactory.initElements(driver,_01_Initilize.class);
Initilize.zOpen("http://newtours.demoaut.com/");
_02_Login Login = PageFactory.initElements(driver,_02_Login.class);
Login.zEnterCrediantials("qtp123", "qtp123");
}
}


package MercuryTours.PageObjects;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;

public class _01_Initilize extends UtilityScript {

private WebDriver driver;

public _01_Initilize(WebDriver driver) throws InterruptedException {
this.driver = driver;
}

public _01_Initilize zOpen(String url) throws Exception {
driver.manage().timeouts().implicitlyWait(ImplicitWait, TimeUnit.SECONDS);
driver.manage().window().maximize();
long start;
start = System.currentTimeMillis();
driver.get(url);
Print (driver.getTitle() + " - " + (System.currentTimeMillis() - start) + " MilliSec");
return this;
}

} 


package MercuryTours.PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class _02_Login extends UtilityScript {
private WebDriver driver;

public _02_Login(WebDriver driver) throws InterruptedException {
this.driver = driver;
}

public _02_Login zEnterCrediantials(String UserNameTxt, String PasswordTxt)
throws InterruptedException {
Wait(3000);
driver.findElement(By.name("userName")).sendKeys(UserNameTxt);
driver.findElement(By.name("password")).sendKeys(UserNameTxt);
//driver.findElement(By.name("login")).click();
click(driver.findElement(By.name("login")));
Print("UserName:" + UserNameTxt);
Print("---Login");
Wait(3000);
return this;
}
public void click(WebElement element)  {
long start;
start = System.currentTimeMillis();
element.click();
Print (driver.getTitle() + " - " + (System.currentTimeMillis() - start) + " MilliSec");
}

}

Note: Print() is a custom function written in Utility class, replace it with System.out.Println();

3. By extending the click() method using Webdriver interface.

--- 
   

Wednesday, June 13, 2012

Webdriver - How to start different browsers.

Webdriver - How to start different browsers.

Following example will help you understand how to invoke different browsers using Webdriver, you can also implemented case structure so that browser selection is automatic instead of comment and uncomment the code.


package MercuryTours;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

//@Listeners({ MercuryTours.TestNG.TestNGCustom.class, MercuryTours.TestNG.TestNGCustomeListener.class })
public class MercuryTours_TC_04 {

private static WebDriver driver;
@BeforeMethod
public static void StartDriver() {

      driver = new InternetExplorerDriver();

/* //Download chromedriver.exe from http://code.google.com/p/chromedriver/downloads/list and place in following location
System.setProperty("webdriver.chrome.driver","C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe");            
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        driver = new ChromeDriver(options);*/
     
/*    FirefoxProfile Profile = new FirefoxProfile();
        Profile.setPreference("browser.safebrowsing.malware.enabled", false);
        driver = new FirefoxDriver(Profile);*/

//Safari driver still in experimental stage and run only on Mac
//For Windows need to relay on Selenium1 or RC
//Selenium browser = new DefaultSelenium("localhost", 4444, "*safari", "http://www.google.com");

 //driver = new OperaDriver();


}

@AfterMethod(alwaysRun = true)
public void StopDriver() {
driver.quit();
}

@Test(groups = { "MercuryToursTestCases" }, enabled = true,timeOut = 90000)
public void Test_TC_01() throws Exception {
driver.get("http://newtours.demoaut.com/");
Thread.sleep(7000);

}


}

-----------------

Friday, April 6, 2012

Webdriver - Timeouts

Webdriver - Timeouts

In webdriver there are three different kinds of time outs. Proper values should be assigned, so that your script run efficiently without waiting for too log or short when page is not loaded and element not preset.

Method Summary
 WebDriver.TimeoutsimplicitlyWait(long time, java.util.concurrent.TimeUnit unit)
          Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.
 WebDriver.TimeoutspageLoadTimeout(long time, java.util.concurrent.TimeUnit unit)
          Sets the amount of time to wait for a page load to complete before throwing an error.
 WebDriver.TimeoutssetScriptTimeout(long time, java.util.concurrent.TimeUnit unit)
          Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error.

Timeouts can also be implemented using TestNG @Test annotation

Example

driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);


Timeouts can also be implemented using TestNG @Test annotation
@Test(groups = { "SampleTest" }, enabled = true, timeOut = 9000)


driver.manage().timeouts().implicitlyWait(ImplicitWait,TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(PageLoadWait,TimeUnit.SECONDS); (Not implemented in IE)
driver.manage().timeouts().setScriptTimeout(AsyScripWait,TimeUnit.SECONDS);

Method Detail

implicitlyWait

WebDriver.Timeouts implicitlyWait(long time,
                                  java.util.concurrent.TimeUnit unit)
Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.When searching for a single element, the driver should poll the page until the element has been found, or this timeout expires before throwing aNoSuchElementException. When searching for multiple elements, the driver should poll the page until at least one element has been found or this timeout has expired.
Increasing the implicit wait timeout should be used judiciously as it will have an adverse effect on test run time, especially when used with slower location strategies like XPath.
Parameters:
time - The amount of time to wait.
unit - The unit of measure for time.
Returns:
A self reference.


setScriptTimeout

WebDriver.Timeouts setScriptTimeout(long time,
                                    java.util.concurrent.TimeUnit unit)
Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is negative, then the script will be allowed to run indefinitely.
Parameters:
time - The timeout value.
unit - The unit of time.
Returns:
A self reference.
See Also:
JavascriptExecutor.executeAsyncScript(String, Object...)


pageLoadTimeout

WebDriver.Timeouts pageLoadTimeout(long time,
                                   java.util.concurrent.TimeUnit unit)
Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.
Parameters:
time - The timeout value.
unit - The unit of time.
Returns:


Thursday, April 5, 2012

Webdriver - Can't Click On element

Webdriver - Can't Click On element

Can't Click On element?
Webdriver identified the element correctly, but the element is hidden or disabled so it can't click on it. This is built in validation in webdriver aka Selenium2, this kind of validation was not there in Selenium1.

This kind of validation is good, but some time I am not sure why it throws the error "Can't Click On element".

I came across a scenario where elements are visible on the screen and I am able to select it, but for Webdriver element is not displayed. Run the following statements to check how Webdriver is considering the element attributes.

System.out.println(driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).isDisplayed());

System.out.println(driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).isEnabled());

These kind of issues occur when there are dynamic changes on the screen using JavaScript, due to some reason Webdriver is not able to update the with the new attributes.

If the element was having an id, I would have run the following statement to click using JavaScript.


script = "document.getElementById('ctl00_cpheRFx_btnCriteriaAdd').click();";
((JavascriptExecutor) driver).executeScript(script);

I will explain my issue using below screenshot. When user select from the drop down, boxes appear on the screen, need to select the icons(Pointed in the screen shot). When I click using following state it says "Can't Click On element".

driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).click();


When verified the properties
.isDisplayed() = false
isEnabled() = true

Then I came to the conclusion that I can't use webdriver to click it as the built in validation block the code.
So started working on the click action using JavaScript. Below code resolved my problem. Carefully change the class names and regular expression as per your html.


String Script = "";
Script += "var elements = document.getElementsByTagName('img');";
Script += "var regex = new RegExp('^Copy Criterion');";
Script += "for(i=0;i<elements.length;i++){";
Script += "  if(elements[i].title.match(regex)){";
Script += "     elements[i].click();";
Script += "   }";
Script += "}";
((JavascriptExecutor) driver).executeScript(Script);


Now you got power to click any element on the screen.

Also read

Webdriver -  Issues with Sendkeys & Click

Webdriver - Select list box items
--


Wednesday, April 4, 2012

Webdriver - Store data on disk

Webdriver - Store data on disk.

There are situations where the data of the current test need to be used in the next test. In this scenario we can't store the values in variables, they are lost once the test is completed (Java program closed). It is advisable to store the data on disk using Java files.

Following are the two methods that are used to read and write data to the files.
I have used one single string where all the values are separated by ";". I can use split method to split the string into separate values.

public static void xFileWriteData(String FileName, String DataSemicolnSeperated) throws Exception   {
FileOutputStream out; 
PrintStream p; 
try
{
out = new FileOutputStream(FileName);
p = new PrintStream(out);
p.println (DataSemicolnSeperated); //Insert for loop if there is more than one line
p.close();
out.close();
}
catch (Exception e)
{
Print("Error writing to file");
}
}

public static String xFileReadData(String FileName) throws Exception   {
String DataSemicolnSeperated = null;
String Line;
try
{
BufferedReader br = new BufferedReader(new FileReader(FileName));
while ((Line = br.readLine()) != null) { 
DataSemicolnSeperated = Line;

br.close();

catch (Exception e)
{
Print("Error reading the file");
}
return DataSemicolnSeperated;
}


---- 

Webdiver - Developed in following language

Webdiver - Developed in following language

Select this link for more details


---

Tuesday, April 3, 2012

Webdriver - Not functioning or Missing clicks

Webdriver - Not functioning or Missing clicks.

I ran Webdriver code on different systems. There are instances where the code work fine in all the systems except 1 or 2 systems.
Following are the some of the solutions in this kind of scenario.

1. Files not copied properly or ant build file not created properly.

2. Browser zoom should be 100%. If it is more or less, clicks will fail.


3. When browser loose focus, sometimes clicks are not processed.

4. Browser to be operated in maximized mode. There are situation where Auto suggests values are not selected when working on not maximized mode.
JS code to maximize the browser

String script = "if (window.screen){window.moveTo(0,0);window.resizeTo(window.screen.availWidth,window.screen.availHeight);};"; 
((JavascriptExecutor) driver).executeScript(script);  

5. LAN settings to be Automatically detect settings

There are some of the trouble shooting areas.

Monday, April 2, 2012

Webdriver - How to handle UltraWebGrid

Webdriver - How to handle UltraWebGrid.

In my application to update any cell, use need to "DoubleClick" to get the cell focus and type the text. Initially I have used "SendKeys" and ".innerHTML" values get displayed on the screen, but they are not getting saved.

I have used below code to solve the issue.


Actions action = new Actions(driver);
action.doubleClick(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")));
action.perform();
action.sendKeys(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")), "Bharath");
action.perform();
Wait(5000);
action.doubleClick(driver.findElement(By.id("ctl00_cpheRFx_lblComputed")));
action.perform();
Wait(5000);

driver.findElement(By.id("ctl00_cpheRFx_btnAddRow")).click();
Wait(5000);

UltraWebGrid Screen shot



---



Webdriver - Doubleclick an element

Webdriver - Doubleclick an element.

In order to perform there events we need to use actions class. Below is the sample code.


Actions action = new Actions(driver);
action.doubleClick(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")));
action.perform();
action.sendKeys(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")), "Bharath");
action.perform();
Wait(5000);


---

Friday, March 30, 2012

Webdriver - Select list box items

Webdriver - Select list box items

HTML for the list box


I prefer using this code to select an option

driver.findElement(By.xpath("//select[@id='ctl00_cpheRFx_ddlCriteriaType']/option[@value='"+Value+"']"
)).click();

The below code also perform the same job

   WebElement ListBox = driver.findElement(By.id("ctl00_cpheRFx_ddlCriteriaType"));
   java.util.List<WebElement> options = ListBox.findElements(By.tagName("option"));
   for(WebElement option : options){
    Print(option.getText());
       if(option.getText().equals("Internal")){
           option.click();
           Print("Selected");
           break;
       }
   }


Above logic is not working for the below HTML (Below is the possible explanation)


There is one place where the IE driver does not interact with elements using native events. This is in clicking <option> elements within a<select> element. Under normal circumstances, the IE driver calculates where to click based on the position and size of the element, typically as returned by the JavaScript getBoundingClientRect() method. However, for <option> elements, getBoundingClientRect() returns a rectangle with zero position and zero size. The IE driver handles this one scenario by using the click() Automation Atom, which essentially sets the .selected property of the element and simulates the onChange event in JavaScript. However, this means that if the onChange event of the<select> element contains JavaScript code that calls alert(), confirm() or prompt(), calling WebElement's click() method will hang until the modal dialog is manually dismissed. There is no known workaround for this behavior using only WebDriver code.





I am getting empty values for "option.getText()". To over come this Webdriver limitation I have created following Java Script code.


var ListBox = document.getElementById('ctl00_cpheRFx_ddleRFxTitle');
var i;
for (i=0;i<ListBox.length;i++)
{
if (ListBox.options[i].text == 'S_05_56_52PM29_Mar_2012')
    {
    ListBox.options[i].selected ='1';
}

}


javascript:ddleRFxTitle_Change(); //To fire on change event, look at the HTML for better understanding

The same can be implemented in the Webdriver in the following way (I prefer this)


String Script = ""; Script += "var ListBox = document.getElementById('ctl00_cpheRFx_ddleRFxTitle');"; Script += "var i;"; Script += "for (i=0;i<ListBox.length;i++)"; Script += "{"; Script += " if (ListBox.options[i].text == '"+Title+"')"; Script += "{"; Script += "ListBox.options[i].selected ='1';"; Script += "}"; Script += "}"; ((JavascriptExecutor) driver).executeScript(Script); Wait(5000); Script = ""; Script += "javascript:ddleRFxTitle_Change();"; ((JavascriptExecutor) driver).executeScript(Script);



---

Thursday, March 22, 2012

Webdriver - Element Exist

Webdriver - Element Exist

I use following code to check whether an element exist.
.size() will provide the total number of elements. Make sure that your id or xPath will return the size as 1.

     if((driver.findElements(By.id("ctl00_cpheRFx_dgSuppliers_ctl0_lnkCompanyName")).size())== 1){
   
    }
    else {
    fail("Supplier Not Added Successfully");
    Print("Supplier Not Added Successfully");
     }

---- 

Monday, March 19, 2012

Webdriver - Type in FCKeditor

Webdriver - Type in FCKeditor

FCK editor is one of the complex object to handle through any automation tool.

After going through the page HTML, I have noticed two i frames. I have used following code to send message to FCK editor.



     driver.switchTo().frame(driver.findElement(By.id("ctl00_cpheRFx_Section_desc___Frame")));
    Print("Switched");
    driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@src='javascript:void(0)']")));
    Print("Switched1");    
    driver.findElement(By.xpath("//body[@contentEditable='true']"));
    WebElement editable = driver.switchTo().activeElement();
    editable.sendKeys("Selenium");
    //Inside iFrane, come back to main page
try
{
Set<String> availableWindows = driver.getWindowHandles();
Print("Handle Size:" +availableWindows.size());
//Retreive all the window handles into variables
String WindowIDparent= null, WindowIDModal = null;
int counter = 1;
for (String windowId : availableWindows) {
if (counter == 1){
Print(Integer.toString(counter)+" " + windowId);
WindowIDparent = windowId;
}
counter++;
}
//Navigate to Parent window
driver.switchTo().window(WindowIDparent);
Print("In the Parent");
Wait(2000);

}
catch (WebDriverException e)
{
e.printStackTrace();
Print("Issue in the Switch");
xKillIEs(); //driver.quit() not working with modal dialog
}


----

Webdriver - Mouse over events (Hover).

Webdriver - Mouse over events (Hover).

Read the following text from the webdriver team with respect to hovering problem.

When you attempt to hover over elements, and your physical mouse cursor is within the boundaries of the IE browser window, the hover will not work. More specifically, the hover will appear to work for a fraction of a second, and then the element will revert back to its previous state. The prevailing theory why this occurs is that IE is doing hit-testing of some sort during its event loop, which causes it to respond to the physical mouse position when the physical cursor is within the window bounds. The WebDriver development team has been unable to discover a workaround for this behavior of IE.

There are few objects and images on my web page where click() functionality is not working. I have taken lot of approaches, but the best solution found so far is below

     driver.findElement(By.xpath("//a[@id='Create']"));
    driver.findElement(By.xpath("//a[@id='Create']")).click();
The first statement will focus the element, next statement actually click the object.


I have another scenario where Image is displayed when I bring the mouse pointer on that row. To handle this situation I have used Actions class.

Below image shows display of icon when user bring the mouse pointer.


Webdriver code to click above pointed image.


Actions action = new Actions(driver);


action.moveToElement(driver.findElement(By.id("ctl00_CphePurchase_agvApprovalRequisitions$3$0$aReqNumber")));//id of requisition number
action.perform();


action.click(driver.findElement(By.id("ctl00_CphePurchase_agvApprovalRequisitions$3$0$imgBtnTrackStatus"))); //id of the image
action.perform();


Above code will not move the actual mouse pointer, but it will convey to IE that it has received a mouse input in that particular location.

For better understanding read the text from Jim (IE driver project lead).

Let me try to explain this. When simulating mouse movements with 
WebDriver, the actual mouse cursor does not move. Let me repeat that 
for emphasis. The actual physical mouse pointer on the screen *will* 
*not* *move*. If you are expecting that, you'll be disappointed. 

What WebDriver does on Windows is it sends the same messages to the IE 
window that it would receive from the input manager by the actual 
mouse. You won't see a change in the pointer on the screen, but if the 
element on the page responds to mouseover events, it should react as 
if you moved the mouse over it. 

The advantage here is that if something like an alert() method is 
called in the element's mouseOver event, WebDriver can still handle 
it. Additionally, it's a more accurate representation of the actual 
mouse movement, firing ancillary events like mouseEnter and so on. 
Contrast this approach with that of Selenium RC, which simply fires 
the mouseOver event directly via JavaScript. 

--Jim 

Still if you want to move the mouse pointer physically, you need to take different approach using Robot class


Point coordinates = driver.findElement(By.id("ctl00_portalmaster_txtUserName")).getLocation();
Robot robot = new Robot();
robot.mouseMove(coordinates.getX(),coordinates.getY()+120);

Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.

Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked.
In all browsers these are in event.screenX and event.screenY.

Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want.
In all browsers these are in event.clientX and event.clientY.

Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.

For more details select this link.



---

Thursday, March 1, 2012

Selenium Webdriver - Creating XPath

Selenium Webdriver - Creating XPath.


GUI ElementCorresponding XPath Remarks 
<input type="submit" value="Save"/>//input[@value='Save']Exactly matches the text "Save" 
<input type="submit" value="Save1"/>
<input type="submit" value="Save2"/>
//input[@value='Save1']
//input[@ type =' submit '][1]
matches the 1st input element, "Save1"
//input[@value='Save1']  
//input[@ type =' submit '][2]
matches the 2nd input element, "Save2" 

<a href="somelink">Structure</a>//a[text()="Structure"]Exactly matches the value within a given tag. Here the text "Structure" which is in between the <a> tag (anchor tag)
<a href="somelink">x_structure_y</a>//a[contains(text(),'structure')]Like wildcard search, matches the input element which has the text "structure" within a given tag
<input type="button" name="ccd_ccd_81533739_removeevent"/>
//input[contains(@name,concat("ccd","_","ccd","_")) and contains(@name,"removeevent")]
Note: The above xpath can be used when the attribute value has a part which is dynamic in nature (here in this case the text in between "ccd_" and "_removeevent" '81533739" keeps on changing everytime the GUI element is accessed)
Matching multiple text(s) pattern of a attribute value
<input type="text" value="Search..."/>//input[@type='text' and contains(@value,'Search')]Matches based on multiple attributes of a GUI element . Here the xpath of the text box is derived  based on its 'type' and 'value' attributes


Note: Contents are taken from this link

----

Selenium 2.19 - Migration of Selenium RC code to Webdriver

Selenium 2.19 - Migration of Selenium RC code to Webdriver.

This release has special feature where we can run the Selenium RC scripts in Webdriver without any changes.

Following code will help you to run the RC code

driver = RemoteWebDriver(desired_capabilities = DesiredCapabilities.FIREFOX)
selenium = DefaultSelenium('localhost', 4444', '*webdriver', 'http://www.google.com') 
selenium.start(driver = drive);

For more details select this link.

---- 

Sunday, February 26, 2012

Remote Desktop - Restart the computer

Remote Desktop - Restart the computer.

Generally we run the Selenium or QTP tests on remote systems. Some times you may require to restart the system, but there is no option provided to restart, just you can log-off.


In order to restart the computer, open the command prompt and type shutdown -r
Attaching screen shots for more clarity.


---

Friday, February 10, 2012

Webdriver - Retrieve innerHTML

Webdriver - Retrieve innerHTML

I was implementing an assertion for save transaction and was trying to retrieve the text using Gettext(), but not successful, getting null. Below is the HTML layout.

String Status = driver.findElement(By.id("spnSuccess")).getText();


Then I have implemented following JavaScript to retrieve the text.

     String script = "return document.getElementById('spnSuccess').innerHTML;";
    String Temp = (String) ((JavascriptExecutor) driver).executeScript(script);
    assertEquals(Temp,"Requisition Saved Successfully");

---