Friday, March 30, 2012

Common error in your Dialy Usage of selenium

Error Codes in Selenium:
The WebDriver API indicates the success or failure of a command invocation via a status code on the Responseobject. The following values are used and have the following meanings.
Status Code Summary Detail
0 Success The command executed successfully.
7 NoSuchElement An element could not be located on the page using the given search parameters.
8 NoSuchFrame A request to switch to a frame could not be satisfied because the frame could not be found.
9 UnknownCommand The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource.
10 StaleElementReference An element command failed because the referenced element is no longer attached to the DOM.
11 ElementNotVisible An element command could not be completed because the element is not visible on the page.
12 InvalidElementState An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element).
13 UnknownError An unknown server-side error occurred while processing the command.
15 ElementIsNotSelectable An attempt was made to select an element that cannot be selected.
17 JavaScriptError An error occurred while executing user supplied !JavaScript.
19 XPathLookupError An error occurred while searching for an element by XPath.
21 Timeout An operation did not complete before its timeout expired.
23 NoSuchWindow A request to switch to a different window could not be satisfied because the window could not be found.
24 InvalidCookieDomain An illegal attempt was made to set a cookie under a different domain than the current page.
25 UnableToSetCookie A request to set a cookie's value could not be satisfied.
26 UnexpectedAlertOpen A modal dialog was open, blocking this operation
27 NoAlertOpenError An attempt was made to operate on a modal dialog when one was not open.
28 ScriptTimeout A script did not complete before its timeout expired.
29 InvalidElementCoordinates The coordinates provided to an interactions operation are invalid.
30 IMENotAvailable IME was not available.
31 IMEEngineActivationFailed An IME engine could not be started.
32 InvalidSelector Argument was an invalid selector (e.g. XPath/CSS).

some of the Common Problems solutions given in selenium FQA's . I am not going to repete those ones. have look below link

http://code.google.com/p/selenium/w/list

Chrome: not clickable:-
------------------------

ChromeDriver always clicks the middle of the element in attempt to be faithful to what an actual user does. However, if you open Chrome and navigate to http://www.freelancersunion.org/about/index.html, you'll notice the link '1990s' is not clickable in the middle.
There are two ways to handle this currently:
1) Change/fix the page so that the user can click on the link in the middle.
2) Use the advanced user interactions API to click at the appropriate place in the link. e.g.,
ActionChains(w).move_to_element_with_offset(link, 0, 20).click().perform()

I suppose most of the 'Element is not clickable at point' errors are due to the link not actually being clickable in its middle. To check, open Chrome's developer tools via Inspect Element and hover over the element that is being clicked. Check that the middle of the bounding box that appears is actually clickable.
 
Solution:-
I guess the issue with clicking element may have something to do with element is not in the current view. For my case, following code makes it work

if u dont want to change everytime code . you will go with below one:
 
Capabilities cp = ((RemoteWebDriver) driver).getCapabilities();
if (cp.getBrowserName().equals("chrome")) 
{
try {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", 
 webElement);
    } catch (Exception e) {  }
}

 webElement.click();

otherwise your doing in single browser just use:

WebElelement we=driver.findElement(By.xpath(""));
we.click;



Monday, March 26, 2012

Selenium RC

Introduction of Selenium Remote Control

What is Selenium Remote Control?
It is the remote control for Selenium. Selenium Remote Control is a tool that allows us to test against the browser using our programming language of choice (in this case, Java).

How does Selenium Remote Control Work?
Selenium Remote Control depends on a server called—what else?—Selenium Server. The Selenium Server is capable of manipulating supported browsers and acts as a client-configured proxy between a browser and a website. This allows it to run JavaScript against a site.

RC Components:

Selenium-RC components are:

The Selenium Server which launches and kills browsers, interprets and runs the Selenese commands passed from the test program, and acts as an HTTP proxy, intercepting and verifying HTTP messages passed between the browser and the AUT.

Client libraries which provide the interface between each programming language and the Selenium-RC Server.

http://seleniumhq.org/docs/05_selenium_rc.html

The diagram shows the client libraries communicate with the Server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands. The browser, using its JavaScript interpreter, executes the Selenium command. This runs the Selenese action or verification you specified in your test script.

Selenium Server

