Monday, 6 April 2015

Learn Selenium Webdriver.

                 Selenium - Webdriver


WebDriver is a tool for automating testing web applications. It is popularly known as Selenium 2.0. WebDriver uses a different underlying framework, while Selenium RC uses JavaScript Selenium-Core embedded within the browser which has got some limitations. WebDriver interacts directly with the browser without any intermediary, unlike Selenium RC that depends on a server. It is used in the following context:
  • Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0).
  • Handling multiple frames, multiple browser windows, popups, and alerts.
  • Complex page navigation.
  • Advanced user navigation such as drag-and-drop.
  • AJAX-based UI elements.

Architecture

WebDriver is best explained with a simple architecture diagram as shown below.
Selenium IDE 92

Selenium RC Vs WebDriver

Selenium RCSelenium WebDriver
The architecture of Selenium RC is complicated, as the server needs to be up and running before starting a test.WebDriver's architecture is simpler than Selenium RC, as it controls the browser from the OS level.
Selenium server acts as a middleman between the browser and Selenese commands.WebDriver interacts directly with the browser and uses the browser's engine to control it.
Selenium RC script execution is slower, since it uses a Javascript to interact with RC.WebDriver is faster, as it interacts directly with the browser.
Selenium RC cannot support headless execution as it needs a real browser to work with.WebDriver can support the headless execution.
It's a simple and small API.Complex and a bit large API as compared to RC.
Less object-oriented API.Purely object oriented API.
Cannot test mobile Applications.Can test iPhone/Android applications.

Scripting using WebDriver

Let us understand how to work with WebDriver. For demonstration, we would use http://www.calculator.net/. We will perform a "Percent Calculator" which is located under "Math Calculator". We have already downloaded the required WebDriver JAR's. Refer the chapter "Environmental Setup" for details.
Step 1 : Launch "Eclipse" from the Extracted Eclipse folder.
Selenium IDE 75
Step 2 : Select the Workspace by clicking the 'Browse' button.
Selenium IDE 76
Step 3 : Now create a 'New Project' from 'File' menu.
Selenium IDE 53
Step 4 : Enter the Project Name and Click 'Next'.
Selenium IDE 77
Step 5 : Go to Libraries Tab and select all the JAR's that we have downloaded. Add reference to all the JAR's of Selenium WebDriver Library folder and also selenium-java-2.42.2.jar and selenium-java-2.42.2-srcs.jar.
Selenium IDE 78
Step 6 : The Package is created as shown below.
Selenium IDE 79
Step 7 : Now right-click on the package and select 'New' >> 'Class' to create a 'class'.
Selenium IDE 82
Step 8 : Now name the class and make it the main function.
Selenium IDE 80
Step 9 : The class outline is shown as below.
Selenium IDE 81
Step 10 : Now it is time to code. The following script is easier to understand, as it has comments embedded in it to explain the steps clearly. Please take a look at the chapter "Locators" to understand how to capture object properties.
import java.util.concurrent.TimeUnit;

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

public class webdriverdemo {
   public static void main(String[] args) {
   
      WebDriver driver = new FirefoxDriver();
      //Puts an Implicit wait, Will wait for 10 seconds before throwing exception
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      
      //Launch website
      driver.navigate().to("http://www.calculator.net/");
      
      //Maximize the browser
      driver.manage().window().maximize();
      
      // Click on Math Calculators
      driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();
      
      // Click on Percent Calculators
      driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();
      
      // Enter value 10 in the first number of the percent Calculator
      driver.findElement(By.id("cpar1")).sendKeys("10");
      
      // Enter value 50 in the second number of the percent Calculator
      driver.findElement(By.id("cpar2")).sendKeys("50");
      
      // Click Calculate Button
      driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click();
      
      // Get the Result Text based on its xpath
      String result = driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText();
      
      // Print a Log In message to the screen
      System.out.println(" The Result is " + result);
      
      //Close the Browser.
      driver.close();
   }
}
Step 11 : The output of the above script would be printed in Console.
Selenium IDE 83

Most Used Commands

