Saturday, January 25, 2014

selenium.webdriver.remote.command



ACCEPT_ALERT = 'acceptAlert'


CLEAR_APP_CACHE = 'clearAppCache'

CLEAR_ELEMENT = 'clearElement'

CLEAR_LOCAL_STORAGE = 'clearLocalStorage'

CLEAR_SESSION_STORAGE = 'clearSessionStorage'

CLICK = 'mouseClick'

CLICK_ELEMENT = 'clickElement'

CLOSE = 'close'

DELETE_ALL_COOKIES = 'deleteAllCookies'


DELETE_SESSION = 'deleteSession'

DISMISS_ALERT = 'dismissAlert'

DOUBLE_CLICK = 'mouseDoubleClick'

DOUBLE_TAP = 'touchDoubleTap'

DRAG_ELEMENT = 'dragElement'

ELEMENT_EQUALS = 'elementEquals'

EXECUTE_ASYNC_SCRIPT = 'executeAsyncScript'

EXECUTE_SCRIPT = 'executeScript'

EXECUTE_SQL = 'executeSql'

FIND_CHILD_ELEMENT = 'findChildElement'

FIND_CHILD_ELEMENTS = 'findChildElements'

FIND_ELEMENT = 'findElement'

FIND_ELEMENTS = 'findElements'

FLICK = 'touchFlick'

GET = 'get'

GET_ACTIVE_ELEMENT = 'getActiveElement'

GET_ALERT_TEXT = 'getAlertText'

GET_ALL_COOKIES = 'getCookies'

GET_APP_CACHE = 'getAppCache'

GET_APP_CACHE_STATUS = 'getAppCacheStatus'


GET_CURRENT_URL = 'getCurrentUrl'

GET_CURRENT_WINDOW_HANDLE = 'getCurrentWindowHandle'

GET_ELEMENT_ATTRIBUTE = 'getElementAttribute'

GET_ELEMENT_LOCATION = 'getElementLocation'

GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW = 'getElementLocationOnceScrolledIntoView'

GET_ELEMENT_SIZE = 'getElementSize'

GET_ELEMENT_TAG_NAME = 'getElementTagName'

GET_ELEMENT_TEXT = 'getElementText'

GET_ELEMENT_VALUE = 'getElementValue'

GET_ELEMENT_VALUE_OF_CSS_PROPERTY = 'getElementValueOfCssProperty'

GET_LOCAL_STORAGE_ITEM = 'getLocalStorageItem'

GET_LOCAL_STORAGE_KEYS = 'getLocalStorageKeys'

GET_LOCAL_STORAGE_SIZE = 'getLocalStorageSize'

GET_LOCATION = 'getLocation'

GET_PAGE_SOURCE = 'getPageSource'

GET_SCREEN_ORIENTATION = 'getScreenOrientation'

GET_SESSION_STORAGE_ITEM = 'getSessionStorageItem'

GET_SESSION_STORAGE_KEYS = 'getSessionStorageKeys'

GET_SESSION_STORAGE_SIZE = 'getSessionStorageSize'

GET_SPEED = 'getSpeed'

GET_TITLE = 'getTitle'

GET_WINDOW_HANDLES = 'getWindowHandles'

GET_WINDOW_POSITION = 'getWindowPosition'

GET_WINDOW_SIZE = 'getWindowSize'

GO_BACK = 'goBack'

GO_FORWARD = 'goForward'

HOVER_OVER_ELEMENT = 'hoverOverElement'

IMPLICIT_WAIT = 'implicitlyWait'

IS_BROWSER_ONLINE = 'isBrowserOnline'

IS_BROWSER_VISIBLE = 'isBrowserVisible'

IS_ELEMENT_DISPLAYED = 'isElementDisplayed'

IS_ELEMENT_ENABLED = 'isElementEnabled'

IS_ELEMENT_SELECTED = 'isElementSelected'

LONG_PRESS = 'touchLongPress'

MAXIMIZE_WINDOW = 'windowMaximize'

MOUSE_DOWN = 'mouseButtonDown'

MOUSE_UP = 'mouseButtonUp'

MOVE_TO = 'mouseMoveTo'

NEW_SESSION = 'newSession'

QUIT = 'quit'

REFRESH = 'refresh'

