Selenium Documentation
Selenium Documentation
Selenium Documentation
Release 1.0
Selenium Project
CONTENTS
1 2
Note to the ReaderDocs Being Revised for Selenium 2.0! Introduction 2.1 Test Automation for Web Applications . . . . . . . 2.2 To Automate or Not to Automate? . . . . . . . . . . 2.3 Introducing Selenium . . . . . . . . . . . . . . . . 2.4 Brief History of The Selenium Project . . . . . . . . 2.5 Seleniums Tool Suite . . . . . . . . . . . . . . . . 2.6 Choosing Your Selenium Tool . . . . . . . . . . . . 2.7 Supported Browsers and Platforms . . . . . . . . . 2.8 Flexibility and Extensibility . . . . . . . . . . . . . 2.9 Whats in this Book? . . . . . . . . . . . . . . . . . 2.10 The Documentation TeamAuthors Past and Present
3 5 5 5 6 6 7 8 8 9 9 10 13 13 13 16 17 20 22 22 23 24 25 25 26 26 28 33 35 35 35 36 37 38 38 40 i
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
Selenium-IDE 3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Installing the IDE . . . . . . . . . . . . . . . . . . . . . 3.3 Opening the IDE . . . . . . . . . . . . . . . . . . . . . . 3.4 IDE Features . . . . . . . . . . . . . . . . . . . . . . . . 3.5 Building Test Cases . . . . . . . . . . . . . . . . . . . . 3.6 Running Test Cases . . . . . . . . . . . . . . . . . . . . 3.7 Using Base URL to Run Test Cases in Different Domains 3.8 Selenium Commands Selenese . . . . . . . . . . . . 3.9 Script Syntax . . . . . . . . . . . . . . . . . . . . . . . . 3.10 Test Suites . . . . . . . . . . . . . . . . . . . . . . . . . 3.11 Commonly Used Selenium Commands . . . . . . . . . . 3.12 Verifying Page Elements . . . . . . . . . . . . . . . . . . 3.13 Assertion or Verication? . . . . . . . . . . . . . . . . . 3.14 Locating Elements . . . . . . . . . . . . . . . . . . . . . 3.15 Matching Text Patterns . . . . . . . . . . . . . . . . . . . 3.16 The AndWait Commands . . . . . . . . . . . . . . . . 3.17 The waitFor Commands in AJAX applications . . . . . . 3.18 Sequence of Evaluation and Flow Control . . . . . . . . . 3.19 Store Commands and Selenium Variables . . . . . . . . . 3.20 JavaScript and Selenese Parameters . . . . . . . . . . . . 3.21 echo - The Selenese Print Command . . . . . . . . . . . . 3.22 Alerts, Popups, and Multiple Windows . . . . . . . . . . 3.23 Debugging . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
Writing a Test Suite . . . . . . . . . . . . . . . . . . User Extensions . . . . . . . . . . . . . . . . . . . . Format . . . . . . . . . . . . . . . . . . . . . . . . . Executing Selenium-IDE Tests on Different Browsers Troubleshooting . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
Selenium 2.0 and WebDriver 4.1 Selenium 2.0 Features . . . . . . . . . . . 4.2 The Selenium Server When to Use It . . 4.3 Setting Up a Selenium-WebDriver Project . 4.4 Migrating from Selenium 1.0 . . . . . . . 4.5 Getting Started With Selenium-WebDriver 4.6 Introducing WebDrivers Drivers . . . . . 4.7 Commands and Operation . . . . . . . . . 4.8 Driver Specics and Tradeoffs . . . . . . . 4.9 WebDriver-Backed Selenium-RC . . . . . 4.10 Selenium WebDriver Wiki . . . . . . . . . 4.11 Next Steps . . . . . . . . . . . . . . . . . WebDriver: Advanced Usage 5.1 Explicit and Implicit Waits . . 5.2 RemoteWebDriver . . . . . . 5.3 AdvancedUserInteractions . . 5.4 Browser Startup Manipulation 5.5 HTML5 . . . . . . . . . . . . 5.6 Parallelizing Your Test Runs .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
Selenium 1 (Selenium RC) 6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 How Selenium RC Works . . . . . . . . . . . . . . . . . . . 6.3 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4 From Selenese to a Program . . . . . . . . . . . . . . . . . . 6.5 Programming Your Test . . . . . . . . . . . . . . . . . . . . 6.6 Learning the API . . . . . . . . . . . . . . . . . . . . . . . . 6.7 Reporting Results . . . . . . . . . . . . . . . . . . . . . . . 6.8 Adding Some Spice to Your Tests . . . . . . . . . . . . . . . 6.9 Server Options . . . . . . . . . . . . . . . . . . . . . . . . . 6.10 Specifying the Path to a Specic Browser . . . . . . . . . . . 6.11 Selenium RC Architecture . . . . . . . . . . . . . . . . . . . 6.12 Handling HTTPS and Security Popups . . . . . . . . . . . . 6.13 Supporting Additional Browsers and Browser Congurations 6.14 Troubleshooting Common Problems . . . . . . . . . . . . . . Test Design Considerations 7.1 Introducing Test Design . . 7.2 Types of Tests . . . . . . . 7.3 Validating Results . . . . . 7.4 Location Strategies . . . . . 7.5 Wrapping Selenium Calls . 7.6 UI Mapping . . . . . . . . 7.7 Page Object Design Pattern 7.8 Data Driven Testing . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
ii
7.9 8 9
Database Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 119 121 121 121 121 122 123 123 127 129 133
Selenium-Grid User-Extensions 9.1 Introduction . . . . . . . . . . . . . . . . 9.2 Actions . . . . . . . . . . . . . . . . . . . 9.3 Accessors/Assertions . . . . . . . . . . . . 9.4 Locator Strategies . . . . . . . . . . . . . 9.5 Using User-Extensions With Selenium-IDE 9.6 Using User-Extensions With Selenium RC
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
10 How to Install the Android Driver 11 .NET client driver conguration 12 Importing Sel2.0 Project into IntelliJ Using Maven
13 Selenium 1.0 Java Client Driver Conguration 147 13.1 Conguring Selenium-RC With Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . 147 13.2 Conguring Selenium-RC With Intellij . . . . . . . . . . . . . . . . . . . . . . . . . . 163 14 Python Client Driver Conguration 165
15 Locating Techniques 169 15.1 Useful XPATH patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 15.2 Starting to use CSS instead of XPATH . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 16 Migrating From Selenium RC to Selenium WebDriver 16.1 How to Migrate to Selenium WebDriver . . . . . . 16.2 Why Migrate to WebDriver . . . . . . . . . . . . 16.3 Before Starting . . . . . . . . . . . . . . . . . . . 16.4 Getting Started . . . . . . . . . . . . . . . . . . . 16.5 Next Steps . . . . . . . . . . . . . . . . . . . . . 16.6 Common Problems . . . . . . . . . . . . . . . . . 171 171 171 172 172 172 172
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
iii
iv
Contents:
CONTENTS
CONTENTS
CHAPTER
ONE
CHAPTER
TWO
INTRODUCTION
2.1 Test Automation for Web Applications
Many, perhaps most, software applications today are written as web-based applications to be run in an Internet browser. The effectiveness of testing these applications varies widely among companies and organizations. In an era of highly interactive and responsive software processes where many organizations are using some form of Agile methodology, test automation is frequently becoming a requirement for software projects. Test automation is often the answer. Test automation means using a software tool to run repeatable tests against the application to be tested. For regression testing this provides that responsiveness. There are many advantages to test automation. Most are related to the repeatability of the tests and the speed at which the tests can be executed. There are a number of commercial and open source tools available for assisting with the development of test automation. Selenium is possibly the most widelyused open source solution. This users guide will assist both new and experienced Selenium users in learning effective techniques in building test automation for web applications. This users guide introduces Selenium, teaches its features, and presents commonly used best practices accumulated from the Selenium community. Many examples are provided. Also, technical information on the internal structure of Selenium and recommended uses of Selenium are provided. Test automation has specic advantages for improving the long-term efciency of a software teams testing processes. Test automation supports: Frequent regression testing Rapid feedback to developers Virtually unlimited iterations of test case execution Support for Agile and extreme development methodologies Disciplined documentation of test cases Customized defect reporting Finding defects missed by manual testing
It is not always advantageous to automate test cases. There are times when manual testing may be more appropriate. For instance, if the applications user interface will change considerably in the near future, then any automation might need to be rewritten anyway. Also, sometimes there simply is not enough time to build test automation. For the short term, manual testing may be more effective. If an application has a very tight deadline, there is currently no test automation available, and its imperative that the testing get done within that time frame, then manual testing is the best solution.
API), partly because selenium addresses some shortcomings in webdriver (such as supporting a broader range of browsers) and partly because the main selenium contributors and I felt that it was the best way to offer users the best possible framework.
2.5.4 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.
2.7.1 Selenium-WebDriver
Selenium-WebDriver supports the following browsers along with the operating systems these browsers are compatable with. Google Chrome 12.0.712.0+ Internet Explorer 6, 7, 8, 9 - 32 and 64-bit where applicable Firefox 3.0, 3.5, 3.6, 4.0, 5.0 Opera 11.5+ HtmlUnit 2.8 Android 2.3+ on devices
Chapter 2. Introduction
* Tests developed on Firefox via Selenium IDE can be executed on any other supported browser via a simple Selenium RC command line. ** Selenium RC server can start any executable, but depending on browser security settings there may be technical limitations that would limit certain features.
tests. This section also demonstrates how your test script can be exported to a programming language for adding more advanced capabilities not supported by Selenium IDE. Selenium 2 Explains how to develop an automated test program using Selenium 2. Selenium 1 Explains how to develop an automated test program using the Selenium RC API. Many examples are presented in both programming languages and scripting languages. Also, the installation and setup of Selenium RC is covered here. The various modes, or congurations, that Selenium RC supports are described, along with their trade-offs and limitations. An architecture diagram is provided to help illustrate these points. Solutions to common problems frequently difcult for new Sel-R users are described here, for instance, handling Security Certicates, https requests, pop-ups, and the opening of new windows. Test Design Considerations This chapter presents programming techniques for use with SeleniumWebDriver and Selenium RC. We also demonstrate techniques commonly asked about in the user forum such as how to design setup and teardown functions, how to implement data-driven tests (tests where one can varies the data between test passes) and other methods of programming common test automation tasks. Selenium-Grid This chapter is not yet developed. User extensions Describes ways that Selenium can be modied, extended and customized.
2.10.1 Acknowledgements
A special thanks goes to Patrick Lightbody. As an administrator of the SeleniumHQ website, major contributor to Selenium RC, his support was invaluable when writing the rst release of the users guide. Patrick helped us understand our audience. He also set us up with everything we needed on the seleniumhq.org website for publishing the documents. Also a thanks goes to Andras Hatvani for his advice on publishing solutions, and to Amit Kumar for participating in our discussions and for assisting with reviewing the document. 10 Chapter 2. Introduction
And of course, we must recognize the Selenium Developers. They have truly designed an amazing tool. Without the vision of the original designers, and the continued efforts of the current developers, we would not have such a great tool to pass on to you.
11
12
Chapter 2. Introduction
CHAPTER
THREE
SELENIUM-IDE
3.1 Introduction
The Selenium-IDE (Integrated Development Environment) is the tool you use to develop your Selenium test cases. Its an easy-to-use Firefox plug-in and is generally the most efcient way to develop test cases. It also contains a context menu that allows you to rst select a UI element from the browsers currently displayed page and then select from a list of Selenium commands with parameters pre-dened according to the context of the selected UI element. This is not only a time-saver, but also an excellent way of learning Selenium script syntax. This chapter is all about the Selenium IDE and how to use it effectively.
13
When downloading from Firefox, youll be presented with the following window.
Select Install Now. The Firefox Add-ons window pops up, rst showing a progress bar, and when the
14
Chapter 3. Selenium-IDE
Restart Firefox. After Firefox reboots you will nd the Selenium-IDE listed under the Firefox Tools menu.
15
16
Chapter 3. Selenium-IDE
3.4.2 Toolbar
The toolbar contains buttons for controlling the execution of your test cases, including a step feature for debugging your test cases. The right-most button, the one with the red-dot, is the record button.
17
Speed Control: controls how fast your test case runs. Run All: Runs the entire test suite when a test suite with multiple test cases is loaded. Run: Runs the currently selected test. When only a single test is loaded this button and the Run All button have the same effect. Pause/Resume: Allows stopping and re-starting of a running test case. Step: Allows you to step through a test case by running it one command at a time. Use for debugging test cases. TestRunner Mode: Allows you to run the test case in a browser loaded with the Selenium-Core TestRunner. The TestRunner is not commonly used now and is likely to be deprecated. This button is for evaluating test cases for backwards compatibility with the TestRunner. Most users will probably not need this button. Apply Rollup Rules: This advanced feature allows repetitive sequences of Selenium commands to be grouped into a single action. Detailed documentation on rollup rules can be found in the UI-Element Documentation on the Help menu. Record: Records the users browser actions.
The other tab - Source displays the test case in the native format in which the le will be stored. By default, this is HTML although it can be changed to a programming language such as Java or C#, or a scripting language like Python. See the Options menu for details. The Source view also allows one to edit the test case in its raw form, including copy, cut and paste operations. The Command, Target, and Value entry elds display the currently selected command along with its parameters. These are entry elds where you can modify the currently selected command. The rst
18
Chapter 3. Selenium-IDE
parameter specied for a command in the Reference tab of the bottom pane always goes in the Target eld. If a second parameter is specied by the Reference tab, it always goes in the Value eld.
If you start typing in the Command eld, a drop-down list will be populated based on the rst characters you type; you can then select your desired command from the drop-down.
Reference The Reference tab is the default selection whenever you are entering or modifying Selenese commands and parameters in Table mode. In Table mode, the Reference pane will display documentation on the current command. When entering or modifying commands, whether from Table or Source mode, it is critically important to ensure that the parameters specied in the Target and Value elds match those specied in the parameter list in the Reference pane. The number of parameters provided must match the number specied, the order of parameters provided must match the order specied, and the type of parameters provided must match the type specied. If there is a mismatch in any of these three areas, the command will not run correctly.
While the Reference tab is invaluable as a quick reference, it is still often necessary to consult the Selenium Reference document.
19
UI-Element and Rollup Detailed information on these two panes (which cover advanced features) can be found in the UIElement Documentation on the Help menu of Selenium-IDE.
3.5.1 Recording
Many rst-time users begin by recording a test case from their interactions with a website. When Selenium-IDE is rst opened, the record button is ON by default. If you do not want Selenium-IDE to begin recording automatically you can turn this off by going under Options > Options... and deselecting Start recording immediately on open. During recording, Selenium-IDE will automatically insert commands into your test case based on your actions. Typically, this will include: clicking a link - click or clickAndWait commands entering values - type command selecting options from a drop-down listbox - select command clicking checkboxes or radio buttons - click command Here are some gotchas to be aware of: The type command may require clicking on some other area of the web page for it to record. Following a link usually records a click command. You will often need to change this to clickAndWait to ensure your test case pauses until the new page is completely loaded. Otherwise, your test case will continue running commands before the page has loaded all its UI elements. This will cause unexpected test case failures.
Also, notice the Show All Available Commands menu option. This shows many, many more commands, again, along with suggested parameters, for testing your currently selected UI element. Try a few more UI elements. Try right-clicking an image, or a user control like a button or a checkbox. You may need to use Show All Available Commands to see options other than verifyTextPresent. Once you select these other options, the more commonly used ones will show up on the primary context menu. For example, selecting verifyElementPresent for an image should later cause that command to be available on the primary context menu the next time you select an image and right-click. Again, these commands will be explained in detail in the chapter on Selenium commands. For now though, feel free to use the IDE to record and select commands into a test case and then run it. You can learn a lot about the Selenium commands simply by experimenting with the IDE.
3.5.3 Editing
Insert Command
Table View
Select the point in your test case where you want to insert the command. To do this, in the Test Case Pane, left-click on the line where you want to insert a new command. Right-click and select Insert Command; the IDE will add a blank line just ahead of the line you selected. Now use the command editing text elds to enter your new command and its parameters.
Source View
Select the point in your test case where you want to insert the command. To do this, in the Test Case Pane, left-click between the commands where you want to insert a new command, and enter the HTML tags needed to create a 3-column row containing the Command, rst parameter (if one is required by the Command), and second parameter (again, if one is required). Be sure to save your test before switching back to Table view. Insert Comment Comments may be added to make your test case more readable. These comments are ignored when the test case is run. Comments may also be used to add vertical white space (one or more blank lines) in your tests; just create empty comments. An empty command will cause an error during execution; an empty comment wont.
Table View
Select the line in your test case where you want to insert the comment. Right-click and select Insert Comment. Now use the Command eld to enter the comment. Your comment will appear in purple font.
Source View
Select the point in your test case where you want to insert the comment. Add an HTML-style comment, i.e., <!-- your comment here -->. 3.5. Building Test Cases 21
Table View
Simply select the line to be changed and edit it using the Command, Target, and Value elds.
Source View
Since Source view provides the equivalent of a WYSIWYG editor, simply modify which line you wish command, parameter, or comment.
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 commands argument onto the end of the value of Base URL. For example, the test case below would be run against http://news.portal.com/about.html:
Base
URL
setting
would
be
run
against
Many Actions can be called with the AndWait sufx, e.g. clickAndWait. This sufx 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. Accessors examine the state of the application and store the results in variables, e.g. storeTitle. They are also used to automatically generate Assertions. 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. 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 eld values, labels, etc. 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).
The parameters are not always required; it depends on the command. In some cases both are required, in others one parameter is required, and in still others the command may take no parameters at all. Here are a couple more examples: goBackAndWait verifyTextPresent type type Welcome to My Home Page (555) 666-7066 ${myVariableAddress}
id=phone id=address1
The command reference describes the parameter requirements for each command. Parameters vary, however they are typically: a locator for identifying a UI element within a page. a text pattern for verifying or asserting expected page content a text pattern or a selenium variable for entering text in an input eld or for selecting an option from an option list. Locators, text patterns, selenium variables, and the commands themselves are described in considerable detail in the section on Selenium Commands. Selenium scripts that will be run from Selenium-IDE will be be stored in an HTML text le format. This consists of an HTML table with three columns. The rst column identies the Selenium command, the second is a target, and the nal column contains a value. The second and third columns may not require values depending on the chosen Selenium command, but they should be present. Each table row represents a new Selenium command. Here is an example of a test that opens a page, asserts the page title and then veries some content on the page: 24 Chapter 3. Selenium-IDE
Rendered as a table in a browser this would look like the following: open assertTitle verifyText /download/ //h2 Downloads Downloads
The Selenese HTML syntax can be used to write and run tests without requiring knowledge of a programming language. With a basic knowledge of selenese and Selenium-IDE you can quickly produce and run testcases.
A le similar to this would allow running the tests all at once, one after another, from the Selenium-IDE. Test suites can also be maintained when using Selenium-RC. This is done via programming and can be done a number of ways. Commonly Junit is used to maintain a test suite if one is using Selenium-RC with Java. Additionally, if C# is the chosen language, Nunit could be employed. If using an interpreted language like Python with Selenium-RC than some simple programming would be involved in setting up a test suite. Since the whole reason for using Sel-RC is to make use of programming logic for your testing this usually isnt a problem.
open opens a page using a URL. click/clickAndWait performs a click operation, and optionally waits for a new page to load. verifyTitle/assertTitle veries an expected page title. verifyTextPresent veries expected text is somewhere on the page. verifyElementPresent veries an expected UI element, as dened by its HTML tag, is present on the page. verifyText veries expected text and its corresponding HTML tag are present on the page. verifyTable veries a tables 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 dened by its HTML tag, is present on the page.
26
Chapter 3. Selenium-IDE
Value
The above example rst opens a page and then asserts that the correct page is loaded by comparing the title with the expected value. Only if this passes will the following command run and verify that the text is present in the expected location. The test case then asserts the rst column in the second row of the rst table contains the expected value, and only if this passed will the remaining cells in that row be veried.
3.13.1 verifyTextPresent
The command verifyTextPresent is used to verify specic text exists somewhere on the page. It takes a single argumentthe text pattern to be veried. For example: Command verifyTextPresent Target Marketing Analysis Value
This would cause Selenium to search for, and verify, that the text string Marketing Analysis appears somewhere on the page currently being tested. Use verifyTextPresent when you are interested in only the text itself being present on the page. Do not use this when you also need to test where the text occurs on the page.
3.13.2 verifyElementPresent
Use this command when you must test for the presence of a specic UI element, rather then its content. This verication does not check the text, only the HTML tag. One common use is to check for the presence of an image. Command verifyElementPresent Target //div/p/img Value
This command veries that an image, specied by the existence of an <img> HTML tag, is present on the page, and that it follows a <div> tag and a <p> tag. The rst (and only) parameter is a locator for telling the Selenese command how to nd the element. Locators are explained in the next section. verifyElementPresent can be used to check the existence of any HTML tag within the page. You can check the existence of links, paragraphs, divisions <div>, etc. Here are a few more examples. Command verifyElementPresent verifyElementPresent verifyElementPresent verifyElementPresent verifyElementPresent verifyElementPresent Target //div/p //div/a id=Login link=Go to Marketing Research //a[2] //head/title Value
These examples illustrate the variety of ways a UI element may be tested. Again, locators are explained in the next section.
27
3.13.3 verifyText
Use verifyText when both the text and its UI element must be tested. verifyText must use a locator. If you choose an XPath or DOM locator, you can verify that specic text appears at a specic location on the page relative to other UI components on the page. Command verifyText Target //table/tr/td/div/p Value This is my text and it occurs right after the div inside the table.
<html> <body> <form id= "loginForm" > <input name= "username" type= "text" /> <input name= "password" type= "password" /> <input name= "continue" type= "submit" value= "Login" /> </form> </body> <html>
The following locator strategies would return the elements from the HTML snippet above indicated by line number: identifier=loginForm (3) identifier=password (5) identifier=continue (6) continue (6) Since the identifier type of locator is the default, the identifier= in the rst three examples above is not necessary. Locating by Id This type of locator is more limited than the identier locator type, but also more explicit. Use this when you know an elements id attribute. 28 Chapter 3. Selenium-IDE
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id= "loginForm" > <input name= "username" <input name= "password" <input name= "continue" <input name= "continue" </form> </body> <html>
"text" /> "password" /> "submit" value= "Login" /> "button" value= "Clear" />
id=loginForm (3) Locating by Name The name locator type will locate the rst element with a matching name attribute. If multiple elements have the same value for a name attribute, then you can use lters to further rene your location strategy. The default lter type is value (matching the value attribute).
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id= "loginForm" > <input name= "username" <input name= "password" <input name= "continue" <input name= "continue" </form> </body> <html>
"text" /> "password" /> "submit" value= "Login" /> "button" value= "Clear" />
name=username (4) name=continue value=Clear (7) name=continue Clear (7) name=continue type=button (7) Note: Unlike some types of XPath and DOM locators, the three types of locators above allow Selenium to test a UI element independent of its location on the page. So if the page structure and organization is altered, the test will still pass. You may or may not want to also test whether the page structure changes. In the case where web designers frequently alter the page, but its functionality must be regression tested, testing via id and name attributes, or really via any HTML property, becomes very important. Locating by XPath XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id
29
or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page. One of the main reasons for using XPath is when you dont have a suitable id or name attribute for the element you wish to locate. You can use XPath to either locate the element in absolute terms (not advised), or relative to an element that does have an id or name attribute. XPath locators can also be used to specify elements via attributes other than id and name. Absolute XPaths contain the location of all elements from the root (html) and as a result are likely to fail with only the slightest adjustment to the application. By nding a nearby element with an id or name attribute (ideally a parent element) you can locate your target element based on the relationship. This is much less likely to change and can make your tests more robust. Since only xpath locators start with //, it is not necessary to include the xpath= label when specifying an XPath locator.
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id= "loginForm" > <input name= "username" <input name= "password" <input name= "continue" <input name= "continue" </form> </body> <html>
"text" /> "password" /> "submit" value= "Login" /> "button" value= "Clear" />
xpath=/html/body/form[1] (3) - Absolute path (would break if the HTML was changed only slightly) //form[1] (3) - First form element in the HTML xpath=//form[@id=loginForm] (3) - The form element with attribute named id and the value loginForm xpath=//form[input/\@name=username] (4) - First form element with an input child element with attribute named name and the value username //input[@name=username] (4) - First input element with attribute named name and the value username //form[@id=loginForm]/input[1] (4) - First input child element of the form element with attribute named id and the value loginForm //input[@name=continue][@type=button] (7) - Input with attribute named name and the value continue and attribute named type and the value button //form[@id=loginForm]/input[4] (7) - Fourth input child element of the form element with attribute named id and value loginForm These examples cover some basics, but in order to learn more, the following references are recommended: W3Schools XPath Tutorial W3C XPath Recommendation 30 Chapter 3. Selenium-IDE
There are also a couple of very useful Firefox Add-ons that can assist in discovering the XPath of an element: XPath Checker - suggests XPath and can be used to test XPath results. Firebug - XPath suggestions are just one of the many powerful features of this very useful add-on. Locating Hyperlinks by Link Text This is a simple method of locating a hyperlink in your web page by using the text of the link. If two links with the same text are present, then the rst match will be used.
1 2 3 4 5 6 7
<html> <body> <p>Are you sure you want to do this?</p> <a href= "continue.html" >Continue</a> <a href= "cancel.html" >Cancel</a> </body> <html>
link=Continue (4) link=Cancel (5) Locating by DOM The Document Object Model represents an HTML document and can be accessed using JavaScript. This location strategy takes JavaScript that evaluates to an element on the page, which can be simply the elements location using the hierarchical dotted notation. Since only dom locators start with document, it is not necessary to include the dom= label when specifying a DOM locator.
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id= "loginForm" > <input name= "username" <input name= "password" <input name= "continue" <input name= "continue" </form> </body> <html>
"text" /> "password" /> "submit" value= "Login" /> "button" value= "Clear" />
dom=document.getElementById(loginForm) (3) dom=document.forms[loginForm] (3) dom=document.forms[0] (3) document.forms[0].username (4) document.forms[0].elements[username] (4) 3.14. Locating Elements 31
document.forms[0].elements[0] (4) document.forms[0].elements[3] (7) You can use Selenium itself as well as other sites and extensions to explore the DOM of your web application. A good reference exists on W3Schools. Locating by CSS CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents. CSS uses Selectors for binding style properties to elements in the document. These Selectors can be used by Selenium as another locating strategy.
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id= "loginForm" > <input class= "required" name= "username" type= "text" /> <input class= "required passfield" name= "password" type= "password" /> <input name= "continue" type= "submit" value= "Login" /> <input name= "continue" type= "button" value= "Clear" /> </form> </body> <html>
css=form#loginForm (3) css=input[name="username"] (4) css=input.required[type="text"] (4) css=input.passfield (5) css=#loginForm input[type="button"] (4) css=#loginForm input:nth-child(2) (5) For more information about CSS Selectors, the best place to go is the W3C publication. Youll nd additional references there. Note: Most experienced Selenium users recommend CSS as their locating strategy of choice as its considerably faster than XPath and can nd the most complicated objects in an intrinsic HTML document. Implicit Locators You can choose to omit the locator type in the following situations: Locators without an explicitly dened locator strategy will default to using the identier locator strategy. See Locating by Identier. Locators starting with // will use the XPath locator strategy. See Locating by XPath. Locators starting with document will use the DOM locator strategy. See Locating by DOM 32 Chapter 3. Selenium-IDE
The actual title of the page reached by clicking on the link was De Anza Film And Television Department - Menu. By using a pattern rather than the exact text, the verifyTitle will pass as long as the two words Film and Television appear (in that order) anywhere in the pages title. For example, if the pages owner should shorten the title to just Film & Television Department, the test would still pass. Using a pattern for both a link and a simple test that the link worked (such as the verifyTitle above does) can greatly reduce the maintenance for such test cases.
33
Regular Expression Patterns Regular expression patterns are the most powerful of the three types of patterns that Selenese supports. Regular expressions are also supported by most high-level programming languages, many text editors, and a host of tools, including the Linux/Unix command-line utilities grep, sed, and awk. In Selenese, regular expression patterns allow a user to perform many tasks that would be very difcult otherwise. For example, suppose your test needed to ensure that a particular table cell contained nothing but a number. regexp: [0-9]+ is a simple pattern that will match a decimal number of any length. Whereas Selenese globbing patterns support only the * and [ ] (character class) features, Selenese regular expression patterns offer the same wide array of special characters that exist in JavaScript. Below are a subset of those special characters: PATTERN . [] * + ? {1,5} | () MATCH any single character character class: any single character that appears inside the brackets quantier: 0 or more of the preceding character (or group) quantier: 1 or more of the preceding character (or group) quantier: 0 or 1 of the preceding character (or group) quantier: 1 through 5 of the preceding character (or group) alternation: the character/group on the left or the character/group on the right grouping: often used with alternation and/or quantier
Regular expression patterns in Selenese need to be prexed with either regexp: or regexpi:. The former is case-sensitive; the latter is case-insensitive. A few examples will help clarify how regular expression patterns can be used with Selenese commands. The rst one uses what is probably the most commonly used regular expression pattern.* (dot star). This two-character sequence can be translated as 0 or more occurrences of any character or more simply, anything or nothing. It is the equivalent of the one-character globbing pattern * (a single asterisk). Command click verifyTitle Target link=regexp:Film.*Television Department regexp:.*Film.*Television.* Value
The example above is functionally equivalent to the earlier example that used globbing patterns for this same test. The only differences are the prex (regexp: instead of glob:) and the anything or nothing pattern (.* instead of just *). The more complex example below tests that the Yahoo! Weather page for Anchorage, Alaska contains info on the sunrise time: Command open verifyTextPresent Target http://weather.yahoo.com/forecast/USAK0012.html regexp:Sunrise: *[0-9]{1,2}:[0-9]{2} [ap]m Value
Lets examine the regular expression above one part at a time: Sunrise: * [0-9]{1,2} : [0-9]{2} [ap]m The string Sunrise: followed by 0 or more spaces 1 or 2 digits (for the hour of the day) The character : (no special characters involved) 2 digits (for the minutes) followed by a space a or p followed by m (am or pm)
34
Chapter 3. Selenium-IDE
Exact Patterns The exact type of Selenium pattern is of marginal usefulness. It uses no special characters at all. So, if you needed to look for an actual asterisk character (which is special for both globbing and regular expression patterns), the exact pattern would be one way to do that. For example, if you wanted to select an item labeled Real * from a dropdown, the following code might work or it might not. The asterisk in the glob:Real * pattern will match anything or nothing. So, if there was an earlier select option labeled Real Numbers, it would be the option selected rather than the Real * option. select //select glob:Real *
In order to ensure that the Real * item would be selected, the exact: prex could be used to create an exact pattern as shown below: select //select exact:Real *
But the same effect could be achieved via escaping the asterisk in a regular expression pattern: select //select regexp:Real \*
Its rather unlikely that most testers will ever need to look for an asterisk or a set of square brackets with characters inside them (the character class for globbing patterns). Thus, globbing patterns and regular expression patterns are sufcient for the vast majority of us.
Selenese, by itself, does not support condition statements (if-else, etc.) or iteration (for, while, etc.). Many useful tests can be conducted without ow control. However, for a functional test of dynamic content, possibly involving multiple pages, programming logic is often needed. When ow 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 languages ow control features. 2. Run a small JavaScript snippet from within the script using the storeEval command. 3. Install the goto_sel_ide.js extension. Most testers will export the test script into a programming language le that uses the Selenium-RC API (see the Selenium-IDE chapter). However, some organizations prefer to run their scripts from SeleniumIDE whenever possible (for instance, when they have many junior-level people running tests for them, or when programming skills are lacking). If this is your case, consider a JavaScript snippet or the goto_sel_ide.js extension.
Later in your script, youll 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 verifyText Target //div/p Value ${userName}
A common use of variables is for storing input for an input eld. Command type Target id=login Value ${userName}
Selenium variables can be used in either the rst 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. An equivalent store command exists for each verify and assert command. Here are a couple more commonly used store commands.
3.19.1 storeElementPresent
This corresponds to verifyElementPresent. It simply stores a boolean valuetrue or falsedepending on whether the UI element is found.
36
Chapter 3. Selenium-IDE
3.19.2 storeText
StoreText corresponds to verifyText. It uses a locater to identify specic page text. The text, if found, is stored in the variable. StoreText can be used to extract text from the page being tested.
3.19.3 storeEval
This command takes a script as its rst 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.
This next example illustrates how a JavaScript snippet can include calls to methods, in this case the JavaScript String objects toUpperCase method and toLowerCase method. Command store storeEval storeEval Target Edith Wharton storedVars[name].toUpperCase() storedVars[name].toLowerCase() Value name uc lc
JavaScript Usage with Non-Script Parameters JavaScript can also be used to help generate values for parameters, even when the parameter is not specied to be of type script. However, in this case, special syntax is requiredthe JavaScript snippet must be enclosed inside curly braces and preceded by the label javascript, as in javascript {*yourCodeHere*}. Below is an example in which the type commands second parameter value is generated via JavaScript code using this special syntax:
37
<!DOCTYPE HTML> <html> <head> <script type= "text/javascript" > function output(resultText){ document.getElementById( output ).childNodes[0].nodeValue=resultText; } function show_confirm(){ var confirmation=confirm( "Chose an option." ); if (confirmation==true){ output( "Confirmed." ); } else{ output( "Rejected!" ); } } function show_alert(){ alert( "Im blocking!" ); output( "Alert is gone." ); } function show_prompt(){ var response = prompt( "Whats the best web QA tool?" , "Selenium" ); output(response); } function open_window(windowName){ window.open( "newWindow.html" ,windowName); } </script> </head> <body>
38
Chapter 3. Selenium-IDE
34 35 36 37 38 39 40 41 42 43 44 45
<input type= "button" id= <input type= "button" id= <input type= "button" id= <a href= "newWindow.html" <input type= "button" id= <input type= "button" id= <br /> <span id= "output" > </span> </body> </html>
"btnConfirm" onclick= "show_confirm()" value= "Show confirm b "btnAlert" onclick= "show_alert()" value= "Show alert" /> "btnPrompt" onclick= "show_prompt()" value= "Show prompt" /> id= "lnkNewWindow" target= "_blank" >New Window Link</a> "btnNewNamelessWindow" onclick= "open_window()" value= "Open "btnNewNamedWindow" onclick= "open_window(Mike)" value= "Op
The user must respond to alert/conrm boxes, as well as moving focus to newly opened popup windows. Fortunately, Selenium can cover JavaScript pop-ups. But before we begin covering alerts/conrms/prompts in individual detail, it is helpful to understand the commonality between them. Alerts, conrmation boxes and prompts all have variations of the following Command assertFoo(pattern) assertFooPresent assertFooNotPresent storeFoo(variable) storeFooPresent(variable) Description throws error if pattern doesnt match the text of the pop-up throws error if pop-up is not available throws error if any pop-up is present stores the text of the pop-up in a variable stores the text of the pop-up in a variable and returns true or false
When running under Selenium, JavaScript pop-ups will not appear. This is because the function calls are actually being overridden at runtime by Seleniums own JavaScript. However, just because you cannot see the pop-up doesnt mean you dont have do 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.]
3.22.1 Alerts
Lets start with asserts because they are the simplest pop-up to handle. To begin, open the HTML sample above in a browser and click on the Show alert button. Youll notice that after you close the alert the text Alert is gone. is displayed on the page. Now run through the same steps with Selenium IDE recording, and verify the text is added after you close the alert. Your test will look something like this: Command open click assertAlert verifyTextPresent Target / btnAlert Im blocking! Alert is gone. Value
You may be thinking Thats odd, I never tried to assert that alert. But this is Selenium-IDE handling and closing the alert for you. If you remove that step and replay the test you will get the following error [error] Error: There was an unexpected Alert! [Im blocking!]. You must include an assertion of the alert to acknowledge its presence. If you just want to assert that an alert is present but either dont know or dont care what text it contains, you can use assertAlertPresent. This will return true or false, with false halting the test.
39
Conrmations Conrmations behave in much the same way as alerts, with assertConfirmation and assertConfirmationPresent offering the same characteristics as their alert counterparts. However, by default Selenium will select OK when a conrmation pops up. Try recording clicking on the Show conrm box button in the sample page, but click on the Cancel button in the popup, then assert the output text. Your test may look something like this: Command open click chooseCancelOnNextConrmation assertConrmation verifyTextPresent Target / btnConrm Choose and option. Rejected Value
The chooseCancelOnNextConfirmation function tells Selenium that all following conrmation should return false. It can be reset by calling chooseOkOnNextConrmation. You may notice that you cannot replay this test, because Selenium complains that there is an unhandled conrmation. This is because the order of events Selenium-IDE records causes the click and chooseCancelOnNextConrmation to be put in the wrong order (it makes sense if you think about it, Selenium cant know that youre cancelling before you open a conrmation) Simply switch these two commands and your test will run ne.
3.23 Debugging
Debugging means nding and xing errors in your test case. This is a normal part of test case development. We wont teach debugging here as most new users to Selenium will already have some basic experience with debugging. If this is new to you, we recommend you ask one of the developers in your organization.
40
Chapter 3. Selenium-IDE
1. Immediately pause the executing test case with the Pause button.
3.23. Debugging
41
column of the drop-down provides alternative locators, whereas the second column indicates the type of each alternative.
42
Chapter 3. Selenium-IDE
<body> <table cellpadding= "1" cellspacing= "1" border= "1" > <thead> <tr><td>Test Cases for De Anza A-Z Directory Links</td></tr> </thead> <tbody> <tr><td><a href= "./a.html" >A Links</a></td></tr> <tr><td><a href= "./b.html" >B Links</a></td></tr> <tr><td><a href= "./c.html" >C Links</a></td></tr> <tr><td><a href= "./d.html" >D Links</a></td></tr> </tbody> </table> </body> </html>
Note: Test case les should not have to be co-located with the test suite le that invokes them. And on Mac OS and Linux systems, that is indeed the case. However, at the time of this writing, a bug prevents Windows users from being able to place the test cases elsewhere than with the test suite that invokes them.
After selecting the OK button, you must close and reopen Selenium-IDE in order for the extensions le to be read. Any change you make to an extension will also require you to close and reopen SeleniumIDE.
43
Information on writing your own extensions can be found near the bottom of the Selenium Reference document.
3.26 Format
Format, under the Options menu, allows you to select a language for saving and displaying the test case. The default is HTML. If you will be using Selenium-RC to run your test cases, this feature is used to translate your test case into a programming language. Select the language, i.e. Java, PHP, you will be using with Selenium-RC for developing your test programs. Then simply save the test case using File=>Save. Your test case will be translated into a series of functions in the language you choose. Essentially, program code supporting your test is generated for you by Selenium-IDE. Also, note that if the generated code does not suit your needs, you can alter it by editing a conguration le which denes the generation process. Each supported language has conguration settings which are editable. This is under the Options=>Options=>Format tab. Note: At the time of this writing, this feature is not yet supported by the Selenium developers. However the author has altered the C# format in a limited manner and it has worked well.
3.28 Troubleshooting
Below is a list of image/explanation pairs which describe frequent sources of problems with SeleniumIDE: Table view is not available with this format. This message can be occasionally displayed in the Table tab when Selenium IDE is launched. The workaround is to close and reopen Selenium IDE. See issue 1008. for more information. If you are able to reproduce this reliably then please provide details so that we can work on a x.
error loading test case: no command found Youve used File=>Open to try to open a test suite le. Use File=>Open Test Suite instead. An enhancement request has been raised to improve this error message. See issue 1010.
44
Chapter 3. Selenium-IDE
This type of error may indicate a timing problem, i.e., the element specied by a locator in your command wasnt fully loaded when the command was executed. Try putting a pause 5000 before the command to determine whether the problem is indeed related to timing. If so, investigate using an appropriate waitFor* or *AndWait command before the failing command.
Whenever your attempt to use variable substitution fails as is the case for the open command above, it indicates that you havent actually created the variable whose value youre trying to access. This is sometimes due to putting the variable in the Value eld when it should be in the Target eld or vice versa. In the example above, the two parameters for the store command have been erroneously placed in the reverse order of what is required. For any Selenese command, the rst required parameter must go in the Target eld, and the second required parameter (if one exists) must go in the Value eld.
error loading test case: [Exception... Component returned failure code: 0x80520012 (NS_ERROR_FILE_NOT_FOUND) [nsIFileInputStream.init] nresult: 0x80520012 (NS_ERROR_FILE_NOT_FOUND) location: JS frame :: chrome://selenium-ide/content/leutils.js :: anonymous :: line 48 data: no] One of the test cases in your test suite cannot be found. Make sure that the test case is indeed located where the test suite indicates it is located. Also, make sure that your actual test case les have the .html extension both in their lenames, and in the test suite le where they are referenced. An enhancement request has been raised to improve this error message. See issue 1011.
Selenium-IDE is very space-sensitive! An extra space before or after a command will cause it to be unrecognizable. 3.28. Troubleshooting 45
Your extension les contents have not been read by Selenium-IDE. Be sure you have specied the proper pathname to the extensions le via Options=>Options=>General in the Selenium Core extensions eld. Also, Selenium-IDE must be restarted after any change to either an extensions le or to the contents of the Selenium Core extensions eld.
This type of error message makes it appear that Selenium-IDE has generated a failure where there is none. However, Selenium-IDE is correct that the actual value does not match the value specied in such test cases. The problem is that the log le error messages collapse a series of two or more spaces into a single space, which is confusing. In the example above, note that the parameter for verifyTitle has two spaces between the words Selenium and web The pages actual title has only one space between these words. Thus, Selenium-IDE is correct to generate an error, but is misleading in the nature of the error. This defect has been raised. See issue 1013.
46
Chapter 3. Selenium-IDE
CHAPTER
FOUR
47
4.3.1 Java
The easiest way to set up a Selenium 2.0 Java project is to use Maven. Maven will download the java bindings (the Selenium 2.0 java client library) and all its dependencies, and will create the project for you, using a maven pom.xml (project conguration) le. Once youve done this, you can import the maven project into your preferred IDE, IntelliJ IDEA or Eclipse. First, create a folder to contain your Selenium project les. Then, to use Maven, you need a pom.xml le. This can be created with a text editor. We wont teach the details of pom.xml les or for using Maven since there are already excellent references on this. Your pom.xml le will look something like this. Create this le in the folder you created for your project.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apac <modelVersion>4.0.0</modelVersion> <groupId>MySel20Proj</groupId> <artifactId>MySel20Proj</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.9.0</version> </dependency> </dependencies> </project>
Be sure you specify the most current version. At the time of writing, the version listed above was the most current, however there were frequent releases immediately after the releast of Selenium 2.0. Check the Maven download page for the current release and edit the above dependency accordingly. Now, from a command-line, CD into the project directory and run maven as follows.
mvn clean install
This will download Selenium and all its dependencies and will add them to the project. Finally, import the project into your preferred development environment. For those not familiar with this, weve provided an appendix which shows this. Importing a maven project into IntelliJ IDEA.
4.3.2 C#
As of Selenium 2.2.0 is distributed as a set of signed dlls and all other dependency dlls. Prior to 2.2.0, all Selenium dlls were unsigned. To include Selenium in your project, simply download the latest
48
selenium-dotnet zip le from https://code.google.com/p/selenium/downloads/list. If you are using Windows Vista or above, you should unblock the zip le before unzipping it: Right click on the zip le, click Properties, click Unblock and click OK. Unzip the contents of the zip le, and add a reference to each of the unzipped dlls to your project in Visual Studio (or your IDE of choice). Ofcial NuGet Packages: RC WebDriver WebDriverBackedSelenium Support
4.3.3 Python
If you are using Python for test automation then you probably are already familiar with developing in Python. To add Selenium to your Python environment run the following command from a commandline.
pip install selenium
Teaching Python development itself is beyond the scope of this document, however there are many resources on Python and likely developers in your organization can help you get up to speed.
4.3.4 Ruby
If you are using Ruby for test automation then you probably are already familiar with developing in Ruby. To add Selenium to your Ruby environment run the following command from a command-line.
gem install selenium-webdriver
Teaching Ruby development itself is beyond the scope of this document, however there are many resources on Ruby and likely developers in your organization can help you get up to speed.
4.3.5 Perl
Perl is not supported in Selenium 2.0 at this time. If you have questions, or would like to assist providing this support, please post a note to the Selenium developers.
4.3.6 PHP
PHP is not supported in Selenium 2.0 at this time. If you have questions, or would like to assist providing this support, please post a note to the Selenium developers.
49
public class Selenium2Example { public static void main(String[] args) { // Create a new instance of the Firefox driver // Notice that the remainder of the code relies on the interface, // not the implementation. WebDriver driver = new FirefoxDriver(); // And now use this to visit Google driver.get( "http://www.google.com" ); // Alternatively the same thing can be done like this // driver.navigate().to("http://www.google.com"); // Find the text input element by its name WebElement element = driver.findElement(By.name( "q" )); // Enter something to search for element.sendKeys( "Cheese!" ); // Now submit the form. WebDriver will find the form for us from the element element.submit(); // Check the title of the page System.out.println( "Page title is: " + driver.getTitle()); // Googles search is rendered dynamically with JavaScript. // Wait for the page to load, timeout after 10 seconds (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().startsWith( "cheese!" ); } });
50
// Should see: "cheese! - Google Search" System.out.println( "Page title is: " + driver.getTitle()); //Close the browser driver.quit(); } }
using OpenQA.Selenium.Firefox; using OpenQA.Selenium; class GoogleSuggest { static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); //Notice navigation is slightly different than the Java version //This is because get is a keyword in C# driver.Navigate().GoToUrl( "http://www.google.com/" ); IWebElement query = driver.FindElement(By.Name( "q" )); query.SendKeys( "Cheese" ); System.Console.WriteLine( "Page title is: " + driver.Title); // TODO add wait driver.Quit(); } }
from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 import time # Create a new instance of the Firefox driver driver = webdriver.Firefox() # go to the google home page driver.get( " http://www.google.com " ) # find the element thats name attribute is q (the google search box) inputElement = driver.find_element_by_name( " q " ) # type in the search inputElement.send_keys( " Cheese! " ) # submit the form (although google automatically searches now without submitting) inputElement.submit() # the page is ajaxy so the title is originally this: print driver.title try:
51
# we have to wait for the page to refresh, the last thing that seems to be updated i WebDriverWait(driver, 10).until(lambda driver : driver.title.lower().startswith( " ch # You should see "cheese! - Google Search" print driver.title finally: driver.quit()
require rubygems require selenium-webdriver driver = Selenium::WebDriver.for :firefox driver.get " http://google.com " element = driver.find_element :name => " q " element.send_keys " Cheese! " element.submit puts " Page title is #{ driver.title } "
wait = Selenium::WebDriver::Wait.new(:timeout => 10) wait.until { driver.title.downcase.start_with? " cheese! " } puts " Page title is driver.quit #{ driver.title } "
In upcoming sections, you will learn more about how to use WebDriver for things such as navigating forward and backward in your browsers history, and how to test web sites that use frames and windows. We also provide a more thorough discussions and examples.
You can nd out more information about each of these by following the links in the table. Which you use depends on what you want to do. For sheer speed, the HtmlUnit Driver is great, but its not graphical, which means that you cant watch whats happening. As a developer you may be comfortable with this, but sometimes its good to be able to test using a real browser, especially when youre showing a demo of your application (or running the tests) for an audience. Often, this idea is referred to as safety, and it falls into two parts. Firstly, theres actual safety, which refers to whether or not the tests work as they should. This can be measured and quantied. Secondly, theres perceived safety, which refers to
52
whether or not an observer believes the tests work as they should. This varies from person to person, and will depend on their familiarity with the application under test, WebDriver, and your testing framework. To support higher perceived safety, you may wish to choose a driver such as the Firefox Driver. This has the added advantage that this driver actually renders content to a screen, and so can be used to detect information such as the position of an element on a page, or the CSS properties that apply to it. However, this additional exibility comes at the cost of slower overall speed. By writing your tests against the WebDriver interface, it is possible to pick the most appropriate driver for a given test. To keep things simple, lets start with the HtmlUnit Driver:
WebDriver driver = new HtmlUnitDriver();
WebDriver will wait until the page has fully loaded (that is, the onload event has red) before returning control to your test or script. Its worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use an Explicit and Implicit Waits.
You can also look for a link by its text, but be careful! The text must be an exact match! You should also be careful when using XPATH in WebDriver. If theres more than one element that matches the query, then only the rst will be returned. If nothing can be found, a NoSuchElementException will be thrown. WebDriver has an Object-based API; we represent all types of elements using the same interface: Web Element. This means that although you may see a lot of possible methods you could invoke when you hit your IDEs auto-complete key combination, not all of them will make sense or be valid. Dont 4.7. Commands and Operation 53
worry! WebDriver will attempt to do the Right Thing, and if you call a method that makes no sense (setSelected() on a meta tag, for example) an exception will be thrown. So, youve got an element. What can you do with it? First of all, you may want to enter some text into a text eld:
element.sendKeys( "some text" );
You can simulate pressing the arrow keys by using the Keys class:
element.sendKeys( " and some" , Keys.ARROW_DOWN);
It is possible to call sendKeys on any element, which makes it possible to test keyboard shortcuts such as those used on GMail. A side-effect of this is that typing something into a text eld wont automatically clear it. Instead, what you type will be appended to whats already there. You can easily clear the contents of a text eld or textarea:
element.clear();
The following number of matches will be found XPath expression //input //INPUT HtmlUnit Driver 1 (example) 0 Firefox Driver 2 2 Internet Explorer Driver 2 0
54
Sometimes HTML elements do not need attributes to be explicitly declared because they will default to known values. For example, the input tag does not require the type attribute because it defaults to text. The rule of thumb when using xpath in WebDriver is that you should not expect to be able to match against these implicit attributes.
This will nd the rst SELECT element on the page, and cycle through each of its OPTIONs in turn, printing out their values, and selecting each in turn. As you will notice, this isnt the most efcient way of dealing with SELECT elements. WebDrivers support classes include one called Select, which provides useful methods for interacting with these.
Select select = new Select(driver.findElement(By.xpath( "//select" ))); select.deselectAll(); select.selectByVisibleText( "Edam" );
This will deselect all OPTIONs from the rst SELECT on the page, and then select the OPTION with the displayed text of Edam. Once youve nished lling out the form, you probably want to submit it. One way to do this would be to nd the submit button and click it:
driver.findElement(By.id( "submit" )).click(); // Assume the button has the ID "submit" :)
Alternatively, WebDriver has the convenience method submit on every element. If you call this on an element within a form, WebDriver will walk up the DOM until it nds the enclosing form and then calls submit on that. If the element isnt in a form, then the NoSuchElementException will be thrown:
element.submit();
55
All calls to driver will now be interpreted as being directed to the particular window. But how do you know the windows name? Take a look at the javascript or link that opened it:
<a href= "somewhere.html" target= "windowName" >Click here to open a new window</a>
Alternatively, you can pass a window handle to the switchTo().window() method. Knowing this, its possible to iterate over every open window like so:
for (String handle : driver.getWindowHandles()) { driver.switchTo().window(handle); }
You can also swing from frame to frame (or into iframes):
driver.switchTo().frame( "frameName" );
Its possible to access subframes by separating the path with a dot, and you can specify the frame by its index too. That is:
driver.switchTo().frame( "frameName.0.child" );
would go to the frame named child of the rst subframe of the frame called frameName. All frames are evaluated as if from *top*.
This will return the currently open alert object. With this object you can now accept, dismiss, read its contents or even type into a prompt. This interface works equally well on alerts, conrms, prompts. Refer to the JavaDocs for more information.
To reiterate: navigate().to() and get() do exactly the same thing. Ones just a lot easier to type than the other! The navigate interface also exposes the ability to move backwards and forwards in your browsers history: 56 Chapter 4. Selenium 2.0 and WebDriver
driver.navigate().forward(); driver.navigate().back();
Please be aware that this functionality depends entirely on the underlying browser. Its just possible that something unexpected may happen when you call these methods if youre used to the behaviour of one browser over another.
4.7.8 Cookies
Before we leave these next steps, you may be interested in understanding how to use cookies. First of all, you need to be on the domain that the cookie will be valid for. If you are trying to preset cookies before you start interacting with a site and your homepage is large / takes a while to load an alternative is to nd a smaller page on the site, typically the 404 page is small (http://example.com/some404page)
// Go to the correct domain driver.get( "http://www.example.com" ); // Now set the cookie. This ones valid for the entire domain Cookie cookie = new Cookie( "key" , "value" ); driver.manage().addCookie(cookie);
// And now output all the available cookies for the current URL Set<Cookie> allCookies = driver.manage().getCookies(); for (Cookie loadedCookie : allCookies) { System.out.println(String.format( "%s -> %s" , loadedCookie.getName(), loadedCookie.g } // You can delete cookies in 3 ways // By name driver.manage().deleteCookieNamed( "CookieName" ); // By Cookie driver.manage().deleteCookie(loadedCookie); // Or all of them driver.manage().deleteAllCookies();
# Go to the correct domain driver.get( " http://www.example.com " ) # Now set the cookie. Heres one for the entire domain # the cookie name here is key and its value is value driver.add_cookie({ key : value }) # And now output all the available cookies for the current URL for cookie in driver.get_cookies: print " %s -> %s " % (cookie[ name ], cookie[ value ]) # You can delete cookies in 2 ways # By name driver.delete_cookie( " CookieName " ) # Or all of them driver.delete_all_cookies()
57
58
Enabling JavaScript If you cant wait, enabling JavaScript support is very easy:
HtmlUnitDriver driver = new HtmlUnitDriver(); driver.setJavascriptEnabled(true);
This will cause the HtmlUnit Driver to emulate Internet Explorers JavaScript handling by default.
Mofying the Firefox Prole Suppose that you wanted to modify the user agent string (as above), but youve got a tricked out Firefox prole that contains dozens of useful extensions. There are two ways to obtain this prole. Assuming that the prole has been created using Firefoxs prole manager (firefox -ProfileManager):
ProfileIni allProfiles = new ProfilesIni(); FirefoxProfile profile = allProfiles.getProfile( "WebDriver" ); profile.setPreferences( "foo.bar" , 23); WebDriver driver = new FirefoxDriver(profile);
As we develop features in the Firefox Driver, we expose the ability to use them. For example, until we feel native events are stable on Firefox for Linux, they are disabled by default. To enable them:
59
Info See the Firefox secion in the wiki page for the most up to date info.
60
Getting running with Chrome Driver Note: this section is likely out of date. If you used the commands at the beginning of this chapter for setting up a Selenium 2 project you should already have the Chrome Driver along with all the other drivers. Download the Chrome Driver executable and follow the other instructions on the wiki page
// Get the underlying WebDriver implementation back. This will refer to the // same WebDriver instance as the "driver" variable above. WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getUnderlyingWebDriver() //Finally, close the browser. Call stop on the WebDriverBackedSelenium instance //instead of calling driver.quit(). Otherwise, the JVM will continue running after //the browser has been closed. selenium.stop();
61
4.9.1 Pros
Allows for the WebDriver and Selenium APIs to live side-by-side Provides a simple mechanism for a managed migration from the Selenium RC API to WebDrivers Does not require the standalone Selenium RC server to be run
4.9.2 Cons
Does not implement every method More advanced Selenium usage (using browserbot or other built-in JavaScript methods from Selenium Core) may not work Some methods may be slower due to underlying implementation differences
Capabilities capabilities = new DesiredCapabilities() capabilities.setBrowserName( "safari" ); CommandExecutor executor = new SeleneseCommandExecutor( "http:localhost:4444/" , "http:// WebDriver driver = new RemoteWebDriver(executor, capabilities);
There are currently some major limitations with this approach, notably that ndElements doesnt work as expected. Also, because were using Selenium Core for the heavy lifting of driving the browser, you are limited by the JavaScript sandbox.
62
CHAPTER
FIVE
IWebDriver driver = new FirefoxDriver(); driver.Url = "http://somedomain/url_that_delays_loading" ; WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement myDynamicElement = wait.Until<IWebElement>((d) => { return d.FindElement(By.Id( "someDynamicElement" )); });
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
ff = webdriver.Firefox() ff.get( " http://somedomain/url_that_delays_loading " ) try: element = WebDriverWait(ff, 10).until(lambda driver : driver.find_element_by_id( " my finally: ff.quit()
63
require rubygems # not required for ruby 1.9 or if you installed without gem require selenium-webdriver driver = Selenium::WebDriver.for :firefox driver.get " http://somedomain/url_that_delays_loading " wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds begin element = wait.until { driver.find_element(:id => " some-dynamic-element " ) } ensure driver.quit end
This waits up to 10 seconds before throwing a TimeoutException or if it nds the element will return it in 0 - 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types. This example is also functionally equivalent to the rst Implicit Waits example.
WebDriver driver = new FirefoxDriver(); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); driver.Url = "http://somedomain/url_that_delays_loading" ; IWebElement myDynamicElement = driver.FindElement(By.Id( "someDynamicElement" ));
from selenium import webdriver ff = webdriver.Firefox() ff.implicitly_wait(10) # seconds ff.get( " http://somedomain/url_that_delays_loading " ) myDynamicElement = ff.find_element_by_id( " myDynamicElement " )
require rubygems # not required for ruby 1.9 or if you installed without gem require selenium-webdriver driver = Selenium::WebDriver.for :firefox driver.manage.timeouts.implicit_wait = 10 # seconds
64
driver.get " http://somedomain/url_that_delays_loading " element = driver.find_element(:id => " some-dynamic-element " )
5.2 RemoteWebDriver
5.2.1 Taking a Screenshot
import java.io.File; import java.net.URL; import import import import import import org.openqa.selenium.OutputType; org.openqa.selenium.TakesScreenshot; org.openqa.selenium.WebDriver; org.openqa.selenium.remote.Augmenter; org.openqa.selenium.remote.DesiredCapabilities; 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); } }
// Add this class to your code and use this instead of RemoteWebDriver // You will then be able to cast it to ITakesScreenshot and call GetScreenshot public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot { /// <summary> /// Gets a <see cref="Screenshot"/> object representing the image of the page on /// </summary> /// <returns>A <see cref="Screenshot"/> object containing the image.</returns> public Screenshot GetScreenshot() { // Get the screenshot as base64. Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null); string base64 = screenshotResponse.Value.ToString(); // ... and convert it. return new Screenshot(base64);
5.2. RemoteWebDriver
65
} }
driver = webdriver.Remote( " http://localhost:4444/wd/hub " , webdriver.DesiredCapabiliti driver.get( " http://www.google.com " ) driver.get_screenshot_as_file( /Screenshots/google.png )
begin driver = Selenium::WebDriver.for :remote, :url => " http://localhost:4444/wd/hub " , : driver.get " http://www.google.com " driver.save_screenshot " /Screenshots/google.png " ensure driver.quit end
5.3 AdvancedUserInteractions
Todo
66
proxy.setHttpProxy(PROXY) .setFtpProxy(PROXY) .setSslProxy(PROXY); DesiredCapabilities cap = new DesiredCapabailities(); cap.setPreference(CapabilityType.PROXY, proxy); WebDriver driver = new InternetExplorerDriver(cap);
from selenium import webdriver PROXY = " localhost:8080 " webdriver.DesiredCapabilities.INTERNETEXPLORER[ proxy ] = { " httpProxy " :PROXY, " ftpProxy " :PROXY, " sslProxy " :PROXY, " noProxy " :None, " proxyType " : " MANUAL " , " class " : " org.openqa.selenium.Proxy " , " autodetect " :False }
# you have to use remote, otherwise youll have to code it yourself in python to # dynamically changing the system proxy preferences driver = webdriver.Remote( " http://localhost:4444/wd/hub " , webdriver.DesiredCapabiliti
caps = Selenium::WebDriver::Remote::Capabilities.ie(:proxy => Selenium::WebDriver::Proxy :http => PROXY, :ftp=>PROXY, :ssl=>PROXY, :no_proxy=>nil )) # you have to use remote, otherwise youll have to code it yourself in ruby to # dynamically changing the system proxy preferences driver = Selenium::WebDriver.for :remote, :url => " http://localhost:4444/wd/hub " , :d
Chrome Is basically the same as internet explorer. It uses the same conguration on the machine as IE does (on windows). On Mac it uses the System Preference -> Network settings. On Linux it uses (on Ubuntu) System > Preferences > Network Proxy Preferences (Alternatively in /etc/environment set http_proxy). As of this writing it is unknown how to set the proxy programmatically.
67
Firefox Firefox maintains its proxy conguration in a prole. You can preset the proxy in a prole and use that Firefox Prole or you can set it on prole that is created on the y as is shown in the following example.
String PROXY = "localhost:8080" ; org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy(); proxy.setHttpProxy(PROXY) .setFtpProxy(PROXY) .setSslProxy(PROXY); DesiredCapabilities cap = new DesiredCapabailities(); cap.setPreference(CapabilityType.PROXY, proxy); WebDriver driver = new FirefoxDriver(cap);
from selenium import webdriver PROXY_HOST = " host " PROXY_PORT = 8080 fp = webdriver.FirefoxProfile() # Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5 fp.set_preference( " network.proxy.type " , 1) fp.set_preference( fp.set_preference( fp.set_preference( fp.set_preference( fp.set_preference( fp.set_preference( " " " " " " network.proxy.http " , PROXY_HOST) network.proxy.http_port " , PROXY_PORT) network.proxy.ftp " , PROXY_HOST) network.proxy.ftp_port " , PROXY_PORT) network.proxy.ssl " , PROXY_HOST) network.proxy.ssl_port " , PROXY_PORT)
fp.set_preference( " network.proxy.no_proxies_on " , " " ) # set this value as desired driver = webdriver.Firefox(firefox_profile=fp)
require rubygems require selenium-webdriver PROXY = localhost:8087 profile = Selenium::WebDriver::Firefox::Profile.new profile.proxy = Selenium::WebDriver::Proxy.new( :http => PROXY, :ftp => PROXY, :ssl => PROXY, :no_proxy => nil ) driver = Selenium::WebDriver.for :firefox, :profile => profile
68
Opera Todo
5.5 HTML5
Todo
5.5. HTML5
69
70
CHAPTER
SIX
6.2.1 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. Here is a simplied architecture diagram....
71
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 verication you specied in your test script.
72
6.3 Installation
Installation is rather a misnomer for Selenium. Selenium has set of libraries available in the programming language of your choice. You could download them from downloads page Once youve chosen a language to work with, you simply need to: Install the Selenium RC Server. Set up a programming project using a language specic client driver.
6.3. Installation
73
java -version If you get a version number (which needs to be 1.5 or later), youre ready to start using Selenium RC.
Add references to the following DLLs: nmock.dll, nunit.core.dll, nunit. framework.dll, ThoughtWorks.Selenium.Core.dll, ThoughtWorks.Selenium.IntegrationTests.dll and ThoughtWorks.Selenium.UnitTests.dll Write your Selenium test in a .Net language (C#, VB.Net), or export a script from Selenium-IDE to a C# le and copy this code into the class le you just created. Write your own simple main() program or you can include NUnit in your project for running your test. These concepts are explained later in this chapter. Run Selenium server from console Run your test either from the IDE, from the NUnit GUI or from the command line For specic details on .NET client driver conguration with Visual Studio, see the appendix .NET client driver conguration.
75
namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium; private StringBuilder verificationErrors;
[SetUp] public void SetupTest() { selenium = new DefaultSelenium( "localhost" , 4444, "*firefox" , "http://www. selenium.Start(); verificationErrors = new StringBuilder(); } [TearDown] public void TeardownTest() { try { selenium.Stop(); } catch (Exception) { // Ignore errors if unable to close the browser } Assert.AreEqual( "" , verificationErrors.ToString()); } [Test] public void TheNewTest() { selenium.Open( "/" ); selenium.Type( "q" , "selenium rc" ); selenium.Click( "btnG" ); selenium.WaitForPageToLoad( "30000" ); Assert.AreEqual( "selenium rc - Google Search" , selenium.GetTitle()); } } }
76
/** Add JUnit framework to your classpath if not already there * for this example to work / * package com.example.tests; import com.thoughtworks.selenium.*; import java.util.regex.Pattern; public class NewTest extends SeleneseTestCase { public void setUp() throws Exception { setUp( "http://www.google.com/" , "*firefox" ); } public void testNew() throws Exception { selenium.open( "/" ); selenium.type( "q" , "selenium rc" ); selenium.click( "btnG" ); selenium.waitForPageToLoad( "30000" ); assertTrue(selenium.isTextPresent( "Results * for selenium rc" )); } }
my $sel = Test::WWW::Selenium->new( host => "localhost" , port => 4444, browser => "*firefox" , browser_url => "http://www.google.com/" ); $sel->open_ok( "/" ); $sel->type_ok( "q" , "selenium rc" ); $sel->click_ok( "btnG" ); $sel->wait_for_page_to_load_ok( "30000" ); $sel->is_text_present_ok( "Results * for selenium rc" );
<?php require_once PHPUnit/Extensions/SeleniumTestCase.php ; class Example extends PHPUnit_Extensions_SeleniumTestCase { function setUp() { $this->setBrowser( " *firefox " ); $this->setBrowserUrl( " http://www.google.com/ " ); } function testMyTestCase() {
77
$this->open( " / " ); $this->type( " q " , " selenium rc " ); $this->click( " btnG " ); $this->waitForPageToLoad( " 30000 " ); $this->assertTrue($this->isTextPresent( " Results * for selenium rc " )); } } ?>
from selenium import selenium import unittest, time, re class NewTest(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium( " localhost " , 4444, " *firefox " , " http://www.google.com/ " ) self.selenium.start() def test_new(self): sel = self.selenium sel.open( " / " ) sel.type( " q " , " selenium rc " ) sel.click( " btnG " ) sel.wait_for_page_to_load( " 30000 " ) self.failUnless(sel.is_text_present( " Results * for selenium rc " )) def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors)
class NewTest < Test::Unit::TestCase def setup @verification_errors = [] if $selenium @selenium = $selenium else @selenium = Selenium::SeleniumDriver.new( " localhost " , 4444, " *firefox " , " ht @selenium.start end @selenium.set_context( " test_new " ) end def teardown @selenium.stop unless $selenium assert_equal [], @verification_errors end def test_new @selenium.open " / "
78
@selenium.type " q " , " selenium rc " @selenium.click " btnG " @selenium.wait_for_page_to_load " 30000 " assert @selenium.is_text_present( " Results * for selenium rc " ) end end
In the next section well explain how to build a test program using the generated code.
6.5.1 Java
For Java, people use either JUnit or TestNG as the test engine. Some development environments like Eclipse have direct support for these via plug-ins. This makes it even easier. Teaching JUnit or TestNG is beyond the scope of this document however materials may be found online and there are publications available. If you are already a java-shop chances are your developers will already have some experience with one of these test frameworks. You will probably want to rename the test class from NewTest to something of your own choosing. Also, you will need to change the browser-open parameters in the statement:
The Selenium-IDE generated code will look like this. This example has comments added manually for additional clarity.
79
package com.example.tests; // We specify the package of our tests import com.thoughtworks.selenium.*; // This is the drivers import. Youll use this for instantiating a // browser and making it do what you need. import java.util.regex.Pattern; // Selenium-IDE add the Pattern module because its sometimes used for // regex validations. You can remove the module if its not used in your // script. public class NewTest extends SeleneseTestCase { // We create our Selenium test case public void setUp() throws Exception { setUp( "http://www.google.com/" , "*firefox" ); // We instantiate and start the browser } public void testNew() throws Exception { selenium.open( "/" ); selenium.type( "q" , "selenium rc" ); selenium.click( "btnG" ); selenium.waitForPageToLoad( "30000" ); assertTrue(selenium.isTextPresent( "Results * for selenium rc" )); // These are the real test steps } }
6.5.2 C#
The .NET Client Driver works with Microsoft.NET. It can be used with any .NET testing framework like NUnit or the Visual Studio 2005 Team System. Selenium-IDE assumes you will use NUnit as your testing framework. You can see this in the generated code below. It includes the using statement for NUnit along with corresponding NUnit attributes identifying the role for each member function of the test class. You will probably have to rename the test class from NewTest to something of your own choosing. Also, you will need to change the browser-open parameters in the statement:
80
namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium; private StringBuilder verificationErrors; [SetUp] public void SetupTest() { selenium = new DefaultSelenium( "localhost" , 4444, "*iehta" , "http://www.google.com/" ); selenium.Start(); verificationErrors = new StringBuilder(); } [TearDown] public void TeardownTest() { try { selenium.Stop(); } catch (Exception) { // Ignore errors if unable to close the browser } Assert.AreEqual( "" , verificationErrors.ToString()); } [Test] public void TheNewTest() { // Open Google search engine. selenium.Open( "http://www.google.com/" ); // Assert Title of page. Assert.AreEqual( "Google" , selenium.GetTitle()); // Provide search term as "Selenium OpenQA" selenium.Type( "q" , "Selenium OpenQA" ); // Read the keyed search term and assert it. Assert.AreEqual( "Selenium OpenQA" , selenium.GetValue( "q" ));
81
// Click on Search button. selenium.Click( "btnG" ); // Wait for page to load. selenium.WaitForPageToLoad( "5000" ); // Assert that "www.openqa.org" is available in search results. Assert.IsTrue(selenium.IsTextPresent( "www.openqa.org" )); // Assert that page title is - "Selenium OpenQA - Google Search" Assert.AreEqual( "Selenium OpenQA - Google Search" , selenium.GetTitle()); } } }
You can allow NUnit to manage the execution of your tests. Or alternatively, you can write a simple main() program that instantiates the test object and runs each of the three methods, SetupTest(), TheNewTest(), and TeardownTest() in turn.
6.5.3 Python
Pyunit is the test framework to use for Python. To learn Pyunit refer to its ofcial documentation <http://docs.python.org/library/unittest.html>_. The basic test structure is:
from selenium import selenium # This is the drivers import. Youll use this class for instantiating a # browser and making it do what you need. import unittest, time, re # This are the basic imports added by Selenium-IDE by default. # You can remove the modules if they are not used in your script. class NewTest(unittest.TestCase): # We create our unittest test case def setUp(self): self.verificationErrors = [] # This is an empty array where we will store any verification errors # we find in our tests self.selenium = selenium( " localhost " , 4444, " *firefox " , " http://www.google.com/ " ) self.selenium.start() # We instantiate and start the browser def test_new(self): # This is the test code. Here you should put the actions you need # the browser to do during your test. sel = self.selenium # We assign the browser to the variable "sel" (just to save us from # typing "self.selenium" each time we want to call the browser).
82
sel.open( " / " ) sel.type( " q " , " selenium rc " ) sel.click( " btnG " ) sel.wait_for_page_to_load( " 30000 " ) self.failUnless(sel.is_text_present( " Results * for selenium rc " )) # These are the real test steps def tearDown(self): self.selenium.stop() # we close the browser (Id recommend you to comment this line while # you are creating and debugging your tests) self.assertEqual([], self.verificationErrors) # And make the test fail if we found that any verification errors # were found
6.5.4 Ruby
Selenium-IDE generates reasonable Ruby, but requires the old Selenium gem. This is a problem because the ofcial Ruby driver for Selenium is the Selenium-Client gem, not the old Selenium gem. In fact, the Selenium gem is no longer even under active development. Therefore, it is advisable to update any Ruby scripts generated by the IDE as follows: 1. On line 1, change require "selenium" to require "selenium/client" 2. On line 11, change Selenium::Client::Driver.new Selenium::SeleniumDriver.new to
You probably also want to change the class name to something more informative than Untitled, and change the test methods name to something other than test_untitled. Here is a simple example created by modifying the Ruby code generated by Selenium IDE, as described above.
# load the Selenium-Client gem require " selenium/client " # Load Test::Unit, Ruby 1.8s default test framework. # If you prefer RSpec, see the examples in the Selenium-Client # documentation. require " test/unit " class Untitled < Test::Unit::TestCase # The setup method is called before each test. def setup # This array is used to capture errors and display them at the # end of the test run. @verification_errors = [] # Create a new instance of the Selenium-Client driver. @selenium = Selenium::Client::Driver.new \ :host => " localhost " , :port => 4444,
83
:browser => " *chrome " , :url => " http://www.google.com/ " , :timeout_in_second => 60 # Start the browser session @selenium.start # Print a message in the browser-side log and status bar # (optional). @selenium.set_context( " test_untitled " ) end # The teardown method is called after each test. def teardown # Stop the browser session. @selenium.stop # Print the array of error messages, if any. assert_equal [], @verification_errors end # This is the main body of your test. def test_untitled # Open the root of the site we specified when we created the # new driver instance, above. @selenium.open " / " # Type selenium rc into the field named q @selenium.type " q " , " selenium rc " # Click the button named "btnG" @selenium.click " btnG " # Wait for the search results page to load. # Note that we dont need to set a timeout here, because that # was specified when we created the new driver instance, above. @selenium.wait_for_page_to_load begin # Test whether the search results contain the expected text. # Notice that the star (*) is a wildcard that matches any # number of characters. assert @selenium.is_text_present( " Results * for selenium rc " ) rescue Test::Unit::AssertionFailedError # If the assertion fails, push it onto the array of errors. @verification_errors << $! end end end
84
my $sel = Test::WWW::Selenium->new( host => "localhost" , port => 4444, browser => "*firefox" , browser_url => "http://www.google.com/" );
$this->setBrowser("*firefox"); $this->setBrowserUrl("http://www.google.com/");
self.selenium = selenium( " localhost " , 4444, " *firefox " , " http://www.google.com/ " ) self.selenium.start()
@selenium = Selenium::ClientDriver.new( " localhost " , 4444, " *firefox " , " http://www @selenium.start
Each of these examples opens the browser and represents that browser by assigning a browser instance to a program variable. This program variable is then used to call methods from the browser. These methods execute the Selenium commands, i.e. like open or type or the verify commands. The parameters required when creating the browser instance are: host Species the IP address of the computer where the server is located. Usually, this is the same machine as where the client is running, so in this case localhost is passed. In some clients this is an optional parameter. port Species the TCP/IP socket where the server is listening waiting for the client to establish a connection. This also is optional in some client drivers. 6.6. Learning the API 85
browser The browser in which you want to run the tests. This is a required parameter. url The base url of the application under test. This is required by all the client libs and is integral information for starting up the browser-proxy-AUT communication. Note that some of the client libraries require the browser to be started explicitly by calling its start() method.
to using a library or test framework. Regardless, after the initial, but short, learning curve you will naturally develop what works best for your own situation.
See TestNG-xslt for more. Logging the Selenese Commands Logging Selenium can be used to generate a report of all the Selenese commands in your test along with the success or failure of each. Logging Selenium extends the Java client driver to add this Selenese logging ability. Please refer to Logging Selenium. Test Reports for Python When using Python Client Driver then HTMLTestRunner can be used to generate a Test Report. See HTMLTestRunner.
87
Test Reports for Ruby If RSpec framework is used for writing Selenium Test Cases in Ruby then its HTML report can be used to generate a test report. Refer to RSpec Report for more. Note: If you are interested in a language independent log of whats going on, take a look at Selenium Server Logging
6.8.1 Iteration
Iteration is one of the most common things people need to do in their tests. For example, you may want to to execute a search multiple times. Or, perhaps for verifying your test results you need to process a result set returned from a database. Using the same Google search example we used earlier, lets check the Selenium search results. This test could use the Selenese: open type clickAndWait assertTextPresent type clickAndWait assertTextPresent type clickAndWait assertTextPresent / q btnG Results * for selenium rc q btnG Results * for selenium ide q btnG Results * for selenium grid selenium rc
selenium ide
selenium grid
The code has been repeated to run the same steps 3 times. But multiple copies of the same code is not good program practice because its more work to maintain. By using a programming language, we can iterate over the search results for a more exible and maintainable solution. In C#: 88 Chapter 6. Selenium 1 (Selenium RC)
// Collection of String values. String[] arr = { "ide" , "rc" , "grid" }; // Execute loop for each String in array arr. foreach (String s in arr) { sel.open( "/" ); sel.type( "q" , "selenium " +s); sel.click( "btnG" ); sel.waitForPageToLoad( "30000" ); assertTrue( "Expected text: " +s+ " is missing on page." , sel.isTextPresent( "Results * for selenium " + s)); }
This can cause your test to abort. For some tests thats what you want. But often that is not desirable as your test script has many other subsequent tests to perform. A better approach is to rst validate if the element is really present and then take alternatives when it it is not. Lets look at this using Java.
// If element is available on page then perform type operation. if(selenium.isElementPresent( "q" )) { selenium.type( "q" , "Selenium rc" ); } else { System.out.printf( "Element: " +q+ " is not available on page." ) }
The advantage of this approach is to continue with test execution even if some UI elements are not available on page.
89
public static String[] getAllCheckboxIds () { String script = "var inputId = new Array();" ;// Create array in java scri script += "var cnt = 0;" ; // Counter for check box ids. script += "var inputFields = new Array();" ; // Create array in java scrip script += "inputFields = window.document.getElementsByTagName(input);" ; script += "for(var i=0; i<inputFields.length; i++) {" ; // Loop through the script += "if(inputFields[i].id !=null " + "&& inputFields[i].id !=undefined " + "&& inputFields[i].getAttribute(type) == checkbox) {" ; // If input fie script += "inputId[cnt]=inputFields[i].id ;" + // Save check box id to inp "cnt++;" + // increment the counter. "}" + // end of if. "}" ; // end of for. script += "inputId.toString();" ;// Convert array in to string. String[] checkboxIds = selenium.getEval(script).split( "," ); // Split the s return checkboxIds; }
Remember to use window object in case of DOM expressions as by default selenium window is referred to, not the test window.
To see the list of options, run the server with the -h option.
$ java -jar selenium-server-standalone-<version-number> -h
Youll see a list of all the options you can use with the server and a brief description of each. The provided descriptions will not always be enough, so weve provided explanations for some of the more important options.
90
Some applications didnt run correctly in a sub frame, and needed to be loaded into the top frame of the window. The multi-window mode option allowed the AUT to run in a separate window rather than in the default frame where it could then have the top frame it required.
91
For older versions of Selenium you must specify multiwindow mode explicitly with the following option:
-multiwindow
As of Selenium RC 1.0, if you want to run your test within a single frame (i.e. using the standard for earlier Selenium versions) you can state this to the Selenium Server using the option
-singlewindow
92
firefox.exe -P
Create the new prole using the dialog. Then when you run Selenium Server, tell it to use this new Firefox prole with the server command-line option -refoxProleTemplate and specify the path to the prole using its lename and directory path.
-firefoxProfileTemplate "path to the profile"
Warning: Be sure to put your prole in a new folder separate from the default!!! The Firefox prole manager tool will delete all les in a folder if you delete a prole, regardless of whether they are prole les or not. More information about Firefox proles can be found in Mozillas Knowledge Base
This will automatically launch your HTML suite, run all the tests and save a nice HTML report with the results. Note: When using this option, the server will start the tests and wait for a specied number of seconds for the test to complete; if the test doesnt complete within that amount of time, the command will exit with a non-zero exit code and no results le will be generated. This command line is very long so be careful when you type it. Note this requires you to pass in an HTML Selenese suite, not a single test. Also be aware the -htmlSuite option is incompatible with -interactive You cannot run both at the same time.
This log le is more verbose than the standard console logs (it includes DEBUG level logging messages). The log le also includes the logger name, and the ID number of the thread that logged the message. For example:
20:44:25 DEBUG [12] org.openqa.selenium.server.SeleniumDriverResourceHandler Browser 465828/:top frame1 posted START NEW
93
This message may be multiline. Browser-Side Logs JavaScript on the browser side (Selenium Core) also logs important messages; in many cases, these can be more useful to the end-user than the regular Selenium Server logs. To access browser-side logs, pass the -browserSideLog argument to the Selenium Server.
java -jar selenium-server-standalone-<version-number>.jar -browserSideLog
-browserSideLog must be combined with the -log argument, to log browserSideLogs (as well as all other DEBUG level logging messages) to a le.
94
Historically, Selenium-Core was limited by this problem since it was implemented in JavaScript. Selenium RC is not, however, restricted by the Same Origin Policy. Its use of the Selenium Server as a proxy avoids this problem. It, essentially, tells the browser that the browser is working on a single spoofed website that the Server provides. Note: You can nd additional information about this topic on Wikipedia pages about Same Origin Policy and XSS.
95
As a test suite starts in your favorite language, the following happens: 1. The client/driver establishes a connection with the selenium-RC server. 2. Selenium RC server launches a browser (or reuses an old one) with a URL that injects SeleniumCores JavaScript into the browser-loaded web page. 3. The client-driver passes a Selenese command to the server. 4. The Server interprets the command and then triggers the corresponding JavaScript execution to execute that command within the browser. 5. Selenium-Core instructs the browser to act on that rst instruction, typically opening a page of the AUT. 6. The browser receives the open request and asks for the websites content from the Selenium RC server (set as the HTTP proxy for the browser to use). 7. Selenium RC server communicates with the Web server asking for the page and once it receives it, it sends the page to the browser masking the origin to look like the page comes from the same server as Selenium-Core (this allows Selenium-Core to comply with the Same Origin Policy). 96 Chapter 6. Selenium 1 (Selenium RC)
8. The browser receives the web page and renders it in the frame/window reserved for it.
As a test suite starts in your favorite language, the following happens: 1. The client/driver establishes a connection with the selenium-RC server. 2. Selenium RC server launches a browser (or reuses an old one) with a URL that will load SeleniumCore in the web page. 3. Selenium-Core gets the rst instruction from the client/driver (via another HTTP request made to the Selenium RC Server). 6.11. Selenium RC Architecture 97
4. Selenium-Core acts on that rst instruction, typically opening a page of the AUT. 5. The browser receives the open request and asks the Web Server for the page. Once the browser receives the web page, renders it in the frame/window reserved for it.
98
Note that when launching the browser this way, you must manually congure the browser to use the Selenium Server as a proxy. Normally this just means opening your browser preferences and specifying localhost:4444 as an HTTP proxy, but instructions for this can differ radically from browser to browser. Consult your browsers documentation for details. Be aware that Mozilla browsers can vary in how they start and stop. One may need to set the MOZ_NO_REMOTE environment variable to make Mozilla browsers behave a little more predictably. Unix users should avoid launching the browser using a shell script; its generally better to use the binary executable (e.g. refox-bin) directly.
99
If you see a message like this, be sure you started the Selenium Server. If so, then there is a problem with the connectivity between the Selenium Client Library and the Selenium Server. When starting with Selenium RC, most people begin by running thier test program (with a Selenium Client Library) and the Selenium Server on the same machine. To do this use localhost as your connection parameter. We recommend beginning this way since it reduces the inuence of potential networking problems which youre getting started. Assuming your operating system has typical networking and TCP/IP settings you should have little difculty. In truth, many people choose to run the tests this way. If, however, you do want to run Selenium Server on a remote machine, the connectivity should be ne assuming you have valid TCP/IP connectivity between the two machines. If you have difculty connecting, you can use common networking tools like ping, telnet, ifcong(Unix)/ipcong (Windows), etc to ensure you have a valid network connection. If unfamilar with these, your system administrator can assist you.
This could be caused by Firefox (prior to Selenium 1.0) cannot start because the browser is already open and you did not specify a separate prole. See the section on Firefox proles under Server Options. The run mode youre using doesnt match any browser on your machine. Check the parameters you passed to Selenium when you program opens the browser. You specied the path to the browser explicitly (using *customsee above) but the path is incorrect. Check to be sure the path is correct. Also check the user group to be sure there are no known issues with your browser and the *custom parameters.
100
6.14.6 Error message: (Unsupported major.minor version 49.0) while starting server
This error says youre not using a correct version of Java. The Selenium Server requires Java 1.5 or higher. To check double-check your java version, run this from the command line.
java -version
If you see a lower version number, you may need to update the JRE, or you may simply need to add it to your PATH environment variable.
global proxy settings in the Internet Options Control Panel. You must make sure that those are correctly congured when Selenium Server launches the browser. Try looking at your Internet Options control panel. Click on the Connections tab and click on LAN Settings. If you need to use a proxy to access the application you want to test, youll need to start Selenium Server with -Dhttp.proxyHost; see the Proxy Conguration for more details. You may also try conguring your proxy manually and then launching the browser with *custom, or with *iehta browser launcher. *custom: When using *custom you must congure the proxy correctly(manually), otherwise youll get a 404 error. Double-check that youve congured your proxy settings correctly. To check whether youve congured the proxy correctly is to attempt to intentionally congure the browser incorrectly. Try conguring the browser to use the wrong proxy server hostname, or the wrong port. If you had successfully congured the browsers proxy settings incorrectly, then the browser will be unable to connect to the Internet, which is one way to make sure that one is adjusting the relevant settings. For other browsers (*refox, *opera) we automatically hard-code the proxy for you, and so ther are no known issues with this functionality. If youre encountering 404 errors and have followed this user guide carefully post your results to user group for some help from the user community.
correctly, you should never see SSL certicate warnings, but you may need to congure your browser to trust our dangerous CyberVillains SSL certicate authority. Again, refer to the HTTPS section for how to do this. modal JavaScript alert/conrmation/prompt dialogs: Selenium tries to conceal those dialogs from you (by replacing window.alert, window.conrm and window.prompt) so they wont stop the execution of your page. If youre seeing an alert pop-up, its probably because it red during the page load process, which is usually too early for us to protect the page. Selenese contains commands for asserting or verifying alert and conrmation popups. See the sections on these topics in Chapter 4.
cmd=getNewBrowserSession&1=*firefox /usr/local/firefox/firefox-bin&2=http://www.google.c
6.14.12 Is it ok to load a custom pop-up as the parent page is loading (i.e., before the parent pages javascript window.onload() function runs)?
No. Selenium relies on interceptors to determine window names as they are being loaded. These interceptors work best in catching new windows if the windows are loaded AFTER the onload() function. Selenium may not recognize windows loaded before the onload function.
/usr/lib/firefox-x.x.x/
Where the x.x.x is the version number you currently have. So, to add that path to the users path. you will have to add the following to your .bashrc le:
export PATH= "$PATH:/usr/lib/firefox-x.x.x/"
If necessary, you can specify the path to refox-bin directly in your test, like this:
"*firefox /usr/lib/firefox-x.x.x/firefox-bin"
This would work perfectly in Firefox, Opera or Safari but not with IE. IE interprets the keys in @style as uppercase. So, even if the source code is in lowercase, you should use:
//td[@style= "BACKGROUND-COLOR:yellow" ]
This is a problem if your test is intended to work on multiple browsers, but you can easily code your test to detect the situation and try the alternative locator that only works in IE.
6.14.17 Error encountered - Cannot convert object to primitive value with shut down of *googlechrome browser
To avoid this error you have to start browser with an option that disables same origin policy checks:
selenium.start( "commandLineFlags=--disable-web-security" );
104
CHAPTER
SEVEN
105
This shows an HTML tag for a check box. Its ID (addForm:_ID74:_ID75:0:_ID79:0:checkBox) is a dynamically generated value. The next time the same page is opened it will likely be a different value.
106
107
This HTML anchor tag denes a button with an ID attribute of adminHomeForm. Its a fairly complex anchor tag when compared to most HTML tags, but it is still a static tag. The HTML will be the same each time this page is loaded in the browser. Its ID remains constant with all instances of this page. That is, when this page is displayed, this UI element will always have this Identier. So, for your test script to click this button you simply need to use the following selenium command.
click adminHomeForm
selenium.click( "adminHomeForm" );
Your application, however, may generate HTML dynamically where the identier varies on different instances of the webpage. For instance, HTML for a dynamic page element might look like this.
<input type= "checkbox" value= "true" id= "addForm:_ID74:_ID75:0:_ID79:0:checkBox" name= "addForm:_ID74:_ID75:0:_ID79:0:checkBox" />
This denes a checkbox. Its ID and name attributes (both addForm:_ID74:_ID75:0:_ID79:0:checkBox) are dynamically generated values. In this case, using a standard locator would look something like the following.
click addForm:_ID74:_ID75:0:_ID79:0:checkBox
Given the dynamically generated Identier, this approach would not work. The next time this page is loaded the Identier will be a different value from the one used in the Selenium command and therefore, will not be found. The click operation will fail with an element not found error. To correct this, a simple solution would be to just use an XPath locator rather than trying to use an ID locator. So, for the checkbox you can simply use
click //input
Or, if it is not the rst input element on the page (which it likely is not) try a more detailed XPath statement.
click //input[3]
Or
click //div/p[2]/input[3]
If however, you do need to use the ID to locate the element, a different solution is needed. You can capture this ID from the website before you use it in a Selenium command. It can be done like this.
String[] checkboxids = selenium.getAllFields(); // Collect all input IDs on page. for(String checkboxid:checkboxids) { if(checkboxid.contains( "addForm" )) { selenium.click(expectedText); } }
This approach will work if there is only one check box whose ID has the text expectedText appended to it.
109
// Search for element "link=ajaxLink" and if available then break loop. try { if (selenium.isElementPresent( "link=ajaxLink" )) break; } catch (Exception e) // Pause for 1 second. Thread.sleep(1000); }
This certainly isnt the only solution. Ajax is a common topic in the user forum and we recommend searching previous discussions to see what others have done.
Instead of duplicating this code you could write a wrapper method that performs both functions.
/** * Clicks and Waits for page to load. * * param elementLocator * param waitPeriod */
110
/** * Selenum-RC -- Clicks on element only if it is available on page. * * param elementLocator */ public void safeClick(String elementLocator) { if(selenium.isElementPresent(elementLocator)) { selenium.click(elementLocator); } else { // Using the TestNG API for logging Reporter.log( "Element: " +elementLocator+ ", is not available on page +selenium.getLocation()); } }
This example uses the Selenium 1 API but Selenium 2 also supports this.
/** * Selenium-WebDriver -- Clicks on element only if it is available on page. * * param elementLocator */ public void safeClick(String elementLocator) { WebElement webElement = getDriver().findElement(By.XXXX(elementLocator)); if(webElement != null) { selenium.click(elementLocator); } else { // Using the TestNG API for logging Reporter.log( "Element: " +elementLocator+ ", is not available on page + getDriver().getUrl()); } }
In this second example XXXX is simply a placeholder for one of the multiple location methods that can be called here. Using safe methods is up to the test developers discretion. Hence, if test execution is to be continued, even in the wake of missing elements on the page, then safe methods could be used, while posting a message to a log about the missing element. This, essentially, implements a verify with a reporting mechanism as opposed to an abortive assert. But if element must be available on page in order to be able to carry out further operations (i.e. login button on home page of a portal) then this safe method technique should not be used. 7.5. Wrapping Selenium Calls 111
7.6 UI Mapping
A UI map is a mechanism that stores all the locators for a test suite in one place for easy modication when identiers or paths to UI elements change in the AUT. The test script then uses the UI Map for locating the elements to be tested. Basically, a UI map is a repository of test script objects that correspond to UI elements of the application being tested. What makes a UI map helpful? Its primary purpose for making test script management much easier. When a locator needs to be edited, there is a central location for easily nding that object, rather than having to search through test script code. Also, it allows changing the Identier in a single place, rather than having to make the change in multiple places within a test script, or for that matter, in multiple test scripts. To summarize, a UI map has two signicant advantages. Using a centralized location for UI objects instead of having them scattered throughout the script. This makes script maintenance more efcient. Cryptic HTML Identiers and names can be given more human-readable names improving the readability of test scripts. Consider the following, difcult to understand, example (in java).
public void testNew() throws Exception { selenium.open( "http://www.test.com" ); selenium.type( "loginForm:tbUsername" , "xxxxxxxx" ); selenium.click( "loginForm:btnLogin" ); selenium.click( "adminHomeForm:_activitynew" ); selenium.waitForPageToLoad( "30000" ); selenium.click( "addEditEventForm:_IDcancel" ); selenium.waitForPageToLoad( "30000" ); selenium.click( "adminHomeForm:_activityold" ); selenium.waitForPageToLoad( "30000" ); }
This script would be hard to follow for anyone not familiar with the AUTs page source. Even regular users of the application might have difculty understanding what thus script does. A better script could be:
public void testNew() throws Exception { selenium.open( "http://www.test.com" ); selenium.type(admin.username, "xxxxxxxx" ); selenium.click(admin.loginbutton); selenium.click(admin.events.createnewevent); selenium.waitForPageToLoad( "30000" ); selenium.click(admin.events.cancel); selenium.waitForPageToLoad( "30000" ); selenium.click(admin.events.viewoldevents); selenium.waitForPageToLoad( "30000" ); }
Now, using some comments and whitespace along with the UI Map identiers makes a very readable script. 112 Chapter 7. Test Design Considerations
public void testNew() throws Exception { // Open app url. selenium.open( "http://www.test.com" ); // Provide admin username. selenium.type(admin.username, "xxxxxxxx" ); // Click on Login button. selenium.click(admin.loginbutton); // Click on Create New Event button. selenium.click(admin.events.createnewevent); selenium.waitForPageToLoad( "30000" ); // Click on Cancel button. selenium.click(admin.events.cancel); selenium.waitForPageToLoad( "30000" ); // Click on View Old Events button. selenium.click(admin.events.viewoldevents); selenium.waitForPageToLoad( "30000" ); }
There are various ways a UI Map can be implemented. One could create a class or struct which only stores public String variables each storing a locator. Alternatively, a text le storing key value pairs could be used. In Java, a properties le containing key/value pairs is probably best method. Consider a property le prop.properties which assigns as aliases reader-friendly identiers for UI elements from the previous example.
admin.username = loginForm:tbUsername admin.loginbutton = loginForm:btnLogin admin.events.createnewevent = adminHomeForm:_activitynew admin.events.cancel = addEditEventForm:_IDcancel admin.events.viewoldevents = adminHomeForm:_activityold
The locators will still refer to html objects, but we have introduced a layer of abstraction between the test script and the UI elements. Values are read from the properties le and used in the Test Class to implement the UI Map. For more on Java properties les refer to the following link.
2. There is single repository for the services or operations offered by the page rather than having these services scattered through out the tests. In both cases this allows any modications required due to UI changes to all be made in one place. Useful information on this technique can be found on numerous blogs as this test design pattern is becoming widely used. We encourage the reader who wishes to know more to search the internet for blogs on this subject. Many have written on this design pattern and can provide useful tips beyond the scope of this user guide. To get you started, though, well illustrate page objects with a simple example. First, consider an example, typical of test automation, that does not use a page object.
/*** * Tests login feature */ public class Login { public void testLogin() { selenium.type( "inputBox" , "testUser" ); selenium.type( "password" , "my supersecret password" ); selenium.click( "sign-in" ); selenium.waitForPageToLoad( "PageWaitPeriod" ); Assert.assertTrue(selenium.isElementPresent( "compose button" ), "Login was unsuccessful" ); } }
There are two problems with this approach. 1. There is no separation between the test method and the AUTs locators (IDs in this example); both are intertwined in a single method. If the AUTs UI changes its identiers, layout, or how a login is input and processed, the test itself must change. 2. The id-locators would be spread in multiple tests, all tests that had to use this login page. Applying the page object techniques this example could be rewritten like this in the following example of a page object for a Sign-in page.
/** * Page Object encapsulates the Sign-in page. */ public class SignInPage { private Selenium selenium;
public SignInPage(Selenium selenium) { this.selenium = selenium; if(!selenium.getTitle().equals( "Sign in page" )) { throw new IllegalStateException( "This is not sign in page, curre +selenium.getLocation()); } } /** * Login as valid user *
114
* @param userName * @param password * @return HomePage object */ public HomePage loginValidUser(String userName, String password) { selenium.type( "usernamefield" , userName); selenium.type( "passwordfield" , password); selenium.click( "sign-in" ); selenium.waitForPageToLoad( "waitPeriod" ); return new HomePage(selenium); } }
and page object for a Home page could look like this.
/** * Page Object encapsulates the Home Page */ public class HomePage { private Selenium selenium;
public HomePage(Selenium selenium) { if (!selenium.getTitle().equals( "Home Page of logged in user" )) { throw new IllegalStateException( "This is not Home Page of logged "is: " +selenium.getLocation()); } } public HomePage manageProfile() { // Page encapsulation to manage profile functionality return new HomePage(selenium); }
/*More methods offering the services represented by Home Page of Logged User. These methods in turn might return more Page Objects for example click on Compose mail button could return ComposeMail class object*/ }
So now, the login test would use these two page objects as follows.
/*** * Tests login feature */ public class TestLogin {
public void testLogin() { SignInPage signInPage = new SignInPage(selenium); HomePage homePage = signInPage.loginValidUser( "userName" , "password" ); Assert.assertTrue(selenium.isElementPresent( "compose button" ), "Login was unsuccessful" ); } }
115
There is a lot of exibility in how the page objects may be designed, but there are a few basic rules for getting the desired maintainability of your test code. Page objects themselves should never be make verications or assertions. This is part of your test and should always be within the tests code, never in an page object. The page object will contain the representation of the page, and the services the page provides via methods but no code related to what is being tested should be within the page object. There is one, single, verication which can, and should, be within the page object and that is to verify that the page, and possibly critical elements on the page, were loaded correctly. This verication should be done while instantiating the page object. In the examples above, both the SignInPage and HomePage constructors check that the expected page is available and ready for requests from the test. A page object does not necessarily need to represent an entire page. The Page Object design pattern could be used to represent components on a page. If a page in the AUT has multiple components, it may improved maintainability if there was a separate page object for each component. There are other design patterns that also may be used in testing. Some use a Page Factory for instantiating their page objects. Discussing all of these is beyond the scope of this user guide. Here, we merely want to introduce the concepts to make the reader aware of some of the things that can be done. As was mentioned earlier, many have blogged on this topic and we encourage the reader to search for blogs on these topics.
" + search))
The Python script above opens a text le. This le contains a different search string on each line. The code then saves this in an array of strings, and iterates over the array doing a search and assert on each string. This is a very basic example, but the idea is to show that running a test with varying data can be done easily with a programming or scripting language. For more examples, refer to the Selenium RC wiki for examples of reading data from a spreadsheet or for using the data provider capabilities of TestNG. Additionally, this is a well-known topic among test automation professionals including those who dont use Selenium so searching the internet on data-driven testing should reveal many blogs on this topic. 116 Chapter 7. Test Design Considerations
117
118
CHAPTER
EIGHT
SELENIUM-GRID
Please refer to the Selenium Grid website http://selenium-grid.seleniumhq.org/how_it_works.html This section is not yet developed. If there is a member of the community who is experienced in SeleniumGrid, and would like to contribute, please contact the Documentation Team. We would love to have you contribute.
119
120
Chapter 8. Selenium-Grid
CHAPTER
NINE
USER-EXTENSIONS
NOTE: This section is close to completion, but it has not been reviewed and edited.
9.1 Introduction
It can be quite simple to extend Selenium, adding your own actions, assertions and locator-strategies. This is done with JavaScript by adding methods to the Selenium object prototype, and the PageBot object prototype. On startup, Selenium will automatically look through methods on these prototypes, using name patterns to recognize which ones are actions, assertions and locators. The following examples give an indication of how Selenium can be extended with JavaScript.
9.2 Actions
All methods on the Selenium prototype beginning with do are added as actions. For each action foo there is also an action fooAndWait registered. An action method can take up to two parameters, which will be passed the second and third column values in the test. Example: Add a typeRepeated action to Selenium, which types the text twice into a text box.
Selenium.prototype.doTypeRepeated = function(locator, text) { // All locator-strategies are automatically handled by "findElement" var element = this.page().findElement(locator); // Create the text to type var valueToType = text + text; // Replace the element text with the new text this.page().replaceText(element, valueToType); };
9.3 Accessors/Assertions
All getFoo and isFoo methods on the Selenium prototype are added as accessors (storeFoo). For each accessor there is an assertFoo, verifyFoo and waitForFoo registered. An assert method can take up to 2 parameters, which will be passed the second and third column values in the test. You can also dene your own assertions literally as simple assert methods, which will also auto-generate verify and waitFor commands. Example: Add a valueRepeated assertion, that makes sure that the element
121
value consists of the supplied text repeated. The 2 commands that would be available in tests would be assertValueRepeated and verifyValueRepeated.
Selenium.prototype.assertValueRepeated = function(locator, text) { // All locator-strategies are automatically handled by "findElement" var element = this.page().findElement(locator); // Create the text to verify var expectedValue = text + text; // Get the actual element value var actualValue = element.value; // Make sure the actual value matches the expected Assert.matches(expectedValue, actualValue); };
9.3.1 Automatic availability of storeFoo, assertFoo, assertNotFoo, waitForFoo and waitForNotFoo for every getFoo
All getFoo and isFoo methods on the Selenium prototype automatically result in the availability of storeFoo, assertFoo, assertNotFoo, verifyFoo, verifyNotFoo, waitForFoo, and waitForNotFoo commands. Example, if you add a getTextLength() method, the following commands will automatically be available: storeTextLength, assertTextLength, assertNotTextLength, verifyTextLength, verifyNotTextLength, waitForTextLength, and waitForNotTextLength commands.
Selenium.prototype.getTextLength = function(locator, text) { return this.getText(locator).length; };
Also note that the assertValueRepeated method described above could have been implemented using isValueRepeated, with the added benet of also automatically getting assertNotValueRepeated, storeValueRepeated, waitForValueRepeated and waitForNotValueRepeated.
122
Chapter 9. User-Extensions
9.6.1 Example
C# 1. Place your user extension in the same directory as your Selenium Server. 2. If you are using client code generated by the Selenium-IDE you will need to make a couple small edits. First, you will need to create an HttpCommandProcessor object with class scope (outside the SetupTest method, just below private StringBuilder verificationErrors;)
HttpCommandProcessor proc;
1. Next, instantiate that HttpCommandProcessor object DefaultSelenium object. This can be done in the test setup.
as
you
would
the
123
1. Instantiate the DefaultSelenium object using the HttpCommandProcessor object you created.
selenium = new DefaultSelenium(proc);
1. Within your test code, execute your user-extension by calling it with the DoCommand() method of HttpCommandProcessor. This method takes two arguments: a string to identify the userextension method you want to use and string array to pass arguments. Notice that the rst letter of your function is lower case, regardless of the capitalization in your user-extension. Selenium automatically does this to keep common JavaScript naming conventions. Because JavaScript is case sensitive, your test will fail if you begin this command with a capital. inputParams is the array of arguments you want to pass to the JavaScript user-extension. In this case there is only one string in the array because there is only one parameter for our user extension, but a longer array will map each index to the corresponding user-extension parameter. Remember that user extensions designed for Selenium-IDE will only take two arguments.
string[] inputParams = { "Hello World" }; proc.DoCommand( "alertWrapper" , inputParams);
1. Start the test server using the -userExtensions argument and pass in your user-extensinos.js le.
java -jar selenium-server.jar -userExtensions user-extensions.js
namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium; private StringBuilder verificationErrors; private HttpCommandProcessor proc;
[SetUp] public void SetupTest() { proc = new HttpCommandProcessor( "localhost" , 4444, "*iexplore" selenium = new DefaultSelenium(proc); //selenium = new DefaultSelenium("localhost", 4444, "*iexplore", selenium.Start(); verificationErrors = new StringBuilder(); }
124
Chapter 9. User-Extensions
[TearDown] public void TeardownTest() { try { selenium.Stop(); } catch (Exception) { // Ignore errors if unable to close the browser } Assert.AreEqual( "" , verificationErrors.ToString()); } [Test] public void TheNewTest() { selenium.Open( "/" ); string[] inputParams = { "Hello World" ,}; proc.DoCommand( "alertWrapper" , inputParams); } } }
Appendixes:
125
126
Chapter 9. User-Extensions
CHAPTER
TEN
127
128
CHAPTER
ELEVEN
Select Visual C# > Class Library > Name your project > Click on OK button.
129
Under right hand pane of Solution Explorer right click on References > Add References.
130
Select following dll les - nmock.dll, nunit.core.dll, nunit.framework.dll,ThoughtWorks. Selenium.Core.dll, ThoughtWorks.Selenium.IntegrationTests.dll, ThoughtWorks.Selenium.UnitTests.dll and click on Ok button
131
132
CHAPTER
TWELVE
From the New Project dialog select Import Project from External Model.
133
Now you will see a dialog allowing you to set project options including the projects root directory.
134
Now the settings dialog will show the directory you just selected.
135
This next dialog shows the name of your maven project as specied in the pom.xml le. Select your maven project and continue.
136
Once your project has been imported it should look like this in IntelliJ.
The maven project download many dependencies (libraries) when you originally ran mvn install. Now in IntelliJ you can see all these libraries. These next two screen captures shows the libraries you should now have in your project.
137
Before you can start writing Selenium code, you still need to create a module and at least one Java class (a .java le). First select the Projects root in IntelliJ and right click.
138
In the dialog select the radio button Create Module From Scratch.
139
Select Java Module and enter a name for the new module.
140
And next, you must create a folder for the source code. By convention this is almost always named src.
141
Now were on the last dialog. Typically you dont need to select any technollogies here. Unless you know for a fact you will be using Groovy or some other technology.
142
Now that the module is created, your project should show the following structure.
143
The .java le should now be created. It should look like this in your project.
144
If your project now looks like the one displayed above, youre done, congrats! And hope you enjoy coding your rst Selenium automation!
145
146
CHAPTER
THIRTEEN
147
148
Provide Name to your project, Select JDK in Use a project Specic JRE option (JDK 1.5 selected in this example) > click Next
149
Keep JAVA Settings intact in next window. Project specic libraries can be added here. (This described in detail in later part of document.)
150
Click Finish > Click on Yes in Open Associated Perspective pop up window.
151
152
153
Name this folder as com and click on Finish button. This should get com package insider src folder.
154
155
SelTestCase class can be kept inside core package. Create one more package inside src folder named testscripts. This is a place holder for test scripts. Please notice this is about the organization of project and it entirely depends on individuals choice / organizations standards. Test scripts package can further be segregated depending upon the project requirements.
156
Create a folder called lib inside project Google. Right click on Project name > New > Folder. This is a place holder for jar les to project (i.e. Selenium client driver, selenium server etc)
157
158
Right click on lib folder > Build Path > Congure build Path
159
Under Library tab click on Add External Jars to navigate to directory where jar les are saved. Select the jar les which are to be added and click on Open button.
160
161
162
163
164
CHAPTER
FOURTEEN
165
Mac The latest Mac OS X version (Leopard at this time) comes with Python pre-installed. To install an extra Python, get a universal binary at http://www.pythonmac.org/ (packages for Python 2.5.x). 166 Chapter 14. Python Client Driver Conguration
You will get a .dmg le that you can mount. It contains a .pkg le that you can launch.
Installing the Selenium driver client for python 1. Download the last version of Selenium Remote Control from the downloads page 2. Extract the content of the downloaded zip le 3. Copy the module with the Seleniums driver for Python (selenium.py) in the folder C:/Python25/Lib (this will allow you to import it directly in any script you write). You will nd the module in the extracted folder, its located inside seleniumpython-driver-client.
Congratulations, youre done! Now any python script that you create can import selenium and start interacting with the browsers.
167
168
CHAPTER
FIFTEEN
LOCATING TECHNIQUES
15.1 Useful XPATH patterns
15.1.1 text
Not yet written - locate elements based on the text content of the node.
15.1.2 starts-with
Many sites use dynamic values for elements id attributes, which can make them difcult to locate. One simple solution is to use XPath functions and base the location on what you do know about the element. For example, if your dynamic ids have the format <input id="text-12345" /> where 12345 is a dynamic number you could use the following XPath: //input[starts-with(@id, text-)]
15.1.3 contains
If an element can be located by a value that could be surrounded by other text, the contains function can be used. To demonstrate, the element <span class="top heading bold"> can be located based on the heading class without having to couple it with the top and bold classes using the following XPath: //span[contains(@class, heading)]. Incidentally, this would be much neater (and probably faster) using the CSS locator strategy css=span.heading
15.1.4 siblings
Not yet written - locate elements based on their siblings. Useful for forms and tables.
169
CSS: css=div.article-heading
170
CHAPTER
SIXTEEN
171
Once youve done this, run your existing tests. This will give you a fair idea of how much work needs to be done. The Selenium emulation is good, but its not completely perfect, so its completely normal for there to be some bumps and hiccups.
This allows you to continue passing the Selenium instance around as normal, but to unwrap the WebDriver instance as required. At some point, youre codebase will mostly be using the newer APIs. At this point, you can ip the relationship, using WebDriver throughout and instantiating a Selenium instance on demand:
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
172
This relies on the fact that type simply replaces the content of the identied element without also ring all the events that would normally be red if a user interacts with the page. The nal direct invocations of key* cause the JS handlers to re as expected. When using the WebDriverBackedSelenium, the result of lling in the form eld would be exciting texttt: not what youd expect! The reason for this is that WebDriver more accurately emulates user behavior, and so will have been ring events all along. This same fact may sometimes cause a page load to re earlier than it would do in a Selenium 1 test. You can tell that this has happened if a StaleElementException is thrown by WebDriver.
This may look complex, but its almost all boiler-plate code. The only interesting bit is that the ExpectedCondition will be evaluated repeatedly until the apply method returns something that is neither null nor Boolean.FALSE.
173
Of course, adding all these wait calls may clutter up your code. If thats the case, and your needs are simple, consider using the implicit waits:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
By doing this, every time an element is located, if the element is not present, the location is retried until either it is present, or until 30 seconds have passed.
16.6.3 Finding By XPath or CSS Selectors Doesnt Always Work, But It Does In Selenium 1
In Selenium 1, it was common for xpath to use a bundled library rather than the capabilities of the browser itself. WebDriver will always use the native browser methods unless theres no alternative. That means that complex xpath expressions may break on some browsers. CSS Selectors in Selenium 1 were implemented using the Sizzle library. This implements a superset of the CSS Selector spec, and its not always clear where youve crossed the line. If youre using the WebDriverBackedSelenium and use a Sizzle locator instead of a CSS Selector for nding elements, a warning will be logged to the console. Its worth taking the time to look for these, particularly if tests are failing because of not being able to nd elements.
becomes:
WebElement element = driver.findElement(By.id( "foo" )); String name = (String) ((JavascriptExecutor) driver).executeScript( "return arguments[0].tagName" , element);
Notice how the passed in element variable appears as the rst item in the JS standard arguments array.
174
becomes:
((JavascriptExecutor) driver).executeScript( "return window.title;" );
175