Selenium

Articles
Resources
Videos
Old
Mobile
User extensions

http://oss.infoscience.co.jp/seleniumhq/docs/book/Selenium_Documentation.pdf
http://www.seleniumhq.org/docs/02_selenium_ide.jsp

Grid

// Single attribute
//tagname[@attributeName=’value1’]
//a[@href=’http://www.google.com’]
//input[@id=’name’]
//input[@name=’username’]
//img[@alt=’sometext’]

// Multiple attributes
//tagname[@attribute1=’value1’][attribute2=’value2’]
//a[@id=’id1’][@name=’namevalue1’]
//img[@src=’’][@href=’’]

// Using contains
//tagname[contains(@attribute,’value1’)]
//input[contains(@id,’’)]
//input[contains(@name,’’)]
//a[contains(@href,’’)]
//img[contains(@src,’’)]
//div[contains(@id,’’)]

// Using starts-with
//tagname[starts-with(@attribute-name,’’)]
//id[starts-with(@id,’’)]
//a[starts-with(@href=’’)]
//img[starts-with(@src=’’)]
//div[starts-with(@id=’’)]
//input[starts-with(@id=’’)]
//button[starts-with(@id,’’)]

// Using following mode
//input[@id=’’]/following::input[1]
//a[@href=’’]/following::a[1]
//img[@src=’’]/following::img[1]

// Using preceding
//input[@id=’’]/ preceding::input[1]
//a[@href=’’]/ preceding::a[1]
//img[@src=’’]/ preceding::img[1]

// Relative and Absolute XPath
//input[@id=’section’]/div/input

What is Selenium?

Selenium is a tool to test web pages.

What are the components of Selenium?

  1. Selenium Core
  2. Selenium RC (Remote Control)
  3. Selenium IDE

Who are the original authors of Selenium?

  1. Selenium: Jason Huggins
  2. WebDriver: Simon Stewart

What is Selenium 2?

Selenium 2 (WebDriver) is the future direction of the project and the newest addition to the Selenium toolkit. This brand new automation tool provides all sorts of awesome features, including a more cohesive and object oriented API as well as an answer to the limitations of the old implementation.

Selenium 2.0 supports the WebDriver API and underlying technology, along with the Selenium 1 technology underneath the WebDriver API for maximum flexibility in porting your tests. In addition, Selenium 2 still runs Selenium 1’s Selenium RC interface for backwards compatibility.

What is Selenium RC?

Selenium RC was the main Selenium project for a long time, before the WebDriver/Selenium merge brought up Selenium 2, the newest and more powerful tool. Now Selenium 1 is deprecated and is not actively supported (mostly in maintenance mode).

What is the purpose of Selenium IDE?

Selenium IDE (Integrated Development Environment) is a prototyping tool for building test scripts. It is a Firefox plugin and provides an easy-to-use interface for developing automated tests. Selenium IDE has a recording feature, which records user actions as they are performed and then exports them as a reusable script in one of many programming languages that can be later executed.

Even though Selenium IDE has a “Save” feature that allows users to keep the tests in a table-based format for later import and execution, it is not designed to run your test passes nor is it designed to build all the automated tests you will need. Specifically, Selenium IDE doesn’t provide iteration or conditional statements for test scripts. At the time of writing there is no plan to add such thing. The reasons are partly technical and partly based on the Selenium developers encouraging best practices in test automation which always requires some amount of programming. Selenium IDE is simply intended as a rapid prototyping tool. The Selenium developers recommend for serious, robust test automation either Selenium 2 or Selenium 1 to be used with one of the many supported programming languages.

What is the purpose of Selenium Grid?

Selenium-Grid allows the Selenium RC solution to scale for large test suites and for test suites that must be run in multiple environments. Selenium Grid allows you to run your tests in parallel, that is, different tests can be run at the same time on different remote machines. This has two advantages. First, if you have a large test suite, or a slow-running test suite, you can boost its performance substantially by using Selenium Grid to divide your test suite to run different tests at the same time using those different machines. Also, if you must run your test suite on multiple environments you can have different remote machines supporting and running your tests in them at the same time. In each case Selenium Grid greatly improves the time it takes to run your suite by making use of parallel processing.

Should we use Selenium 1 or should we use Selenium 2?