The following table lists some of the most frequently used commands in WebDriver along with their syntax.
CommandDescription
driver.get("URL")To navigate to an application.
element.sendKeys("inputtext")Enter some text into an input box.
element.clear()Clear the contents from the input box.
select.deselectAll()Deselect all OPTIONs from the first SELECT on the page.
select.selectByVisibleText("some text")Select the OPTION with the input specified by the user.
driver.switchTo().window("windowName")Move the focus from one window to another.
driver.switchTo().frame("frameName")Swing from frame to frame.
driver.switchTo().alert()Helps in handling alerts.
driver.navigate().to("URL")Navigate to the URL.
driver.navigate().forward()To navigate forward.
driver.navigate().back()To navigate back.
driver.close()Closes the current browser associated with the driver.
driver.quit()Quits the driver and closes all the associated window of that driver.
driver.refresh()Refreshes the current page.

Monday, 30 March 2015

Selenium - Selenese Commands

Selenese Commands

A command refers to what Selenium has to do and commands in selenium are of three types. Click on each one of them to know more about the commands.
Actions:
Actions are commands that manipulate the state of the application. Upon execution, if an action fails the execution of the current test is stopped. For Example, "click a link" and "select an option".
The following table lists the Selenium action commands that are used very frequently, however the list is note exhaustive.
Command/SyntaxDescription
click (locator)Clicks on a link, button, checkbox or radio button
clickAt (locator,coordString)Clicks on an element with the help of locator and co-ordinates
close()Simulates the user clicking the "close" button in the title bar of a popup window or tab.
contextMenuAt (locator,coordString)Simulates opening the context menu of the specified element from a specified location
doubleClick (locator)Double clicks on a webelement based on the specified element.
dragAndDrop (locator,movementsString)Drags an element and then drops it based on specified distance.
dragAndDropToObject (Dragobject,dropobject)Drags an element and drops it on another element.
echo (message)Prints the specified message on console which is used for debugging.
fireEvent (locator,eventName)Explicitly simulate an event, to trigger the corresponding "onevent" handler
focus (locator)Move the focus to the specified element
highlight (locator)Changes the background Color of the specified element to yellow Briefly which is useful for debugging purposes.
mouseDown (locator)Simulates a user pressing the left mouse button on the specified element.
mouseDownAt (locator,coordString)Simulates a user pressing the left mouse button at the specified location on the specified element.
mouseUp (locator)Simulates the event that occurs when the user releases the mouse button
mouseUpAt (locator,coordString)Simulates the event that occurs when the user releases the mouse button at the specified location.
open (url)Opens an URL in the specified browser and it accepts both relative and absolute URLs.
openWindow (url,windowID)Opens a popup window. After opening the window, user need to activate it using the selectWindow command.
pause (waitTime)Waits for the specified amount of time (in milliseconds)
refresh()Simulates the user clicking the "Refresh" button on their browser.
select (selectLocator,optionLocator)Select an option from a drop-down using an option locator.
selectWindow (windowID)Selects a popup window using a window locator; once a popup window has been selected, all focus shifts to that window.
store (expression,variableName)The name of a variable in which the result is to be stored and expression is the value to store
type (locator,value)Sets the value of an input field, similar to user typing action.
typeKeys (locator,value)Simulates keystroke events on the specified element, as though you typed the value key-by-key.
waitForCondition (script,timeout)Executes the specified JavaScript snippet repeatedly until it evaluates to "true".
waitForPageToLoad (timeout)Waits for a new page to load.
waitForPopUp (windowID,timeout)Waits for a popup window to appear and load.
windowFocus()Gives focus to the currently selected window
windowMaximize()Resize currently selected window to take up the entire screen
Accessors:
Accessors evaluate the state of the application and store the results in a variable which are used in assertions. For Example, "storeTitle".
The following table lists the Selenium accessors that are used very frequently, however the list is not exhaustive.
Command/SyntaxDescription
assertErrorOnNext (message)Pings Selenium to expect an error on the next command execution with an expected message.
storeAllButtons (variableName)Returns the IDs of all buttons on the page.
storeAllFields (variableName)Returns the IDs of all input fields on the page.
storeAllLinks (variableName)Returns the IDs of all links on the page.
storeAllWindowIds (variableName)Returns the IDs of all windows that the browser knows about in an array.
storeAllWindowTitles (variableName)Returns the names of all windows that the browser knows about in an array.
storeAllWindowNames (variableName)Returns the titles of all windows that the browser knows about in an array.
storeAttribute (attributeLocator, variableName)Gets the value of an element attribute. The value of the attribute may differ across browsers.
storeBodyText (variableName)Gets the entire text of the page.
storeConfirmation (variableName)Retrieves the message of a JavaScript confirmation dialog generated during the previous action.
storeElementIndex (locator, variableName)Get the relative index of an element to its parent (starting from 0).
storeLocation (variableName)Gets the absolute URL of the current page.
storeSelectedIds (selectLocator,variableName)Gets all element IDs for selected options in the specified select or multi-select element.
storeSelectedIndex (selectLocator, variableName)Gets index (option number, starting at 0) for selected option in the specified select element.
storeSelectedLabel (selectLocator, variableName)Gets label (visible text) for selected option in the specified select element..
storeSelectedValue (selectLocator,variableName)Gets value (value attribute) for selected option in the specified select element.
storeSelectOptions (selectLocator,variableName)Gets all labels in the specified select drop-down.
storeTable (tableCellAddress, variableName)Gets the text from a cell of a table. The cellAddress syntax: tableLocator.row.column, where row and column start at 0.
storeText (locator, variableName)Gets the text of an element. This works for any element that contains text.
storeTitle (variableName)Gets the title of the current page.
storeValue (locator,variableName)Gets the (whitespace-trimmed) value of an input field.
storeChecked (locator, variableName)Gets whether a toggle-button (checkbox/radio) is checked.
storeElementPresent (locator, variableName)Verifies that the specified element is somewhere on the page.
storeTextPresent (pattern, variableName)Verifies that the specified text pattern appears somewhere on the rendered page shown to the user.
storeVisible (locator, variableName)Determines if the specified element is visible.
Assertions:
Assertions enable us to verify the state of an application and compares against the expected. It is used in 3 modes, viz. - "assert", "verify", and "waitfor". For Example, "verify if an item form the dropdown is selected".
The following table lists the Selenium assertions that are used very frequently, however the list is not exhaustive.
Command/SyntaxDescription
waitForErrorOnNext (message)Waits for error; used with the accessor assertErrorOnNext.
verifySelected(selectLocator, optionLocator)Verifies that the selected option of a drop-down satisfies the optionSpecifier.
waitForSelected (selectLocator, optionLocator)Waits for getting the option selected; used with the accessor assertSelected.
waitForNotSelected (selectLocator, optionLocator)Waits for not getting the option selected; used with accessor the assertSelected.
verifyAlert (pattern)Verifies the alert text; used the with accessor storeAlert.
waitForAlert (pattern)Waits for the alert; used with the accessor storeAlert.
verifyAllButtons (pattern)Verifies the button; used with the accessor storeAllButtons.
waitForAllButtons (pattern)Waits for the button to load; used with the accessor storeAllButtons.
verifyAllLinks (pattern)Verifies all links; used with the accessor storeAllLinks.
waitForAllLinks (pattern)Waits for all links; used with the accessor storeAllLinks.
verifyAllWindowIds (pattern)Verifies the window id; used with the accessor storeAllWindowIds.
waitForAllWindowIds (pattern )Waits the window id; used with the accessor storeAllWindowIds.
verifyAttribute(attributeLocator, pattern)Verifies an attribute of an element; used with the accessor storeAttribute.
waitForAttribute(attributeLocator, pattern)Waits for an attribute of an element; used with accessor storeAttribute.
verifyBodyText(pattern)Verifies the body text; used with the accessor storeBodyText.
waitForBodyText(pattern)Waits for the body text; used with the accessor storeBodyText.
waitForConfirmation(pattern)Waits for confirmation; used with the accessor storeConfirmationPresent.