REMOVE_LOCAL_STORAGE_ITEM = 'removeLocalStorageItem'

REMOVE_SESSION_STORAGE_ITEM = 'removeSessionStorageItem'

SCREENSHOT = 'screenshot'

SEND_KEYS_TO_ACTIVE_ELEMENT = 'sendKeysToActiveElement'

SEND_KEYS_TO_ELEMENT = 'sendKeysToElement'

SET_ALERT_VALUE = 'setAlertValue'

SET_BROWSER_ONLINE = 'setBrowserOnline'

SET_BROWSER_VISIBLE = 'setBrowserVisible'

SET_ELEMENT_SELECTED = 'setElementSelected'

SET_LOCAL_STORAGE_ITEM = 'setLocalStorageItem'

SET_LOCATION = 'setLocation'

SET_SCREEN_ORIENTATION = 'setScreenOrientation'

SET_SCRIPT_TIMEOUT = 'setScriptTimeout'

SET_SESSION_STORAGE_ITEM = 'setSessionStorageItem'

SET_SPEED = 'setSpeed'

SET_TIMEOUTS = 'setTimeouts'

SET_WINDOW_POSITION = 'setWindowPosition'

SET_WINDOW_SIZE = 'setWindowSize'

SINGLE_TAP = 'touchSingleTap'

SUBMIT_ELEMENT = 'submitElement'

SWITCH_TO_FRAME = 'switchToFrame'

SWITCH_TO_WINDOW = 'switchToWindow'

TOGGLE_ELEMENT = 'toggleElement'

TOUCH_DOWN = 'touchDown'

TOUCH_MOVE = 'touchMove'

TOUCH_SCROLL = 'touchScroll'

TOUCH_UP = 'touchUp'

UPLOAD_FILE = 'uploadFile'

Selenium Web Driver Command List

Commands                                             

driver.get("http://www.google.com"); To open an application
driver.findElement(By.id("passwd-id")); Finding Element using Id
driver.findElement(By.name("passwd")); Finding Element using Name
driver.findElement(By.xpath("//input[@id=’passwd-id’]")); Finding Element using Xpath
element.sendKeys("some text"); To type some data
element.clear(); clear thecontents of a text field or textarea
driver.findElement(By.xpath("//select")); Selecting the value
select.findElements(By.tagName("option")); Selecting the value
select.deselectAll(); This will deselect all OPTIONs from the first SELECT on the page
select.selectByVisibleText("Edam"); select the OPTION withthe displayed text of “Edam”
findElement(By.id("submit")).click(); To click on Any button/Link
driver.switchTo().window("windowName"); Moving from one window to another window
driver.switchTo().frame("frameName"); swing from frame to frame (or into iframes)
driver.switchTo().frame("frameName.0.child"); to access subframes by separating the path with a dot, and you can specify the frame by itsindex too.
driver.switchTo().alert(); Handling Alerts
driver.navigate().to("http://www.example.com"); To Navigate Paeticular URL
driver.navigate().forward(); To Navigate Forward
driver.navigate().back(); To Navigate Backword
driver.close() Closes the current window
driver.quit() Quits the driver and closes every associated window.
driver.switch_to_alert() Switches focus to an alert on the page.
driver.refresh() Refreshes the current page.
driver.implicitly_wait(30) Amount of time to wait
driver.set_script_timeout(30) The amount of time to wait

Commonly Used Selenium Commands


To conclude our introduction of Selenium, we’ll show you a few typical Selenium commands. These are probably the most commonly used commands for building tests.
open
opens a page using a URL.
click/clickAndWait
performs a click operation, and optionally waits for a new page to load.
verifyTitle/assertTitle
verifies an expected page title.
verifyTextPresent
verifies expected text is somewhere on the page.
verifyElementPresent
verifies an expected UI element, as defined by its HTML tag, is present on the page.
verifyText
verifies expected text and its corresponding HTML tag are present on the page.
verifyTable
verifies a table’s expected contents.
waitForPageToLoad
pauses execution until an expected new page loads. Called automatically when clickAndWait is used.
waitForElementPresent
pauses execution until an expected UI element, as defined by its HTML tag, is present on the page.

How to integrate a JUnit4 – Webdriver test into JMeter