Selenium Server receives Selenium commands from your test program, interprets them, and reports back to your program the results of running those tests.

The RC server bundles Selenium Core and automatically injects it into the browser. This occurs when your test program opens the browser (using a client library API function). Selenium-Core is a JavaScript program, actually a set of JavaScript functions which interprets and executes Selenese commands using the browser’s built-in JavaScript interpreter.

The Server receives the Selenese commands from your test program using simple HTTP GET/POST requests. This means you can use any programming language that can send HTTP requests to automate Selenium tests on the browser.

How do I use Selenium Remote Control?
In the folder structure of the download, there are two jars that we want: selenium-server.jar in the “server” folder and selenium-java-client-driver.jar in the “java” folder.

We need to be able to start and stop the Selenium Server. We can do this at the command line:

Start Selenium Server from command prompt:

java -jar selenium-server.jar

Stop Selenium Server from command prompt:

http://localhost:4444/selenium-server/driver/?cmd=shutDown

To limit configuration and external dependencies, we can do this in our test code using the SeleniumServer class:

SeleniumServer server = new SeleniumServer();

server.start();

...

server.stop();

With the server running, we may now use a client:

Selenium selenium = new DefaultSelenium( String seleniumServerHost,

int seleniumServerPort, String browserType, String baseURL);

selenium.open("http://www.somesite.com/somePage.html");

selenium.stop();

An explanation of the variables in the DefaultSelenium constructor:

  • seleniumServerHost is the where the Selenium Server is running. Typically, it is localhost.
  • seleniumServerPort is the port on which the Selenium Server is listening. The default is 4444.
  • browserType is the type of browser you want to use for testing. Common browser types are *firefox, *iexplore, *opera.
  • baseURL is the base URL for the site you are testing. To adhere to the Same Origin Policy , the Selenium object created is tied to that particular URL and can only be used for that URL.

Now, just opening a page isn’t all that useful. We need to interact with the page. To do this, we use our selenium client’s methods with locators. For example:

selnium.click("link=Text For Some Link");

The string “link=Text For Some Link” is a locator. Most of operations involve locators that tie a Selenium command to elements in an HTML document.

Locators take the form of

“locatorType=argument”

A locator type can be an element id, an element name, an xpath expression, link text, and more.

A few examples:

selenium.click(“id=idOfThing”); //an id locator

selenium.click(“name=nameOfThing”); //a name locator