Locators

Element Locators help Selenium to identify the HTML element the command refers to. All these locators can be identified with the help of FirePath and FireBug plugin of Mozilla. Please refer the Environment Setup chapter for details.
  • identifier=id Select the element with the specified "id" attribute and if there is no match, select the first element whose @name attribute is id.
  • id=id Select the element with the specified "id" attribute.
  • name=name Select the first element with the specified "name" attribute
  • dom=javascriptExpression Selenium finds an element by evaluating the specified string that allows us to traverse through the HTML Document Object Model using JavaScript. Users cannot return a value but can evaluate as an expression in the block.
  • xpath=xpathExpression Locate an element using an XPath expression.
  • link=textPattern Select the link element (within anchor tags) which contains text matching the specified pattern.
  • css=cssSelectorSyntax Select the element using css selector.

Learn What Is Selenium-RC(Remote Control) And It's Architecture.

Selenium - Remote Control


Selenium Remote Control (RC) was the main Selenium project that sustained for a long time before Selenium WebDriver(Selenium 2.0) came into existence. Now Selenium RC is hardly in use, as WebDriver offers more powerful features, however users can still continue to develop scripts using RC.
It allows us to write automated web application UI tests with the help of full power of programming languages such as Java, C#, Perl, Python and PHP to create more complex tests such as reading and writing files, querying a database, and emailing test results.

