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

Sunday, 29 March 2015

How To Set-Up Selenium Environment.



Selenium - Environment Setup


In order to develop Selenium RC or WebDriver scripts, users have to ensure that they have the initial configuration done. Setting up the environment involves the following steps.
  • Download and Install Java
  • Download and Configure Eclipse
  • Configure FireBug and FirePath
  • Configure Selenium RC
  • Configure Selenium WebDriver

Download and Install Java

We need to have JDK (Java Development Kit) installed in order to work with Selenium WebDriver/Selenium. Let us see how to download and install Java.
Step 1 : Navigate to the URL:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Step 2 : Go to "Downloads" section and select "JDK Download".
Selenium IDE 30
Step 3 : Select "Accept License Agreement" radio button.
Selenium IDE 31
Step 4 : Select the appropriate installation. In this case, it is 'Windows 7-64' bit. Click the appropriate link and save the .exe file to your disk.
Selenium IDE 32
Step 5 : Run the downloaded exe file to launch the Installer wizard. Click 'Next' to continue.
Selenium IDE 33
Step 6 : Select the features and click 'Next'.
Selenium IDE 34
Step 7 : The installer is extracted and its progress is shown in the wizard.
Selenium IDE 35
Step 8 : The user can choose the install location and click 'Next'.
Selenium IDE 36
Step 9 : The installer installs the JDK and new files are copied across.
Selenium IDE 37
Step 10 : The Installer installs successfully and displays the same to the user.
Selenium IDE 38
Step 11 : To verify if the installation was successful, go to the command prompt and just type 'java' as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an "unknown command" error.
Selenium IDE 48

Download and Configure Eclipse

Step 1 : Navigate to the URL: http://www.eclipse.org/downloads/ and download the appropriate file based on your OS architecture.
Selenium IDE 39
Step 2 : Click the 'Download' button.
Selenium IDE 40
Step 3 : The download would be in a Zipped format. Unzip the contents.
Selenium IDE 41
Step 4 : Locate Eclipse.exe and double click on the file.
Selenium IDE 42
Step 5 : To configure the workspace, select the location where the development has to take place.
Selenium IDE 43
Step 6 : The Eclipse window opens as shown below.
Selenium IDE 44

Configure FireBug and FirePath

To work with Selenium RC or WebDriver, we need to locate elements based on their XPath or ID or name, etc. In order to locate an element, we need tools/plugins.
Step 1 : Navigate to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/ and download plugin.
Selenium IDE 62
Step 2 : The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.
Selenium IDE 63
Step 3 : After installing, we can launch the plugin by navigating to "Web Developer" >> "Firebug".
Selenium IDE 64
Step 4 : FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of an element. Install FirePath by navigating to "https://addons.mozilla.org/en-US/firefox/addon/firepath/"
Selenium IDE 65
Step 5 : The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.
Selenium IDE 66
Step 6 : Now launch "Firebug" by navigating to "Tools" >> "Webdeveloper" >> "Firebug".
Selenium IDE 67

Example

Now let us understand how to use FireBug and FirePath with an example. For demonstration, we will use www.google.com and capture the properties of the text box of "google.com".
Step 1 : First click on the arrow icon as highlighted in the following screenshot and drag it to the object for which we would like to capture the properties. The HTML/DOM of the object would be displayed as shown below. We are able to capture the 'ID' of the input text box with which we can interact.
Selenium IDE 68
Step 2 : To fetch the XPath of the object, go to 'firepath' tab and perform the following steps.
  • Click the Spy icon.
  • Select the Control for which we would like to capture the XPath
  • XPath of the selected control would be generated.
Selenium IDE 69

Configure Selenium RC

Now let us look at how to configure Selenium Remote control. We will understand how to develop scripts with Selenium RC in later chapters, however for now, we will understand just the configuration part of it.
Step 1 : Navigate to the Selenium downloads section http://www.seleniumhq.org/download/ and download Selenium Server by clicking on its version number as shown below.
Selenium IDE 45
Step 2 : After downloading, we need to start the Selenium Server. To do so, open command prompt and navigate to the folder where the downloaded JAR file is kept as shown below.
Selenium IDE 46
Step 3 : To start the server, use the command 'java -jar <<downloaded jar name >> and if java JDK is installed properly, you would get a success message as shown below. Now we can start writing Selenium RC scripts.
Selenium IDE 47

Configure Selenium WebDriver

Now let us look at how to configure Selenium WebDriver. We will understand how to develop scripts with Selenium WebDriver in later chapters, however for now, we will understand just the configuration part of it.
Step 1 : Navigate to the selenium downloads section http://www.seleniumhq.org/download/ and download Selenium WebDriver by clicking on its version number as shown below.
Selenium IDE 49
Step 2 : The downloaded file is in Zipped format and one has to unzip the contents to map it to the project folder.
Selenium IDE 49
Step 3 : The Unzipped contents would be displayed as shown below. How to map it to the project folder and how to start scripting would be dealt in the webDriver chapter.
Selenium IDE 51