selenium.click(“xpath=//img[@alt='The image alt text']”); //an xpath locator

selenium.click(“dom=document.images[56]” ); //a DOM locator

selenium.click(“link=Test Page For Selenium”); //a link locator

selenium.click(“css=span#firstChild”); //a css locator

In order to test a system, we need to be able to interact with it and make assertions about it. When the system we wish to test is a web application UI, we need to be able to interact with the page/browser and making assertions about the same. Let’s look at how we can this with Selenium Remote Control and JUnit.

The most common interactions are accomplished through the following methods in DefaultSelenium:

Ø open(String url)

Ø click(String locator)

Ø type(String locator, String value)

Ø select(String locator, String optionLocator)

Ø check(String locator)

Ø waitForPageToLoad(String timeoutInMilliseconds)

Now that we have a way of interacting, we need to be able to get information about a page. DefaultSelenium has many methods for getting information about a page. The ones that I use the most are:

Ø getTitle()

Ø getText(String locator)

Ø getValue(String locator)

Ø isEditable(String locator)

Ø isElementPresent(String locator)

Ø getSelectedLabel(String locator)

Ø getSelectedValue(String locator)

Ø isSomethingSelected(String locator)

Ø isChecked(String locator)

Ø getAlert()

Rather than trying to describe all of the methods above (that’s what the JavaDoc is for), lets look at some code.

Getting Started Using Java


First, let’s create the test class with the set up, tear down, and constants we’ll need. (Note that the example code refers to a real page.)

public class TestPageForSeleniumRemoteControlTest

extends TestCase

{

private static final String MAX_WAIT_TIME_IN_MS = "60000";

private static final String BASE_URL = "http://www.bitmotif.com";

private static final String TEST_PAGE_URL =

BASE_URL + "/test-page-for-selenium-remote-control";

private static final String TEST_PAGE_TITLE =

"Bit Motif » Test Page For Selenium Remote Control";

private Selenium selenium = new DefaultSelenium( "localhost",4444,"*firefox",BASE_URL);

private SeleniumServer seleniumServer;

public void setUp()

throws Exception

{

seleniumServer = new SeleniumServer();

seleniumServer.start();

selenium.start();

}

public void tearDown()

throws Exception

{

selenium.stop();

seleniumServer.stop();

}

}

Code examples:

Checking the Title


Now, let’s open a page and check the title.

public void test_NavigatingPages_WithoutClickingLink()

throws Exception

{

selenium.open(BASE_URL);

selenium.open(TEST_PAGE_URL);

assertEquals(TEST_PAGE_TITLE, selenium.getTitle());

}

Navigating through page


Next, let’s test clicking a link that takes us to a new page. We need to use waitForPageToLoad. If we don’t, funny things can happen. For example, we could ask for information before the page is loaded. It wouldn’t be there and the test would fail.

public void test_NavigatingPages_ClickingLink()

throws Exception

{

selenium.open(BASE_URL);

selenium.click("link=Test Page For Selenium Remote Control");

selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);

assertEquals(TEST_PAGE_TITLE, selenium.getTitle());

}

Verifying an Element Exists


If we want to check that an element exists, we can do the following:

public void testIsElementPresent()

throws Exception

{

selenium.open(TEST_PAGE_URL);

assertTrue(selenium.isElementPresent("id=textInput"));

}

Text Inputs


Let’s type something in a text box. Notice that we use the getValue to check what is in the text input.

public void testEnterValuesIntoTextField_CheckWithGetValue()
   throws Exception
{
   selenium.open(TEST_PAGE_URL);
   assertEquals("", selenium.getValue("id=textInput"));
 
   selenium.type("id=textInput", "Text In The Field");
 
   assertEquals("Text In The Field", selenium.getValue("id=textInput"));
}

What happens when we use getText to check what we typed? In this case, the text we are interested in is actually the value of the input. Since the input element does does not have any text, the getText method returns an empty string.

 public void testEnterValuesIntoTextField_CheckWithGetText()
    throws Exception
{
    selenium.open(TEST_PAGE_URL);
    assertEquals("", selenium.getText("id=textInput"));
 
    selenium.type("id=textInput", "Text In The Field");
 
    assertEquals("", selenium.getText("id=textInput"));
}
 

Checkboxes


Let’s click a checkbox:

public void testClickingACheckBox_UseCheckAndIsCheckedMethods()
   throws Exception
{
   selenium.open(TEST_PAGE_URL);
   assertFalse(selenium.isChecked("id=checkBoxInput"));
 
   selenium.check("id=checkBoxInput");
 
   assertTrue(selenium.isChecked("id=checkBoxInput"));
}
 
Now, let’s look at clicking a checkbox and checking its value a different way — let’s use click and getValue.
public void testCheckingACheckBox_UseClickAndGetValueMethods()
   throws Exception
{
   selenium.open(TEST_PAGE_URL);
   assertEquals("off", selenium.getValue("id=checkBoxInput"));
 
   selenium.click("id=checkBoxInput");
 
   assertEquals("on", selenium.getValue("id=checkBoxInput"));
}
 
Radio Buttons
When working with radio buttons, the form of the locator is a little different. In the locator, we give both the name (input name) and value (value of the radio button).
public void testClickingARadioButton_UseCheckAndIsCheckedMethods()
   throws Exception
{
   selenium.open(TEST_PAGE_URL);
 
   assertFalse(selenium.isChecked("name=radioButton value=a"));
   assertFalse(selenium.isChecked("name=radioButton value=b"));
 
   selenium.check("name=radioButton value=b");
 
   assertTrue(selenium.isChecked("name=radioButton value=b"));
   assertFalse(selenium.isChecked("name=radioButton value=a"));
}
 
We could also use click and getValue when working with radio buttons. But, it gets a little hard to work with. We can’t just ask for the value of the input. And, the individual buttons have a value of “off” or “on”. Consider:
 
public void testClickingARadioButton_UseClickAndGetValueMethods()
   throws Exception
{
   selenium.open(TEST_PAGE_URL);
   assertEquals("off", selenium.getValue("name=radioButton"));
   assertEquals("off", selenium.getValue("name=radioButton value=a"));
   assertEquals("off", selenium.getValue("name=radioButton value=b"));
 
   selenium.click("name=radioButton value=b");
 
   assertEquals("off", selenium.getValue("name=radioButton"));
   assertEquals("off", selenium.getValue("name=radioButton value=a"));
   assertEquals("on", selenium.getValue("name=radioButton value=b"));
}
Selects


Selects can be a little more complex than your average input. First, there is the select itself we must identify. Then, there are the options in the select. The options in a select may be identified with ids and values, just the visible text in the option, or some combination thereof. So, we have to use a locator for the select itself and a locator for the option(s) we are interested in. The locator of the option(s) can be the option element’s id, value, label, or index in the select.

Once something is selected, we can use getValue, getSelectedValue, and getSelectedLabel.

public void testSelectFromDropDown_NoValuesInSelect_UseLabelOptionLocator()

throws Exception

{

selenium.open(TEST_PAGE_URL);

assertEquals("option one", selenium.getSelectedLabel("id=selectWithLabelsOnly"));

assertEquals("option one", selenium.getValue("id=selectWithLabelsOnly"));

selenium.select("id=selectWithLabelsOnly", "label=option two");

assertTrue(selenium.isSomethingSelected("id=selectWithLabelsOnly"));

assertEquals("option two", selenium.getSelectedLabel("id=selectWithLabelsOnly"));

assertEquals("option two", selenium.getValue("id=selectWithLabelsOnly"));

}

Lets look at the same test but using the index verison of the select locator.

public void testSelectFromDropDown_NoValuesInSelect_UseIndexOptionLocator()

throws Exception

{

selenium.open(TEST_PAGE_URL);

assertEquals("option one", selenium.getSelectedLabel("id=selectWithLabelsOnly"));

assertEquals("option one", selenium.getValue("id=selectWithLabelsOnly"));

selenium.select("id=selectWithLabelsOnly", "index=1");

assertTrue(selenium.isSomethingSelected("id=selectWithLabelsOnly"));

assertEquals("option two", selenium.getSelectedLabel("id=selectWithLabelsOnly"));

assertEquals("option two", selenium.getValue("id=selectWithLabelsOnly"));

}

Notice what we get if we look at a select with values.

public void testSelectFromDropDown_LabelsAndValuesInSelect_UseLabelLocator()

throws Exception

{

selenium.open(TEST_PAGE_URL);

assertTrue(selenium.isSomethingSelected("id=selectWithLabelsAndValues"));

String selectedLabel = selenium.getSelectedLabel("id=selectWithLabelsAndValues");

assertEquals("option one", selectedLabel);

assertEquals("1", selenium.getValue("id=selectWithLabelsAndValues"));

assertEquals("1", selenium.getSelectedValue("id=selectWithLabelsAndValues"));

selenium.select("id=selectWithLabelsAndValues", "label=option two");

assertTrue(selenium.isSomethingSelected("id=selectWithLabelsAndValues"));

 

selectedLabel = selenium.getSelectedLabel("id=selectWithLabelsAndValues");

assertEquals("option two", selectedLabel);

assertEquals("2", selenium.getValue("id=selectWithLabelsAndValues"));

assertEquals("2", selenium.getSelectedValue("id=selectWithLabelsAndValues"));

}

Alert Boxes


Often we need to work with alert boxes. The getAlert method is the man. Invoking this method is the same as clicking “OK” on the alert box. It also returns the text in the alert box.

public void testAlertBox()
   throws Exception
{
   selenium.open(TEST_PAGE_URL);
   selenium.click("id=popUpDiv");
   assertEquals("You clicked the div.", selenium.getAlert());
}

i will cover the webdriver and some more useful Functions in my next post
Have Fun with selenium 

Sunday, March 25, 2012

WebDriver Examples

WebDrivers Examples:-

Explicit Waits:-

WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});