Many people get started with Selenium IDE. If you are not already experienced with a programming or scripting language you can use Selenium IDE to get familiar with Selenium commands. Using the IDE you can create simple tests quickly, sometimes within seconds. We don’t, however, recommend you do all your test automation using Selenium IDE. To effectively use Selenium you will need to build and run your tests using either Selenium 2 or Selenium 1 in conjunction with one of the supported programming languages. Which one you choose depends on you.

At the time of writing the Selenium developers are planning on the Selenium-WebDriver API being the future direction for Selenium. Selenium 1 is provided for backwards compatibility. Still, both have strengths and weaknesses which are discussed in the corresponding chapters of this document. We recommend those who are completely new to Selenium to read through these sections. However, for those who are adopting Selenium for the first time, and therefore building a new test suite from scratch, you will probably want to go with Selenium 2 since this is the portion of Selenium that will continue to be supported in the future.

See http://www.seleniumhq.org/docs/01_introducing_selenium.jsp#supported-browsers-and-platforms

What is the purpose of the UI-Element part of Selenium IDE?

Detailed information on the UI-Element and the Rollup tabs can be found in the UI-Element Documentation on the Help menu of Selenium-IDE.

What are the typical Selenium commands?

  1. open
  2. click
  3. type
  4. verifyTextPresent
  5. verifyElementPresent / waitForElementPresent
  6. goBackAndWait
  7. verifyTitle / assertTitle
  8. verifyText: verifies expected text and its corresponding HTML tag are present on the page.
  9. verifyTable: verifies a table’s expected contents.
  10. waitForPageToLoad

How can we debug a test case using Selenium IDE?

You can set a breakpoint in the test case to cause it to stop on a particular command. This is useful for debugging your test case. To set a breakpoint, select a command, right-click, and from the context menu select Toggle Breakpoint.

How can we tell Selenium IDE to run the test case from a specific command?

You can tell the IDE to begin running from a specific command in the middle of the test case. This also is used for debugging. To set a startpoint, select a command, right-click, and from the context menu select Set/Clear Start Point.

How can we tell Selenium IDE to run only a specific command?

Double-click any single command to run it by itself. This is useful when writing a single command. It lets you immediately test a command you are constructing, when you are not sure if it is correct. You can double-click it to see if it runs correctly. This is also available from the context menu.

What is the purpose of the Base URL field in Selenium IDE?

The Base URL field at the top of the Selenium-IDE window is very useful for allowing test cases to be run across different domains. Suppose that a site named http://news.portal.com had an in-house beta site named http://beta.news.portal.com. Any test cases for these sites that begin with an open statement should specify a relative URL as the argument to open rather than an absolute URL (one starting with a protocol such as http: or https:). Selenium-IDE will then create an absolute URL by appending the open command’s argument onto the end of the value of Base URL.

What are the 3 favors of Selenium commands?

  1. Actions: are commands that generally manipulate the state of the application. They do things like “click this link” and “select that option”. If an Action fails, or has an error, the execution of the current test is stopped. Many Actions can be called with the “AndWait” suffix, e.g. “clickAndWait”. This suffix tells Selenium that the action will cause the browser to make a call to the server, and that Selenium should wait for a new page to load.
  2. Accessors: examine the state of the application and store the results in variables, e.g. “storeTitle”. They are also used to automatically generate Assertions.
  3. Assertions: are like Accessors, but they verify that the state of the application conforms to what is expected. Examples include “make sure the page title is X” and “verify that this checkbox is checked”.

What are the differences between assert, verify, and waitFor ?

All Selenium Assertions can be used in 3 modes: “assert”, “verify”, and ” waitFor”. For example, you can “assertText”, “verifyText” and “waitForText”.

When an “assert” fails, the test is aborted. When a “verify” fails, the test will continue execution, logging the failure. This allows a single “assert” to ensure that the application is on the correct page, followed by a bunch of “verify” assertions to test form field values, labels, etc.

The “waitFor” commands wait for some condition to become true (which can be useful for testing Ajax applications). They will succeed immediately if the condition is already true. However, they will fail and halt the test if the condition does not become true within the current timeout setting (see the setTimeout action below).

Should we choose "assert" or "verify"?