JMeter is an open source load testing tool, with many capabilities. One of the many interesting things which can be done is to integrate a webdriver test into a JMeter test suite.
Before start make sure that Java and JMeter properly installed, and the webdriver libraries are downloaded. You can download them from the following links:

The following step is to create a new project in Eclipse with a webdriver test. To keep it simple the test just hits the google.com page, and will check its title.
To create a project:
- Click File -> New- > Java Project
New Java Project
New Java Project
- Enter project name -> click Finish
New Java Project Name
New Java Project Name

Webdriver – XPath and CSS selector performance tip

There are cases when using XPath has some advantages over CSS selectors.
For example if there is a site where we can select an item only by text because the other type of locators are not clear(id’s and classes are generated and they are used in multiple places).
What can we do in this situation?
  1. Use a CSS locator to select multiple elements and then call the getText() function and compare the results with the selected string
    This is a working solution, but Webdriver calls are expensive and it can really slow down test runs in IE8 and IE9 browsers.
  2. Use the XPath’s contains function to select the element by its text value
    span[contains(text(),'Text to search for')]
Short background story:
To solve our initial problem using CSS we have been forced to use the getText() function to be able to compare the text and get the appropriate element.
When we came up with the 2. solution the overall run time of the tests have been reduced and the test runs became more stable in IE8 and IE9.

How to use TestNG with Selenium WebDriver