Implicit Waits:-

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));


Taking a Screenshot:-

import java.io.File;
import java.net.URL;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {

public void myTest() throws Exception {
WebDriver driver = new RemoteWebDriver(
new URL("http://localhost:4444/wd/hub"),
DesiredCapabilities.firefox());

driver.get("http://www.google.com");

// RemoteWebDriver does not implement the TakesScreenshot class
// if the driver does have the Capabilities to take a screenshot
// then Augmenter will add the TakesScreenshot methods to the instance
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot)augmentedDriver).
getScreenshotAs(OutputType.FILE);
}
}

Fire Fox Profilers:-
---------------------

by using the profilers we can get the firefox Extesions and by default its not show the extesions.


ProfileIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("WebDriver");
profile.setPreferences("foo.bar", 23);
WebDriver driver = new FirefoxDriver(profile);

if the profile isn’t already registered with Firefox:

File profileDir = new File("path/to/top/level/of/profile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.addAdditionalPreferences(extraPrefs);
WebDriver driver = new FirefoxDriver(profile)

Enable the native events in firefox:

FirefoxProfile profile = new FirefoxProfile();
profile.setEnableNativeEvents(true);
WebDriver driver = new FirefoxDriver(profile);

Locating UI Elements (WebElements):-
----------------------------------

this can be done bye two ways one is by using the webdriver instance, second one is by using the webelement

By ID, By Name,

By Class Name:-

“Class” in this case refers to the attribute on the DOM element.
example:

Cheddar
Gouda


List cheeses = driver.findElements(By.className("cheese"));

By Tag Name:-


WebElement frame = driver.findElement(By.tagName("iframe"));

By Link Text:-

cheese>
WebElement cheese = driver.findElement(By.linkText("cheese"));

By Partial Link Text:-

search for cheese>
WebElement cheese = driver.findElement(By.partialLinkText("cheese"));

By CSS:-

If a browser does not have native support for css queries, then Sizzle is used. IE 6,7 and FF3.0 currently use Sizzle as the css query engine.
Beware that not all browsers were created equal, some css that might work in one version may not work in another.

milkcheese

WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));