Selenium RC Architecture

Selenium RC works in such a way that the client libraries can communicate with the Selenium RC Server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands.
The browser executes the Selenium command using its JavaScript interpreter.
Selenium IDE 52
Selenium RC comes in two parts.
  • The Selenium Server launches and kills browsers. In addition to that, it interprets and executes the Selenese commands. It also acts as an HTTP proxy by intercepting and verifying HTTP messages passed between the browser and the application under test.
  • Client libraries that provide an interface between each one of the programming languages (Java, C#, Perl, Python and PHP) and the Selenium-RC Server.

RC Scripting

Now let us write a sample script using Selenium Remote Control. Let us use http://www.calculator.net/ for understanding Selenium RC. We will perform a Percent calculation using 'Percent Calculator' that is present under the 'Math Calculators' module.
Step 1 : Start Selenium Remote Control (with the help of command prompt).
Step 2 : After launching Selenium RC, open Eclipse and create a "New Project" as shown below.
Selenium IDE 53
Step 3 : Enter the project name and click 'Next' button.
Selenium IDE 54
Step 4 : Verify the Source, Projects, Libraries, and Output folder and click 'Finish'.
Selenium IDE 55
Step 5 : Right click on 'project' container and choose 'Configure Build Path'.
Selenium IDE 56
Step 6 : Properties for 'selrcdemo' opens up. Navigate to 'Libraries' tab and select 'Add External JARs'. Choose the Selenium RC jar file that we have downloaded and it would appear as shown below.
Selenium IDE 57
Step 7 : The referenced Libraries are shown as displayed below.
Selenium IDE 58
Step 8 : Create a new class file by performing a right click on 'src' folder and select 'New' >> 'class'.
Selenium IDE 59
Step 9 : Enter a name of the class file and enable 'public static void main' as shown below.
Selenium IDE 60
Step 10 : The Created Class is created under the folder structure as shown below.
Selenium IDE 70
Step 11 : Now it is time for coding. The following code has comments embedded in it to make the readers understand what has been put forth.
package selrcdemo;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class rcdemo {
   public static void main(String[] args) throws InterruptedException {
   
      // Instatiate the RC Server
      Selenium selenium = new DefaultSelenium("localhost", 4444 , "firefox", "http://www.calculator.net");
      selenium.start();   // Start
      selenium.open("/");  // Open the URL
      selenium.windowMaximize();
      
      // Click on Link Math Calculator
      selenium.click("xpath=.//*[@id='menu']/div[3]/a");
      Thread.sleep(2500); // Wait for page load
      
      // Click on Link Percent Calculator
      selenium.click("xpath=.//*[@id='menu']/div[4]/div[3]/a");
      Thread.sleep(4000); // Wait for page load
      
      // Focus on text Box
      selenium.focus("name=cpar1");
      // enter a value in Text box 1
      selenium.type("css=input[name=\"cpar1\"]", "10");
      
      // enter a value in Text box 2
      selenium.focus("name=cpar2");
      selenium.type("css=input[name=\"cpar2\"]", "50");
      
      // Click Calculate button
      selenium.click("xpath=.//*[@id='content']/table/tbody/tr/td[2]/input");
      
      // verify if the result is 5
      String result = selenium.getText(".//*[@id='content']/p[2]");
      
      if (result == "5"){
         System.out.println("Pass");
      }
      else{
         System.out.println("Fail");
      }
   }
}
Step 11 : Now, let us execute the script by clicking 'Run' Button.
Selenium IDE 72
Step 12 : The script would start executing and user would be able to see the command history under 'Command History' Tab.
Selenium IDE 71
Step 13 : The final state of the application is shown as below. The percentage is calculated and it displayed the result on screen as shown below.
Selenium IDE 73
Step 14 : The output of the test is printed on the Eclipse console as shown below as we have printed the output to the console. In real time the output is written to an HTML file or in a simple Text file.
Selenium IDE 74