Selenium Documentation
Selenium Documentation
Release 1.0
Selenium Project
CONTENTS
1 2
Note to the Reader Introducing Selenium 2.1 To Automate or Not to Automate? That is the Question! 2.2 Test Automation for Web Applications . . . . . . . . . 2.3 Introducing Selenium . . . . . . . . . . . . . . . . . . 2.4 Selenium Components . . . . . . . . . . . . . . . . . . 2.5 Supported Browsers . . . . . . . . . . . . . . . . . . . 2.6 Flexibility and Extensibility . . . . . . . . . . . . . . . 2.7 About this Book . . . . . . . . . . . . . . . . . . . . . 2.8 The Documentation Team . . . . . . . . . . . . . . . . Selenium Basics 3.1 Getting Started Choosing Your Selenium Tool 3.2 Introducing Selenium Commands . . . . . . . . 3.3 Test Suites . . . . . . . . . . . . . . . . . . . . 3.4 Commonly Used Selenium Commands . . . . . 3.5 Summary . . . . . . . . . . . . . . . . . . . . .
3 5 5 5 6 6 7 8 8 9 11 11 11 13 14 14 15 15 15 18 18 21 24 24 25 27 28 29 29 29
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
Selenium-IDE 4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Installing the IDE . . . . . . . . . . . . . . . . . . . . . 4.3 Opening the IDE . . . . . . . . . . . . . . . . . . . . . . 4.4 IDE Features . . . . . . . . . . . . . . . . . . . . . . . . 4.5 Building Test Cases . . . . . . . . . . . . . . . . . . . . 4.6 Running Test Cases . . . . . . . . . . . . . . . . . . . . 4.7 Using Base URL to Run Test Cases in Different Domains 4.8 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . 4.9 Writing a Test Suite . . . . . . . . . . . . . . . . . . . . 4.10 User Extensions . . . . . . . . . . . . . . . . . . . . . . 4.11 Format . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.12 Executing Selenium-IDE Tests on Different Browsers . . 4.13 Troubleshooting . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
Selenium Commands 35 5.1 Verifying Page Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 5.2 Locating Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 5.3 Matching Text Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
The AndWait Commands . . . . . . . . . . The waitFor Commands in AJAX applications Sequence of Evaluation and Flow Control . . . Store Commands and Selenium Variables . . . JavaScript and Selenese Parameters . . . . . . echo - The Selenese Print Command . . . . . . Alerts, Popups, and Multiple Windows . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
44 44 44 45 46 47 47 51 51 51 53 56 59 65 67 68 71 75 75 79 80 80 87 87 87 89 90 93 93 95 96 99 101 101 101 101 102 103 103 107 107 108 108 110 114 118 119
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 What to Test? . . . . . . . . . 7.3 Verifying Results . . . . . . . 7.4 Choosing a Location Strategy 7.5 Testing Ajax Applications . . 7.6 UI Mapping . . . . . . . . . 7.7 Bitmap Comparison . . . . . 7.8 Handling Errors . . . . . . . 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
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
8 9
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
10 Selenium 2.0 and WebDriver 10.1 What is WebDriver? . . . . . . . . 10.2 When to Use WebDriver? . . . . . 10.3 The 5 Minute Getting Started Guide 10.4 Next Steps For Using WebDriver . 10.5 WebDriver Implementations . . . . 10.6 Emulating Selenium RC . . . . . . 10.7 Tips and Tricks . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
ii
How XPATH Works in WebDriver Getting and Using WebDriver . . Roadmap . . . . . . . . . . . . . Further Resources . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
12 Java Client Driver Conguration 127 12.1 Conguring Selenium-RC With Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . 127 12.2 Conguring Selenium-RC With Intellij . . . . . . . . . . . . . . . . . . . . . . . . . . 143 13 Python Client Driver Conguration 155
14 Locating Techniques 159 14.1 Useful XPATH patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 14.2 Starting to use CSS instead of XPATH . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
iii
iv
Contents:
CONTENTS
CONTENTS
CHAPTER
ONE
CHAPTER
TWO
INTRODUCING SELENIUM
2.1 To Automate or Not to Automate? That is the Question!
Is automation always advantageous? When should one decide to automate test cases? 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 would need to be rewritten. 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. However, 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 during the development process Virtually unlimited iterations of test case execution Customized reporting of application defects Support for Agile and eXtreme development methodologies Disciplined documentation of test cases Finding defects missed by manual testing
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 guide introduces Selenium, teaches its most widely used features, and provides useful advice in 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 as contributed by a consortium of experienced Selenium users. It is our hope that this guide will get additional new users excited about using Selenium for test automation. We hope this guide will assist in getting the word out that quality assurance and software testing have many options beyond what is currently practiced. We hope this users guide and Selenium itself provide a valuable aid to boosting the readers efciency in his or her software testing processes.
2.4.1 Selenium-IDE
Selenium-IDE is the Integrated Development Environment for building Selenium test cases. It operates as a Firefox add-on and provides an easy-to-use interface for developing and running individual test cases or entire test suites. Selenium-IDE has a recording feature, which will keep account of user actions as they are performed and store them as a reusable script to play back. It also has a context menu (right-click) integrated with the Firefox browser, which allows the user to pick from a list of assertions and verications for the selected location. Selenium-IDE also offers full editing of test cases for more precision and control. Although Selenium-IDE is a Firefox only add-on, tests created in it can also be run against other browsers by using Selenium-RC and specifying the name of the test suite on the command line.
Selenium-RC provides an API (Application Programming Interface) and library for each of its supported languages: HTML, Java, C#, Perl, PHP, Python, and Ruby. This ability to use Selenium-RC with a highlevel programming language to develop test cases also allows the automated testing to be integrated with a projects automated build environment.
2.4.3 Selenium-Grid
Selenium-Grid allows the Selenium-RC solution to scale for large test suites or test suites that must be run in multiple environments. With Selenium-Grid, multiple instances of Selenium-RC are running on various operating system and browser congurations; Each of these when launching register with a hub. When tests are sent to the hub they are then redirected to an available Selenium-RC, which will launch the browser and run the test. This allows for running tests in parallel, with the entire test suite theoretically taking only as long to run as the longest individual test.
* 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 2.5. Supported Browsers 7
Test Design Considerations Presents many useful techniques for using Selenium efciently. This includes scripting techniques and programming techniques for use with Selenium-RC. We cover examples of source code showing how to report defects in the application under test. We also cover techniques commonly asked about in the user group such as how to implement data-driven tests (tests where one can vary the data between different test passes). Selenium-Grid This chapter is not yet developed. User extensions Presents all the information required for easily extending Selenium.
2.8.3 Acknowledgements
A huge special thanks goes to Patrick Lightbody. As an administrator of the SeleniumHQ website, his support has been invaluable. Patrick has helped us understand the Selenium communityour audience. He also set us up with everything we needed on the SeleniumHQ website for developing and releasing this users guide. His enthusiasm and encouragement denitely helped drive this project. Also 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. 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, the reader. 2.8. The Documentation Team 9
10
CHAPTER
THREE
SELENIUM BASICS
3.1 Getting Started Choosing Your Selenium Tool
Most people get started with Selenium-IDE. This is what we recommend. Its an easy way to get familiar with Selenium commands quickly. You can develop your rst script in just a few minutes. Selenium-IDE is also very easy to install. See the chapter on Selenium-IDE for specics. You may also run your scripts from the Selenium-IDE. Its simple to use and is recommended for lesstechnical users. The IDE allows developing and running tests without the need for programming skills as required by Selenium-RC. The Selenium-IDE can serve as an excellent way to train junior-level employees in test automation. Anyone who understands how to conduct manual testing of a website can easily transition to using the Selenium-IDE for running and developing tests. Some testing tasks are too complex though for the Selenium-IDE. When programming logic is required Selenium-RC must be used. For example, any tests requiring iteration, such as testing each element of a variable length list requires running the script from a programming language. Selenium-IDE does not support iteration or condition statements. Finally, Selenium-Core is another way of running tests. One can run test scripts from a web-browser using the HTML interface TestRunner.html. This is the original method for running Selenium commands. It has limitations though; similar to Selenium-IDE, it does not support iteration. Selenium-Core also cannot switch between http and https protocols. Since the development of SeleniumIDE and Selenium-RC, more people are using these tools rather than Selenium-Core. At the time of writing (April 09) it is still available and may be convenient for some. However, the Selenium community is encouraging the use of Selenium-IDE and RC and discouraging the use of Selenium-Core. Support for Selenium-Core is becoming less available and it may even be deprecated in a future release.
A command is what tells Selenium what to do. Selenium commands come in three avors: Actions, Accessors and Assertions. Actions are commands that generally manipulate the state of the application. They do things like click this link and select that option. If an Action fails, or has an error, the execution of the current test is stopped. Many Actions can be called with the AndWait 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. 12 Chapter 3. Selenium Basics
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:
<table> <tr><td>open</td><td></td><td>/download/</td></tr> <tr><td>assertTitle</td><td></td><td>Downloads</td></tr> <tr><td>verifyText</td><td>//h2</td><td>Downloads</td></tr> </table>
Rendered as a table in a browser this would look like the following: open assertTitle verifyText /download/ Downloads Downloads
//h2
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.
13
3.5 Summary
Now that youve seen an introduction to Selenium, youre ready to start writing your rst scripts. We recommend beginning with the Selenium IDE and its context-sensitive, right-click, menu. This will allow you to get familiar with the most common Selenium commands quickly, and you can have a simple script done in just a minute or two. Chapter 3 gets you started and then guides you through all the features of the Selenium-IDE.
14
CHAPTER
FOUR
SELENIUM-IDE
4.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.
15
Select Install Now. The Firefox Add-ons window pops up, rst showing a progress bar, and when the download is complete, displays the following.
16
Chapter 4. Selenium-IDE
Restart Firefox. After Firefox reboots you will nd the Selenium-IDE listed under the Firefox Tools menu.
17
Options menu allows the changing of settings. You can set the timeout value for certain commands, add user-dened user extensions to the base set of Selenium commands, and specify the format (language) used when saving your test cases. The Help menu is the standard Firefox Help menu; only one item on this menuUI-Element Documentationpertains to Selenium-IDE.
4.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.
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.
19
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 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.
20
Chapter 4. Selenium-IDE
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. 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.
4.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. Note: This can be set to OFF as a default with an available user extension. 4.5. Building Test Cases 21
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.
22
Chapter 4. Selenium-IDE
4.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 >. Edit a Command or Comment
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. 4.5. Building Test Cases 23
24
Chapter 4. Selenium-IDE
Base
URL
setting
would
be
run
against
4.8 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.
4.8. Debugging
25
Then click the Run button to execute the test case beginning at that startpoint.
1. Immediately pause the executing test case with the Pause button.
26
Chapter 4. Selenium-IDE
This locator assistance is presented on the Selenium-IDE window as a drop-down list accessible at the right end of the Target eld (only when the Target eld contains a recorded locator-type argument). Below is a snapshot showing the contents of this drop-down for one command. Note that the rst column of the drop-down provides alternative locators, whereas the second column indicates the type of each alternative.
27
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. Information on writing your own extensions can be found near the bottom of the Selenium Reference document.
28
Chapter 4. Selenium-IDE
4.11 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.
4.13 Troubleshooting
Below is a list of image/explanation pairs which describe frequent sources of problems with SeleniumIDE:
4.11. Format
29
This problem occurs occasionally when Selenium IDE is rst brought up. The solution is to close and reopen Selenium IDE. The bug has been led as SIDE-230.
30
Chapter 4. Selenium-IDE
Youve used File=>Open to try to open a test suite le. Use File=>Open Test Suite instead.
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 immediately 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.
4.13. Troubleshooting
31
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.
Selenium-IDE is very space-sensitive! An extra space before or after a command will cause it to be unrecognizable.
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.
32
Chapter 4. Selenium-IDE
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 System and Division. 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.
4.13. Troubleshooting
33
34
Chapter 4. Selenium-IDE
CHAPTER
FIVE
SELENIUM COMMANDS
Selenium commands, often called selenese, are the set of commands that run your tests. A sequence of these commands is a test script. Here we explain those commands in detail, and we present the many choices you have in testing your web application when using Selenium.
35
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.
5.1.2 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.
5.1.3 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.
36
5.1.4 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=username (4) identifier=continue (5) continue (5) Since the identifier type of locator is the default, the identifier= in the rst three examples above is not necessary.
5.2.2 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. 5.2. Locating Elements 37
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)
<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.
38
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 5.2. Locating Elements 39
XPath Tutorial - with interactive examples. 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.
<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>
<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" />
40
document.forms[0].username (4) document.forms[0].elements[username] (4) 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.
<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.
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
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. 42 Chapter 5. Selenium Commands
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)
43
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.
5.7.1 storeElementPresent
This corresponds to verifyElementPresent. It simply stores a boolean valuetrue or falsedepending on whether the UI element is found.
45
5.7.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.
5.7.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
46
<!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>
47
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.]
5.10.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.
48
5.10.2 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.
49
50
CHAPTER
SIX
SELENIUM-RC
6.1 Introduction
Selenium-RC is the solution for tests that need more than simple browser actions and linear execution. Selenium-RC uses the full power of programming languages to create more complex tests like reading and writing les, querying a database, and emailing test results. Youll want to use Selenium-RC whenever your test requires logic not supported by Selenium-IDE. What logic could this be? For example, Selenium-IDE does not directly support: condition statements iteration logging and reporting of test results error handling, particularly unexpected errors database testing test case grouping re-execution of failed tests test case dependency screenshot capture of test failures Although these tasks are not supported by Selenium directly, all of them can be achieved by using programming techniques with a language-specic Selenium-RC client library. In the Adding Some Spice to Your Tests section, youll nd examples that demonstrate the advantages of using a programming language for your tests.
51
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....
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.
52
Chapter 6. Selenium-RC
6.3 Installation
After downloading the Selenium-RC zip le from the downloads page, youll notice it has several subfolders. These folders have all the components you need for using Selenium-RC with the programming language of your choice. 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
53
If you get a version number (which needs to be 1.5 or later), youre ready to start using Selenium-RC.
54
Chapter 6. Selenium-RC
Run Selenium server from the console Execute your test from a console or your Python IDE For details on Python client driver conguration, see the appendix Python Client Driver Conguration.
6.3. Installation
55
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)
56
Chapter 6. Selenium-RC
{ // 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()); } } }
In Java:
/** 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" )); } }
In Perl:
use use use use use use strict; warnings; Time::HiRes qw( sleep ) ; Test::WWW::Selenium; Test::More "no_plan" ; Test::Exception;
my $sel = Test::WWW::Selenium->new( host => "localhost" , port => 4444, browser => "*firefox" , browser_url => "http://www.google.com/" );
57
$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" );
In PHP:
<?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() { $this->open( " / " ); $this->type( " q " , " selenium rc " ); $this->click( " btnG " ); $this->waitForPageToLoad( " 30000 " ); $this->assertTrue($this->isTextPresent( " Results * for selenium rc " )); } } ?>
in Python:
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)
58
Chapter 6. Selenium-RC
in Ruby:
require " selenium " require " test/unit "
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 " / " @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:
selenium = new DefaultSelenium("localhost", 4444, "*iehta", "http://www.google.com/");
The Selenium-IDE generated code will look like this. This example has comments added manually for additional clarity.
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 } }
60
Chapter 6. Selenium-RC
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:
selenium = new DefaultSelenium("localhost", 4444, "*iehta", "http://www.google.com/");
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(); }
61
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" )); // 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.
62
Chapter 6. Selenium-RC
# 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). 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
63
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, :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 "
64
Chapter 6. Selenium-RC
# 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
In Java:
setUp( "http://www.google.com/" , "*firefox" );
In Perl:
my $sel = Test::WWW::Selenium->new( host => "localhost" , port => 4444,
65
In PHP:
$this->setBrowser("*firefox"); $this->setBrowserUrl("http://www.google.com/");
In Python:
self.selenium = selenium( " localhost " , 4444, " *firefox " , " http://www.google.com/ " ) self.selenium.start()
In Ruby:
@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. 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.
In the background the browser will actually perform a type operation, essentially identical to a user typing input into the browser, by using the locator and the string you specied during the method call.
66
Chapter 6. Selenium-RC
67
ReportNG is a HTML reporting plug-in for the TestNG framework. It is intended as a replacement for the default TestNG HTML report. ReportNG provides a simple, colour-coded view of the test results. See ReportNG for more. Also, for a very nice summary report try using TestNG-xslt. A TestNG-xslt Report looks like this.
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. 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
however iteration is impossible, and most conditions will be much easier in a programming language. In addition, you may need exception handling for error recovery. For these reasons and others, we have written this section to illustrate the use of common programming techniques to give you greater verication power in your automated testing. The examples in this section are written in C# and Java, although the code is simple and can be easily adapted to the other supported languages. If you have some basic knowledge of an object-oriented programming language you shouldnt have difculty understanding this section.
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#:
// 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)); }
69
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.
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; }
70
Chapter 6. Selenium-RC
selenium.getEval( "window.document.images.length;" );
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.jar -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.
71
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.
72
Chapter 6. Selenium-RC
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
73
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
74
Chapter 6. Selenium-RC
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.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.
75
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.
76
Chapter 6. Selenium-RC
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). 6.11. Selenium-RC Architecture 77
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). 78 Chapter 6. Selenium-RC
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.
79
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.
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.
80
Chapter 6. Selenium-RC
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.
81
16:20:03.919 INFO - Preparing Firefox profile... 16:20:27.822 WARN - GET /selenium-server/driver/?cmd=getNewBrowserSession&1=*fir efox&2=https%3a%2f%2f2.zoppoz.workers.dev%3a443%2fhttp%2fsage-webapp1.qa.idc.com HTTP/1.1 java.lang.RuntimeException: Firefox refused shutdown while preparing a profile at org.openqa.selenium.server.browserlaunchers.FirefoxCustomProfileLaunc her.waitForFullProfileToBeCreated(FirefoxCustomProfileLauncher.java:277) ......................... Caused by: org.openqa.selenium.server.browserlaunchers.FirefoxCustomProfileLaunc her$FileLockRemainedException: Lock file still present! C:\DOCUME~1\jsvec\LOCALS ~1\Temp\customProfileDir203138\parent.lock
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.
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.
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.
85
86
Chapter 6. Selenium-RC
CHAPTER
SEVEN
This is HTML snippet for a check box. Its ID and name (addForm:_ID74:_ID75:0:_ID79:0:checkBox) are same and both are dynamic (they will change the next time you open the application). In this case
88
89
Getting a feel for these types of decisions will come with time and a little experience. They are easy concepts, and easy to change in your test, but they do depend do depend on the requirements of your AUT. For some projects the requirements are clear and therefore your tests will be clear. For others, not so much, and you will have to give it your best guess. The purpose of this subsection is to help you anticipate your needs so you can make these decisions more efciently.
This is HTML anchor tag dening an 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 within 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. 90 Chapter 7. Test Design ConsIDerations
click
adminHomeForm
Or, in Selenium-RC
selenium.click( "adminHomeForm" );
Your application, however, may generate HTML with IDs that are generated dynamically and therefore the ID itself varies on different instances of the webpage under test. 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 programmed solution is required. Another solution is to capture this ID from the website itself, before you need to use it in a Selenium command. It can be done like this.
String[] checkboxids = selenium.getAllFields(); // Collect all input IDs on page. if(!GenericValidator.IsBlankOrNull(checkboxids[i])) // If collected ID is not null. { // If the ID starts with addForm if(checkboxids[i].indexOf( "addForm" ) > -1) { selenium.click(checkboxids[i]);
91
} }
This approach will work if there is only one eld whose ID has the text addForm appended to it. Consider one more example of a Dynamic object; a page with two links having the same name and the same html name. Now if href is used to click the link, it would always be clicking on the rst element. Clicking on the second link can be achieved as follows.
// Flag for second appearance of link. boolean isSecondInstanceLink = false; // Desired link. String editInfo = null; // Collect all links. String[] links = selenium.getAllLinks(); // Loop through collected links. for(String linkID: links) { // If retrieved link is not null if(!GenericValidator.isBlankOrNull(linkID))
// Find the inner HTML of link. String editTermSectionInfo = selenium.getEval ( "window.document.getElementByID(" +linkID+ ").innerHTML" ); // If retrieved link is expected link. if(editTermSectionInfo.equalsIgnoreCase( "expectedlink" )) { // If it is second appearance of link then save the link ID and break the loop. if(isSecondInstanceLink) { editInfo = linkID; break; } // Set the second appearance of Autumn term link to true as isSecondInstanceLink = true; } } } // Click on link. selenium.click(editInfo);
You might consider trying the UI-Element extension in this situation. http://wiki.openqa.org/display/SIDE/Contributed+Extensions+and+Formats#ContributedExtensionsandFormatsUIElementLocator
// 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 group and we suggest searching previous discussions to see what others have done along with the questions they have posted.
7.6 UI Mapping
A UI map is a mechanism that stores Identiers, or in our case, locators, for an applications UI elements. 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. 7.5. Testing Ajax Applications 93
What makes a UI map heplful? 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 Identifer 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 maintanence more efcient. Cryptic HTML Identiers and names can be given more human-readable names improving the readability of test scripts. Consider the following example (in java) of selenium tests for a website:
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 is incomprehensible to anyone who isnt very familiar with the AUTs page source. Even regular users of the application would have difculty understanding what the script does. A better script would 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" ); }
There are no comments provided but it is more comprehensible because of the keywords used in scripts. (please be aware that UI Map is NOT a replacement for comments! Comments are still important for documenting an automated test.) An even better test script could look like this.
public void testNew() throws Exception { // Open app url. selenium.open( "http://www.test.com" );
94
// 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" ); }
The idea is to have a centralized location for objects and using comprehensible names for those objects. To achieve this, properties les can be used in java. A properties le contains key/value pairs, where each key and value are strings. Consider a property le prop.properties which assigns as aliases easily understood Identiers for the HTML objects used earlier.
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 Properties les refer to the following link.
95
sel.type( " q " , search) sel.click( " btnG " ) sel.waitForPageToLoad( " 30000 " ) self.failUnless(sel.is_text_present( " Results * for
" + search))
Why would we want a separate le with data in it for our tests? One important method of testing is to run the same test repetitively with different data values. This is called Data Driven Testing and is a very common testing task. Test automation tools, Selenium included, generally handle this as its a common reason for test automation. 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 of what you can do, but the Idea is to show you things that can easily be done with either a programming or scripting language when theyre difcult or even impossible to do using Selenium-IDE. Refer to the Selnium RC wiki for examples of reading data from spread sheet or using data provider capabilities of TestNG with java client driver.
96
public static Connection con = DriverManager.getConnection(url, "username" , "password" ); // Create statement object which would be used in writing DDL and DML // SQL statement. public static Statement stmt = con.createStatement(); // Send SQL SELECT statements to the database via the Statement.executeQuery // method which returns the requested information as rows of data in a // ResultSet object. ResultSet result = stmt.executeQuery ( "select top 1 email_address from user_register_table" ); // Fetch value of "email_address" from "result" object. String emailaddress = result.getString( "email_address" ); // Use the fetched value to login to application. selenium.type( "userID" , emailaddress);
This is a very simple example of data retrieval from a DB in Java. A more complex test could be to validate that inactive users are not able to login to the application. This wouldnt take too much work from what youve already seen.
97
98
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.
99
100
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, verifyFooa nd 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
101
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.
102
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
103
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(); }
104
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); } } }
105
106
Chapter 9. User-Extensions
CHAPTER
TEN
107
public class Example { public static void main(String[] args) { // Create a new instance of the html unit driver // Notice that the remainder of the code relies on the interface, // not the implementation. WebDriver driver = new HtmlUnitDriver(); // And now use this to visit Google driver.get( "http://www.google.com" );
108
// 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()); } }
Compile and run this. You should see a line with the title of the Google search results as output on the console. Congratulations, youve managed to get started with WebDriver! In this next example, you shall use a page that requires Javascript to work properly, such as Google Suggest. You will also be using the Firefox Driver. Make sure that Firefox is installed on your machine and is in the normal location for your OS. Once thats done, create a new class called GoogleSuggest, which looks like:
package org.openqa.selenium.example; import java.util.List; import import import import import org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.RenderedWebElement; org.openqa.selenium.WebElement; org.openqa.selenium.firefox.FirefoxDriver;
public class GoogleSuggest { public static void main(String[] args) throws Exception { // The Firefox driver supports javascript WebDriver driver = new FirefoxDriver(); // Go to the Google Suggest home page driver.get( "http://www.google.com/webhp?complete=1&hl=en" ); // Enter the query string "Cheese" WebElement query = driver.findElement(By.name( "q" )); query.sendKeys( "Cheese" );
// Sleep until the div we want is visible or 5 seconds is over long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { // Browsers which render content (such as Firefox and IE) // return "RenderedWebElements" RenderedWebElement resultsDiv = (RenderedWebElement) driver.findElement(By.c // If results have been returned, // the results are displayed in a drop down. if (resultsDiv.isDisplayed()) { break;
109
} }
// And now list the suggestions List<WebElement> allSuggestions = driver.findElements(By.xpath( "//td[@class=gac for (WebElement suggestion : allSuggestions) { System.out.println(suggestion.getText()); } } }
When you run this program, youll see the list of suggestions being printed to the console. Thats all there is to using WebDriver! Hopefully, this will have whet your appetite for more. In the Next Steps section you will learn more about how to use WebDriver for things such as navigating forward and backward in your browsers history, and how to use frames and windows. It also provides a more complete discussion of the examples than The 5 Minute Getting Started Guide. If youre ready, lets take the Next Steps!
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 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();
110
10.4.2 Navigating
The rst thing youll want to do with WebDriver is navigate to a page. The normal way to do this is by calling get:
driver.get( "http://www.google.com" );
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 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 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:
111
element.clear();
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 can see, 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();
112
Not all drivers render their content to the screen (such as the HtmlUnit Driver), so its not safe to assume that the cast will work, but if it does you can gather additional information such as the size and location of the element. In addition, you can use drag and drop, either moving an element by a certain amount, or on to another element:
RenderedWebElement element = (RenderedWebElement) driver.findElement(By.name( "source" )) RenderedWebElement target = (RenderedWebElement) driver.findElement(By.name( "target" )); element.dragAndDropOn(target);
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*.
113
driver.navigate().to( "http://www.example.com" );
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:
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.
10.4.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:
// 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 }
A pure Java solution and so it is platform independent. Supports JavaScript Cons Emulates other browsers JavaScript behaviour (see below) JavaScript in the HtmlUnit Driver None of the popular browsers uses the JavaScript engine used by HtmlUnit (Rhino). If you test JavaScript using HtmlUnit the results may differ signicantly from those browsers. When we say JavaScript we actually mean JavaScript and the DOM. Although the DOM is dened by the W3C each browser out there has its own quirks and differences in their implementation of the DOM and in how JavaScript interacts with it. HtmlUnit has an impressively complete implementation of the DOM and has good support for using JavaScript, but it is no different from any other browser: it has its own quirks and differences from both the W3C standard and the DOM implementations of the major browsers, despite its ability to mimic other browsers. With WebDriver, we had to make a choice; do we enable HtmlUnits JavaScript capabilities and run the risk of teams running into problems that only manifest themselves there, or do we leave JavaScript disabled, knowing that there are more and more sites that rely on JavaScript? We took the conservative approach, and by default have disabled support when we use HtmlUnit. With each release of both WebDriver and HtmlUnit, we reassess this decision: we hope to enable JavaScript by default on the HtmlUnit at some point. 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.
115
Before Going Any Further The Firefox Driver contains everything it needs in the JAR le. If youre just interested in using this driver, then all you need to do is put the webdriver-firefox.jar or webdriver-all.jar on your CLASSPATH, and WebDriver will do everything else for you. If you want to dig deeper, though, carry on reading! Important System Properties The following system properties (read using System.getProperty() and set using System.setProperty() in Java code or the -DpropertyName=value command line ag) are used by the Firefox Driver: Property What it means webThe location of the binary used to control Firefox. driver.refox.bin webThe name of the prole to use when starting Firefox. This defaults to driver.refox.prole WebDriver creating an anonymous prole webShould be true if temporary les and proles should not be deleted driver.reap_prole Normally the Firefox binary is assumed to be in the default location for your particular operating system: OS Expected Location of Firefox Linux refox (found using which) Mac /Applications/Firefox.app/Contents/MacOS/refox Windows XP %PROGRAMFILES%\Mozilla Firefox\refox.exe Windows Vista \Program Files (x86)\Mozilla Firefox\refox.exe By default, the Firefox driver creates an anonymous prole Installing a Downloaded Binary The wedriver-all.zip which may be downloaded from the website, contains all the dependencies (including the common library) required to run the Firefox Driver. In order to use it: Copy all the jar les on to your CLASSPATH.
Installing Simply add webdriver-all.jar to your CLASSPATH. You do not need to run an installer before using the Internet Explorer Driver, though some conguration is required. Required Conguration Add every site you intend to visit to your Trusted Sites If you do not do this, then you will not be able to interact with the page.
Normally the Chrome binary is assumed to be in the default location for your particular operating system:
117
Expected Location of Chrome /usr/bin/google-chrome /Applications/Google Chrome.app/Contents/MacOS/GoogleChrome or /User/:username/:as_to_the_left %HOMEPATH%\Local Settings\Application Data\Google\Chrome\Application\chrome.exe C:\Users%USERNAME%\AppData\Local\Google\Chrome\Application\chrome.exe
Installing a Downloaded Binary The wedriver-all.zip which may be downloaded from the website, contains all the dependencies required to run the Chrome Driver. In order to use it, copy all the jar les on to your CLASSPATH.
// And get the underlying WebDriver implementation back. This will refer to the // same WebDriver instance as the "driver" variable above. WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getUnderlyingWebDriver()
10.6.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
10.6.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 118 Chapter 10. Selenium 2.0 and WebDriver
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.
Currently, only the Firefox Driver supports this, but you should also expect support for the Internet Explorer Driver too.
119
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:
FirefoxProfile profile = new FirefoxProfile(); profile.setEnableNativeEvents(true); WebDriver driver = new FirefoxDriver(profile);
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
120
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.
If you want to use the Firefox Driver, you need to add the following dependency to your pom.xml:
<dependency> <groupId>org.seleniumhq.webdriver</groupId> <artifactId>webdriver-firefox</artifactId> <version>0.9.7376</version> </dependency>
If you want to use the Internet Explorer Driver, you need to add the following dependency to your pom.xml:
<dependency> <groupId>org.seleniumhq.webdriver</groupId> <artifactId>webdriver-ie</artifactId> <version>0.9.7376</version> </dependency>
If you want to use the Chrome Driver, you need to add the following dependency to your pom.xml:
<dependency> <groupId>org.seleniumhq.webdriver</groupId> <artifactId>webdriver-chrome</artifactId> <version>0.9.7376</version> </dependency>
Finally, if you like to use any of our support classes, you should add the following dependency to your pom.xml:
121
10.10 Roadmap
The roadmap for WebDriver is available here
122
CHAPTER
ELEVEN
Select Visual C# > Class Library > Name your project > Click on OK button.
123
Under right hand pane of Solution Explorer right click on References > Add References.
124
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
125
126
CHAPTER
TWELVE
127
128
Provide Name to your project, Select JDK in Use a project Specic JRE option (JDK 1.5 selected in this example) > click Next
129
Keep JAVA Settings intact in next window. Project specic libraries can be added here. (This described in detail in later part of document.)
130
Click Finish > Click on Yes in Open Associated Perspective pop up window.
131
132
133
Name this folder as com and click on Finish button. This should get com package insider src folder.
134
135
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.
136
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)
137
138
Right click on lib folder > Build Path > Congure build Path
139
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.
140
141
142
143
144
145
Click Next and provide Module name and Module content root.
146
Adding Libraries to Project: Click on Settings button in the Project Tool bar.
147
148
Browse to the Selenium directory and select selenium-java-client-driver.jar and seleniumserver.jar. (Multiple Jars can be selected b holding down the control key.).
149
Select both jar les in project pan and click on Apply button.
150
Now click ok on Project Structure followed by click on Close on Project Settings pan. Added jars would appear in project Library as following.
151
152
Note: This is not hard and fast convention and might very from project to project. Herein core contains the SelTestCase class which is used to create Selenium object and re up the browser. testscripts package contains the test classes which extend the SelTestCase class. Hence extended structure would look as following.
153
154
CHAPTER
THIRTEEN
155
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). 156 Chapter 13. 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.
157
158
CHAPTER
FOURTEEN
LOCATING TECHNIQUES
14.1 Useful XPATH patterns
14.1.1 text
Not yet written - locate elements based on the text content of the node.
14.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-)]
14.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
14.1.4 siblings
Not yet written - locate elements based on their siblings. Useful for forms and tables.
159
CSS: css=div.article-heading
160