By XPATH:-

At a high level, WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation.

internet exporer doesnt have the Native XPath Support for that we will do manually. Tag and Attribute Name must be lower cased.



List inputs = driver.findElements(By.xpath("//input"));

Using JavaScript:-

Cheddar
Gouda

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]");

Finding all the input elements to the every label on a page:

List labels = driver.findElements(By.tagName("label"));
List inputs = (List) ((JavascriptExecutor)driver).executeScript(
"var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);

User Input - Filling In Forms:-
-------------------------------
the state of checkboxes, and you can use “click” to set something like an OPTION tag selected.

WebElement select = driver.findElement(By.tagName("select"));
List allOptions = select.findElements(By.tagName("option"));
for (WebElement option : allOptions) {
System.out.println(String.format("Value is: %s", option.getAttribute("value")));
option.click();
}

WebDriver’s support classes include one called “Select”, which provides useful methods for interacting with these.

Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();
select.selectByVisibleText("Edam");

Once you’ve finished filling out the form, you probably want to submit it. One way to do this would be to find the “submit” button and click it:

driver.findElement(By.id("submit")).click();

or
WebDriver has the convenience method “submit” on every element.

element.submit();

Moving Between Windows and Frames:-
---------------------------------

driver.switchTo().window("windowName");

For unknown Window titles we can use the window handle method

for (String handle : driver.getWindowHandles())
{
driver.switchTo().window(handle);
}

Drag And Drop Commands:-

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



Webdriver gives us very facinating soultion by Using the Action clause. here the sample code.....









Actions builder = new Actions(driver);

Action dragAndDrop = builder.clickAndHold(someElement)
    .moveToElement(otherElement)
    .release(otherElement)
    .build();
    dragAndDrop.perform();
    (Or)
  i assumed , you will alreday intialize the webdriver:
 
    driver.get("http://html5demos.com/drag")
    target = @driver.find_element(:id, "one")
    source = @driver.find_element(:id, "bin")
    driver.action.drag_and_drop(target, source).perform
 

Taking the ScrrenShot :-

Here You will see the code for Taking the screen shot when something goes wrong in your application. its working fine with the Chrome and IE but Firefox its opening the new Empty window. if you guys found any soulution for this plz update accordingly.

 

public static void  capturescreen(String Testname,String step,WebDriver driver)throws Exception
    {   
 String path="FloderPath/html folder/Screenshots/"+Testname+"/"+step+".png";
 WebDriver augmentedDriver = new Augmenter().augment(driver);
 File scrFile=((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path));
  }

use it as like below:

  capturescreen(String Testname,String step,WebDriver driver);