Choosing between “assert” and “verify” comes down to convenience and management of failures. There’s very little point checking that the first paragraph on the page is the correct one if your test has already failed when checking that the browser is displaying the expected page. If you’re not on the correct page, you’ll probably want to abort your test case so that you can investigate the cause and fix the issue(s) promptly. On the other hand, you may want to check many attributes of a page without aborting the test case on the first failure as this will allow you to review all failures on the page and take the appropriate action. Effectively an “assert” will fail the test and abort the current test case, whereas a “verify” will fail the test and continue to run the test case.

How many parameters can a selenium command takes?

Selenium commands can take up to 2 parameters.

What are some sample locators?

  1. //div/p
  2. id=Login
  3. link=Go to Marketing Research
  4. //a[2]
  5. xpath=/html/body/form[1]
  6. //form[1]
  7. xpath=//form[@id='loginForm']
  8. xpath=//form[input/@name='username']: (First form element with an input child element with attribute named ‘name’ and the value ‘username’)
  9. dom=document.getElementById('loginForm')
  10. css=form#loginForm

Does Selenium support the question mark for matching text?

Not definitively. See http://www.seleniumhq.org/docs/02_selenium_ide.jsp#matching-text-patterns

Command Target Value
verifyTitle regexp:.*Film.*Television.* cell-content

What can we do if we need to support flow control with Selenium IDE?

Selenese, by itself, does not support condition statements (if-else, etc.) or iteration (for, while, etc.). Many useful tests can be conducted without flow control. However, for a functional test of dynamic content, possibly involving multiple pages, programming logic is often needed. When flow control is needed, there are three options:

  1. Run the script using Selenium-RC and a client library such as Java or PHP to utilize the programming language’s flow control features.
  2. Run a small JavaScript snippet from within the script using the storeEval command.
  3. Install the goto_sel_ide.js extension.

How can we use the store commands with Selenium variables?

You can use Selenium variables to store constants at the beginning of a script. Also, when combined with a data-driven test design (discussed in a later section), Selenium variables can be used to store values passed to your test program from the command-line, from another program, or from a file.

The plain store command is the most basic of the many store commands and can be used to simply store a constant value in a selenium variable. It takes two parameters, the text value to be stored and a selenium variable. Use the standard variable naming conventions of only alphanumeric characters when choosing a name for your variable.

Command Target Value
store gro.etisym|luap#gro.etisym|luap userName

Later in your script, you’ll want to use the stored value of your variable. To access the value of a variable, enclose the variable in curly brackets ({}) and precede it with a dollar sign like this.

Command Target Value
verifyText //div/p ${userName}

Where can we use Selenium variables?

Selenium variables can be used in either the first or second parameter and are interpreted by Selenium prior to any other operations performed by the command. A Selenium variable may also be used within a locator expression.

What are available "store" commands?

An equivalent store command exists for each verify and assert command. Here are a couple more commonly used store commands.

  1. storeElementPresent: This corresponds to verifyElementPresent. It simply stores a boolean value–”true” or “false”–depending on whether the UI element is found.
  2. storeText: StoreText corresponds to verifyText. It uses a locater to identify specific page text. The text, if found, is stored in the variable. StoreText can be used to extract text from the page being tested.
  3. storeEval: This command takes a script as its first parameter. Embedding JavaScript within Selenese is covered in the next section. StoreEval allows the test to store the result of running the script in a variable.

How can we use JavaScript as Selenese parameters?

JavaScript can be used with two types of Selenese parameters: script and non-script (usually expressions). In most cases, you’ll want to access and/or manipulate a test case variable inside the JavaScript snippet used as a Selenese parameter. All variables created in your test case are stored in a JavaScript associative array. An associative array has string indexes rather than sequential numeric indexes. The associative array containing your test case’s variables is named storedVars. Whenever you wish to access or manipulate a variable within a JavaScript snippet, you must refer to it as storedVars[‘yourVariableName’].

Several Selenese commands specify a script parameter including assertEval, verifyEval, storeEval, and waitForEval. These parameters require no special syntax. A Selenium-IDE user would simply place a snippet of JavaScript code into the appropriate field, normally the Target field (because a script parameter is normally the first or only parameter).

The example below illustrates how a JavaScript snippet can be used to perform a simple numerical calculation:

Command Target Value
store 10 hits
storeXpathCount //blockquote blockquotes
storeEval storedVars[‘hits’]-storedVars[‘blockquotes’] paragraphs