(The precondition for this tutorial that the Selenium WebDriver is already installed.)
Firstly go to TestNG website’s download page, and follow the instructions to install the TestNG plugin to Eclipse. (http://testng.org/doc/download.html)
After the TestNG was installed, create a new java class file (without main method).
Create the setUp() function. To this function you can put that the WebDriver use for example the Firefox browser, and for example that the driver get the desired webpage.
This function will start before the test. To ensure that, before the setUp() function need to put @BeforeClass annotation.
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
If you use only one test in the java file then you can use the @BeforeTest annotation too.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.

Basic HTTP authentication and Webdriver

I encountered an interesting problem last week.
I had to make an automated test scripts on a test site which was protected by Basic HTTP Authentication.
I’ll assume that everybody knows how Basic HTTP Authentication works and will just focus on the solution:

 WebDriver driver = new ChromeDriver();
 driver.get("http://username:password@URL");

Of course you should change the username, password and URL strings to your data .
To pass the basic http authentication in firefox, you have to set a browser preference during the driver creation.

 FirefoxProfile profile = new FirefoxProfile();
 profile.SetPreference("network.http.phishy-userpass-length", 255);
 driver = new FirefoxDriver(profile);
 driver.get("http://username:password@URL");

How to execute JavaScript using Selenium WebDriver


With Java Script we can access the DOM Properties. By doing so we can get the properties values of those objects.

Say i have a Div or a Span control like below:
<Div id="SampleDiv1">I am in Div</Div> or
<Span id="SampleSpan1">I am in Span</Div>

Here we have two solutions to get the value of the objects.

Solution 1: Use the getAttribute method.
This method is described in below location:
http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#getAttribute%28java.lang.String%29

So for ex above, we can use like:
String sReturnText=driver.findElement(By.id("SampleSpan1")).getAttribute("innerHTML");
System.out.println(sReturnText);


Because in the above example we are trying to get text from the control we can directly use getText method like below:
String sReturnText=driver.findElement(By.id("SampleSpan1")).getText();
System.out.println(sReturnText);

Solution 2: We can get the DOM properties be JavaScript
There might be situations you will be needing to run the JavaScript in your automation. To do this/cover the example follow below steps:
String sJScript = "return document.getElementById('SampleSpan1').innerHTML;";
String sReturnText = (String) ((JavascriptExecutor) driver).executeScript(sJScript);
 System.out.println(sReturnText);

How to right click and choose an option using Selenium WebDriver


There is no direct way to choose an option after right clicking using Selenium WebDriver.

For Ex: what i mean here is say you open google.com
and then right click on "About Google" and have to choose "Open Link in new Tab"

In Selenium WebDriver there is no direct way to do this.

The work around is clicking {DOWN} button. But there is a disadvantage in this approach, suppose if your options dynamically change then this approach wont work.

Here is the sample code for the above approach:

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class RightClickAndChooseAnOption
{
    public static void main(String[] args)
    {
        WebDriver driver=new FirefoxDriver();
        driver.navigate().to("http://www.google.com");
       
        driver.manage().window().maximize();
       
        WebElement oWE=driver.findElement(By.linkText("About Google"));
       
        Actions oAction=new Actions(driver);
        oAction.moveToElement(oWE);
        oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
       
    }

}

How to switch between different windows using Selenium WebDriver


Inorder to switch between Windows we should be knowing the window handlers and traverse between windows.

For that i am opening the link in a new window using clicking down button, after that moving to the specified window.

Here is the code:
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class MoveBetweenTabs
{
    public static void main(String[] args)
    {
        WebDriver driver=new FirefoxDriver();
        driver.navigate().to("http://www.google.com");
       
        driver.manage().window().maximize();
       
        WebElement oWE=driver.findElement(By.linkText("About Google"));
       
        Actions oAction=new Actions(driver);
        oAction.moveToElement(oWE);
        oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
       
        Set<String> sHandlers= driver.getWindowHandles();
        for(String sHandler:sHandlers)
        {
       
            if(driver.switchTo().window(sHandler).getTitle().equals("Google"))
            {
                driver.switchTo().window(sHandler);
                WebElement oWE1=driver.findElement(By.linkText("+Google"));
                oWE1.click();
            }
        }
    }
}

How to choose Ext JS Combo values using Selenium WebDriver


When we see Ext JS Combo box, it looks like a ordinary combo box and when we try
Select oSel=
new Select(oCategoryItems);
List<WebElement> oListItems=oSel.getOptions();

It throws an error message saying,
Element should have been "select" but was "input"

The reason being Ext JS combo box are not just combo boxes, they combination of controls like,
<Input> and <Image> or <em>
<input> and <Select>

You can see the sample combo box object in Naukri.com website, which is attached


So inorder to select these items, first we need to click on the Input object and then select the value.

Following is the code for printing out all the values, you can use whatever function you want after clicking the object.


 
import
java.util.List;
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.support.ui.Select;
 
public
class PrintListBoxValues
{
public static void main(String[] args)
{
WebDriver driver=
new FirefoxDriver();
driver.get(
"http://www.naukri.com/");
WebElement oCategory=driver.findElement(By.id(
"farea"));
oCategory.click();
WebElement oCategoryItems=driver.findElement(By.id(
"fareaSL"));
Select oSel=
new Select(oCategoryItems);
List<WebElement> oListItems=oSel.getOptions();
for(int i=1;i<=oListItems.size()-1;i++)
{
System.
out.println(oListItems.get(i).getText());
}
}
}

How to check the object existance


Here in the below code, i am checking for an object existence.

    //Max_TimeOut variable holds the time in seconds for the maximum time to wait before the control flows to NoSuchElementException block.
    int Max_TimeOut=60;
    public boolean isObjExists(WebDriver driver,By locator)
    {
        //I am putting the code in try catch because if the object does not exist, it throws exception.
        try
        {
            //Before throwing exception, it will wait for the Max_timeout specified
            WebDriverWait wait=new WebDriverWait(driver,Max_TimeOut);
            wait.until(ExpectedConditions.elementToBeClickable(locator));
            //If the element found, then it returns true
            return true;
        }
        catch(NoSuchElementException exception)
        {
            //If the element is not found, then it returns false
            return false;
        }
       
    }

This function can be invoked in like below:
        By locator=By.name("Email");
        if(obj.isObjExists(driver, locator))
        {
            Reporter.log("Object exists");
            WebElement uNameElement=driver.findElement(locator);
            uNameElement.sendKeys("abcd");
        }
        else
        {
            Reporter.log("Object does not exist");
        }

What is the difference between WebDriver.close() and WebDriver.quit()


WebDriver.close() method closes the current window.

See the below example, here it opens the new link in a different window and upon executing the close() method, it closes the parent window and leaving the new window open.

WebDriver driver=new FirefoxDriver();
driver.get("http://google.com");
driver.manage().window().maximize();
WebElement oWE=driver.findElement(By.linkText("About Google"));
Actions oAction=new Actions(driver);
oAction.moveToElement(oWE);
oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
driver.close();

Whereas, WebDriver.quit() method quits the driver, and closing every associated window.
In the above example, if you use driver.quit() in place of close , then first opens "google" page and then open the "about google" in new window and closes both the windows.