JavaScript can also be used to help generate values for parameters, even when the parameter is not specified to be of type script. However, in this case, special syntax is required–the entire parameter value must be prefixed by javascript{ with a trailing }, which encloses the JavaScript snippet, as in javascript{*yourCodeHere*}. Below is an example in which the type command’s second parameter value is generated via JavaScript code using this special syntax:

Command Target Value
type q javascript{storedVars[‘searchString’].toUpperCase()}

How can we print some text to our log using Selenese?

Use the echo command. Selenese has a simple command that allows you to print text to your test’s output. This is useful for providing informational progress notes in your test which display on the console as your test is running. These notes also can be used to provide context within your test result reports, which can be useful for finding where a defect exists on a page in the event your test finds a problem. Finally, echo statements can be used to print the contents of Selenium variables.

How does Selenium handle alerts, confirms and prompts?

When running under Selenium, JavaScript pop-ups will not appear. This is because the function calls are actually being overridden at runtime by Selenium’s own JavaScript. However, just because you cannot see the pop-up doesn’t mean you don’t have to deal with it. To handle a pop-up, you must call its assertFoo(pattern) function. If you fail to assert the presence of a pop-up your next command will be blocked and you will get an error similar to the following [error] Error: There was an unexpected Confirmation! [Chose an option.]

Command Target Value
assertAlert I’m blocking!
chooseCancelOnNextConfirmation
assertConfirmation Choose an option.
answerOnNextPrompt Selenium!
assertPrompt What’s the best web QA tool?

See http://www.seleniumhq.org/docs/02_selenium_ide.jsp#alerts-popups-and-multiple-windows

What are user extensions?

User extensions are JavaScript files that allow one to create his or her own customizations and features to add additional functionality. Often this is in the form of customized commands although this extensibility is not limited to additional commands. There are a number of useful extensions created by users.

Perhaps the most popular of all Selenium-IDE extensions is one which provides flow control in the form of while loops and primitive conditionals. This extension is the goto_sel_ide.js. For an example of how to use the functionality provided by this extension, look at the page created by its author.

To install this extension, put the pathname to its location on your computer in the Selenium Core extensions field of Selenium-IDE’s Options=>Options=>General tab.

chapt3_img32_Extensions_install.png

After selecting the OK button, you must close and reopen Selenium-IDE in order for the extensions file to be read. Any change you make to an extension will also require you to close and reopen Selenium-IDE.

Information on writing your own extensions can be found near the bottom of the [Information on writing your own extensions can be found near the bottom of the Selenium Reference document. Selenium Reference] document.

Sometimes it can prove very useful to debug step by step Selenium IDE and your User Extension. The only debugger that appears able to debug XUL/Chrome based extensions is Venkman which is supported in Firefox until version 32 included. The step by step debug has been verified to work with Firefox 32 and Selenium IDE 2.9.0.

How can we export our tests to different formats?

See http://www.seleniumhq.org/docs/02_selenium_ide.jsp#format

Can we run tests written using Selenium IDE with Selenium RC?

Yes. While Selenium-IDE can only run tests against Firefox, tests developed with Selenium-IDE can be run against other browsers, using a simple command-line interface that invokes the Selenium-RC server. This topic is covered in the Run Selenese tests section on Selenium-RC chapter. The -htmlSuite command-line option is the particular feature of interest.

How can we create a plain Java project for selenium purpose?

  1. Create a plain Java project
  2. Download the selenium JAR file
  3. Add the selenium JAR file to the project class path.
  4. Right click on the project
  5. Create a testng.xml file
  6. Right click on the testng.xml file and select "Run As -> TestNG Suite"
  7. java org.testng.TestNG testng.xml
  8. java -cp bin;lib/* org.testng.TestNG testng.xml
WebDriver driver = new WebDriver()
driver.get("http://www.facebook.com");
System.out.println(driver.getTitle());
driver.quit();

How can we configure Jenkins to run Selenium?

  1. Click on Manage Jenkins
  2. Click on Configure System
  3. Click on JDK Installation
  4. Provide the correct path for your JDK installation
  5. Uncheck the "Install automatically" checkbox
  6. Click the apply button and the save button
  7. Write your test cases
  8. Create a test suite
  9. Create a .bat file to run your test suite
  10. Create a Jenkins job to run your batch file

How can we find an XPath for an element?

  1. Launch Firebug
  2. Click on the FireXPath tab
  3. Inspect an element
  4. Switch back to FireBug
  5. The FireXPath tab display the XPath for the selected element
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License