This action might not be possible to undo. Are you sure you want to continue?
Release 1.0
Selenium Project
December 13, 2010 8 8 9 11 11 11 13 14 14 15 15 15 18 19 22 24 24 25 27 28 29 29 29
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .ium Commands 33 5.1 Verifying Page Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 5.2 Locating Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 5.3 Matching Text Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
i
. . . 6. . . . . . . . . . . . . . . Selenium-Grid User-Extensions 9. . . . . . . . . . . . . . . . . . .1 Introduction . . . . . . . .The Selenese Print Command . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Emulating Selenium RC . . . . . . . . . . . . . . . .1 Introducing Test Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 Adding Some Spice to Your Tests . . . . . . . . . .5 Using User-Extensions With Selenium-IDE 9.4 Locator Strategies . . . . . .9 Server Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Programming Your Test .10 6 The “AndWait” Commands . . .5 5. . . . . . . . . . .12 Handling HTTPS and Security Popups . . . . . . . . . . . . . . . . . . . .3 Accessors/Assertions . ii . . . . . . . . . . . . . . . . . . . . . . . .11 Selenium-RC Architecture . . . . . . . . . . . . . . . . .3 Verifying Results . . . . .0 and WebDriver 10. . . . . . . . . . . . . .2 Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . .4 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Testing Ajax Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. .13 Supporting Additional Browsers and Browser Conﬁgurations 6. . . . . . . . .2 When to Use WebDriver? . . . . . . . . . . . . . . . . . . . . 6. . . . .7 Reporting Results .6 Using User-Extensions With Selenium RC . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . .1 Introduction . . . . . . . . Popups.5 WebDriver Implementations . . . . . . .14 Troubleshooting Common Problems . .7 Tips and Tricks . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . and Multiple Windows . . . .3 The 5 Minute Getting Started Guide 10. .6 5. . . . . . . . . . . . . .4 Next Steps For Using WebDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 . . . . . .8 Handling Errors . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . Alerts. . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 UI Mapping . . . . . . . . . . . . Test Design ConsIDerations 7. . . 6. . . . . . . . . . . . . . . 9. . . . .4 From Selenese to a Program . . . . . . The waitFor Commands in AJAX applications Sequence of Evaluation and Flow Control . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 5. . . . . . . . . . . . . . . . . . . . 6. . . . . . . 6. . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . echo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 What to Test? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . JavaScript and Selenese Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 5. . . . . . 8 9 . . . . 9. . . . . . . . . . . . 10 Selenium 2. . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Store Commands and Selenium Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. . . . . . . . . . . 9. . . . . . . . . . . . . . 10. 42 42 42 43 44 45 45 49 49 49 51 54 57 63 65 66 69 73 73 77 78 78 85 85 85 87 88 91 91 93 94 97 99 99 99 99 100 101 101 105 105 106 106 108 112 116 117 Selenium-RC 6. 10. . . . . . . . . . . .1 What is WebDriver? . . . . . . . . . . . . . . . . . . 7. . . . . . . . . .7 Bitmap Comparison . . . . .6 Learning the API . . . . . . .4 Choosing a Location Strategy 7. . . . 10. . . . . . . . . . . . . . . . . . .10 Specifying the Path to a Speciﬁc Browser . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . 9. . . . . . .9 5.2 How Selenium-RC Works . . . . . . . . . . . . . . . .
. . . . 141 13 Python Client Driver Conﬁguration 153 14 Locating Techniques 157 14. . . . . . . . . . .1 Useful XPATH patterns . . . . . . . . .10 10.9 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET client driver conﬁguration 12 Java Client Driver Conﬁguration 125 12. . . . . . . . . . . . . . . . . . Roadmap . . . .11 How XPATH Works in WebDriver Getting and Using WebDriver . . . . . . . . . . . . . . . . . . . 118 119 120 120 121 11 . . . . . .10. . . . . . . . . . . . . . 125 12. . . . . . . . . . . . . . . . . . . . . . . . . . . 157 14. . . . . . . . . . . . . . . . .2 Starting to use CSS instead of XPATH . . .1 Conﬁguring Selenium-RC With Eclipse . . 157 iii . . . . . . . . . . . . . . . . . . . . . . .2 Conﬁguring Selenium-RC With Intellij . . . . . . . . . . . . . . . . . . . . .8 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Further Resources . . . .
iv
Selenium Documentation, Release 1.0
Contents:
CONTENTS
1
Selenium Documentation, Release 1.0
2
CONTENTS
Thanks very much for reading. or suggestions you have for improving it. hopefully. and to thank you for being interested in Selenium. Also. is unmatched by available proprietary tools. we believe this documentation will truly help to spread the knowledge around. we have aimed to write so that those completely new to test automation will be able to use this document as a stepping stone. We really want to hear about any problems you have with the documentation. Whether you are brand-new to Selenium. There are planned areas we haven’t written yet. and welcome to Selenium! The Documentation Team would like to welcome you. along with its tight integration with the browser. This document will be a ‘live’ document on the SeleniumHQ website where frequent updates will occur as we complete the additional planned documentation. However. Why? We absolutely believe this is the best tool for web-application testing. We feel its extensibility and ﬂexibility. We have worked very. we really want to “get the word out” about Selenium. or have been using it for awhile. to expand its user community. No doubt.CHAPTER ONE NOTE TO THE READER Hello. We are very excited to promote Selenium and. We truly believe you will be similarly excited once you learn how Selenium approaches test automation. please ﬁle a bug report. It’s quite different from other tools. In short. experienced users and “newbies” will beneﬁt from our Selenium User’s Guide. – the Selenium Documentation Team 3 . We have also already added some valuable information that more experienced users will appreciate. we have written the beginning chapters ﬁrst so newcomers can get started more smoothly. Please realize that this document is a work in progress. For errors. Improvement suggestions should be ﬁled as an enhancement request. very hard on this document.
0 4 Chapter 1. Release 1.Selenium Documentation. Note to the Reader .
There are times when manual testing may be more appropriate. Software testing is often conducted manually. Also.CHAPTER TWO INTRODUCING SELENIUM 2. such as eXtreme programming (XP) and Agile. The effectiveness of testing these applications varies widely among companies and organizations. manual testing may be more effective. or lack the skills to perform.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. and it’s imperative that the testing get done within that time frame. Utilizing these alternatives would in most cases greatly improve the efﬁciency of their software development by adding efﬁciencies to their testing. software applications today are written as web-based applications to be run in an Internet browser. For instance. Test automation means using a tool to run repeatable tests against the target application whenever necessary. this is effective. At times. 5 . then manual testing is the best solution. automation has speciﬁc advantages for improving the long-term efﬁciency of a software team’s testing processes. sometimes there simply is not enough time to build test automation. Test automation is often the answer. If an application has a very tight deadline. however there are alternatives to manual testing that many organizations are unaware of. then any automation would need to be rewritten. However. perhaps most. For the short term.2 Test Automation for Web Applications Many.. In an era of continuously improving software processes. if the application’s user interface will change considerably in the near future. there is currently no test automation available. it can be argued that disciplined testing and quality assurance practices are still underdeveloped in many organizations.
One of Selenium’s key features is the support for executing one’s tests on multiple browser platforms. These operations are highly ﬂexible. 6 Chapter 2. Introducing Selenium . 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. if the application under test returns a result set.4.4 Selenium Components Selenium is composed of three major tools. Selenium-IDE also offers full editing of test cases for more precision and control. the programming language’s iteration support can be used to iterate through the result set. and if the automated test program needs to run tests on each element in the result set. Although Selenium-IDE is a Firefox only add-on. Also. This user’s guide will assist both new and experienced Selenium users in learning effective techniques in building test automation for web applications. It is our hope that this guide will get additional new users excited about using Selenium for test automation. which allows the user to pick from a list of assertions and veriﬁcations for the selected location. For instance. 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. Many examples are provided. and provides useful advice in best practices accumulated from the Selenium community.2 Selenium-RC (Remote Control) Selenium-RC allows the test automation developer to use a programming language for maximum ﬂexibility and extensibility in developing test logic. This guide introduces Selenium. We hope this user’s guide and Selenium itself provide a valuable aid to boosting the reader’s efﬁciency in his or her software testing processes. calling Selenium commands to run tests on each item. Most are related to the repeatability of the tests and the speed at which the tests can be executed.3 Introducing Selenium Selenium is a robust set of tools that supports rapid development of test automation for web-based applications. 2.Selenium Documentation. 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 operates as a Firefox add-on and provides an easy-to-use interface for developing and running individual test cases or entire test suites. Release 1. which will keep account of user actions as they are performed and store them as a reusable script to play back. Selenium-IDE has a recording feature. Each one has a speciﬁc role in aiding the development of web application test automation. There are a number of commercial and open source tools available for assisting with the development of test automation. 2. teaches its most widely used features. Selenium is possibly the most widelyused open source solution.1 Selenium-IDE Selenium-IDE is the Integrated Development Environment for building Selenium test cases.0 There are many advantages to test automation.4. Selenium provides a rich set of testing functions speciﬁcally geared to the needs of testing of a web application. allowing many options for locating UI elements and comparing expected test results against actual application behavior. 2. 2. It also has a context menu (right-click) integrated with the Firefox browser.
Linux. run tests Start browser. run tests Start browser. and Ruby. C#. Linux. Linux. which will launch the browser and run the test. Mac Windows. Perl. run tests Start browser. This allows for running tests in parallel. Linux. Python. run tests Start browser. 2. multiple instances of Selenium-RC are running on various operating system and browser conﬁgurations.Selenium Documentation. Mac Windows. Each of these when launching register with a hub. Release 1. Supported Browsers 7 .0 Selenium-RC provides an API (Application Programming Interface) and library for each of its supported languages: HTML. 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 project’s automated build environment. run tests Start browser. run tests Start browser.4. With Selenium-Grid. When tests are sent to the hub they are then redirected to an available Selenium-RC. Java. run tests Partial support possible** Operating Systems Windows. Mac Windows Windows Windows Mac Mac Mac Windows. run tests Start browser. run tests Start browser. Mac Windows As applicable * Tests developed on Firefox via Selenium-IDE can be executed on any other supported browser via a simple Selenium-RC command line. run tests Start browser. Mac Windows. run tests Start browser. but depending on browser security settings there may 2.5. run tests Start browser. run tests Start browser. PHP. with the entire test suite theoretically taking only as long to run as the longest individual test. ** Selenium-RC server can start any executable.5 Supported Browsers Browser Firefox 3. 2. Mac Windows-RC Start browser.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. Linux. Linux.
It introduces the novice to Selenium test automation. Release 1. veriﬁcations and assertions can be made against a web application. Many examples are presented in both a programming language and a scripting language. This is. Selenium’s strongest characteristic when compared with proprietary test automation tools and other open source solutions. Architecture diagrams are provided to help illustrate these points. pop-ups. This chapter also describes useful techniques for making your scripts more readable when interpreting defects caught by your Selenium tests. We explain how your test script can be “exported” to the programming language of your choice. Selenium-IDE Teaches how to build test cases using the Selenium Integrated Development Environment. Finally. A number of solutions to problems which are often difﬁcult for the new user are described in this chapter. Selenium is an Open Source project where code can be modiﬁed and enhancements can be submitted for contribution. This includes handling Security Certiﬁcates. and the opening of new windows. We do not assume the reader has experience in testing beyond the basics. this section describes some conﬁgurations available for extending and customizing how the Selenium-IDE supports test case development. 2. Also provides a general description of Selenium commands and syntax. The various modes. Finally. Selenium Commands Describes a subset of the most useful Selenium commands in detail. Also.7 About this Book This reference documentation targets both new users of Selenium and those who have been using Selenium and are seeking additional knowledge. along with their trade-offs and limitations.6 Flexibility and Extensibility You’ll ﬁnd that Selenium is highly ﬂexible. This allows users to customize the generated code to ﬁt in with their own test frameworks. or conﬁgurations. This section allows you to get a general feel for how Selenium approaches test automation and helps you decide where to begin. Selenium-IDE allows for the addition of user-deﬁned “user-extensions” for creating additional commands customized to the user’s needs. Introducing Selenium . the installation and setup of Selenium-RC is covered here. There are multiple ways in which one can add functionality to Selenium’s framework to customize test automation for one’s speciﬁc testing needs. Also. perhaps. The remaining chapters of the reference present: Selenium Basics Introduces Selenium by describing how to select the Selenium component most appropriate for your testing tasks. Selenium-RC Explains how to develop an automated test program using the Selenium-RC API. 2.. This chapter shows what types of actions. that Selenium-RC supports are described.0 be technical limitations that would limit certain features. The experienced Selenium user will also ﬁnd this reference valuable. 8 Chapter 2. Selenium-RC support for multiple programming and scripting languages allows the test writer to build any logic they need into their automated testing and to use a preferred programming or scripting language of one’s choice.Selenium Documentation. https requests.
8. Each of us contributed signiﬁcantly by taking a leadership role in speciﬁc areas. but in the end. He also set us up with everything we needed on the SeleniumHQ website for developing and releasing this user’s guide. Release 1. Selenium-Grid This chapter is not yet developed. Mary Ann. This includes scripting techniques and programming techniques for use with Selenium-RC.3 Acknowledgements A huge special thanks goes to Patrick Lightbody.2 Current Authors • Mary Ann May-Pumphrey • Peter Newhook In addition to the original team members who are still involved (May ‘09). and the continued efforts of the current developers. and to Amit Kumar for participating in our discussions and for assisting with reviewing the document. Mary Ann is actively writing new subsections and has provided editorial assistance throughout the document. Patrick has helped us understand the Selenium community–our audience. we would not have such a great tool to pass on to you. 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). The Documentation Team 9 .8. We cover examples of source code showing how to report defects in the application under test. his support has been invaluable. we must recognize the Selenium Developers.8 The Documentation Team 2.0 Test Design Considerations Presents many useful techniques for using Selenium efﬁciently. 2. Without the vision of the original designers. Each chapter originally had a primary author who kicked off the intial writing. Their reviewing and editorial contributions proved invaluable. Also thanks goes to Andras Hatvani for his advice on publishing solutions. User extensions Presents all the information required for easily extending Selenium. and Peter have recently made major contributions.8. As an administrator of the SeleniumHQ website.8. each of us made signiﬁcant contributions to each chapter throughout the project. Their enthusiasm and dedication has been incredibly helpful. We hope they continue to be involved. They have truly designed an amazing tool. And of course.1 The Original Authors • Dave Hunt • Paul Grandjean • Santiago Suarez Ordonez • Tarun Kumar The original authors who kickstarted this document are listed in alphabetical order.Selenium Documentation. 2. His enthusiasm and encouragement deﬁnitely helped drive this project. 2. 2. Peter has provided assistance with restructuring our most difﬁcult chapter and has provided valuable advice on topics to include. the reader.
Selenium Documentation.0 10 Chapter 2. Release 1. Introducing Selenium .
When programming logic is required Selenium-RC must be used. 11 . event handling. input ﬁelds. This is what we recommend. the Selenium community is encouraging the use of Selenium-IDE and RC and discouraging the use of Selenium-Core.1 Selenium Commands – Selenese Selenium provides a rich set of commands for fully testing your web-app in virtually any way you can imagine. You may also run your scripts from the Selenium-IDE. test for broken links. it does not support iteration. any tests requiring iteration. However.2. Ajax functionality. alerts. One can run test scripts from a web-browser using the HTML interface TestRunner. 3.html. It has limitations though. It’s simple to use and is recommended for lesstechnical users. The Selenium-IDE can serve as an excellent way to train junior-level employees in test automation. In selenese. Anyone who understands how to conduct manual testing of a website can easily transition to using the Selenium-IDE for running and developing tests. This is the original method for running Selenium commands. Selenium-Core is another way of running tests. and many other web-application features. Selenium-IDE does not support iteration or condition statements. The command set is often called selenese. Support for Selenium-Core is becoming less available and it may even be deprecated in a future release. test for speciﬁc content. The Command Reference lists all the available commands. and table data among other things. Since the development of SeleniumIDE and Selenium-RC. similar to Selenium-IDE. more people are using these tools rather than Selenium-Core.2 Introducing Selenium Commands 3. such as testing each element of a variable length list requires running the script from a programming language. It’s an easy way to get familiar with Selenium commands quickly. Some testing tasks are too complex though for the Selenium-IDE. submitting forms.1 Getting Started – Choosing Your Selenium Tool Most people get started with Selenium-IDE. Finally. Selenium-IDE is also very easy to install. In addition Selenium commands support testing of window size. These commands essentially create a testing language. pop up windows.CHAPTER THREE SELENIUM BASICS 3. one can test the existence of UI elements based on their HTML tags. You can develop your ﬁrst script in just a few minutes. Selenium-Core also cannot switch between http and https protocols. For example. mouse position. selection list options. See the chapter on Selenium-IDE for speciﬁcs. The IDE allows developing and running tests without the need for programming skills as required by Selenium-RC. At the time of writing (April 09) it is still available and may be convenient for some.
“verifyText” and “waitForText”.0 A command is what tells Selenium what to do. they will fail and halt the test if the condition does not become true within the current timeout setting (see the setTimeout action below). “storeTitle”. logging the failure.2. If an Action fails. the execution of the current test is stopped. When an “assert” fails. however they are typically: • a locator for identifying a UI element within a page.2 Script Syntax Selenium commands are simple. They do things like “click this link” and “select that option”. Parameters vary. “clickAndWait”. labels.g. and the commands themselves are described in considerable detail in the section on Selenium Commands. in others one parameter is required. 12 Chapter 3. Examples include “make sure the page title is X” and “verify that this checkbox is checked”. e. the test is aborted. Locators. followed by a bunch of “verify” assertions to test form ﬁeld values. the test will continue execution. Release 1. Accessors and Assertions. Many Actions can be called with the “AndWait” sufﬁx. 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. This sufﬁx tells Selenium that the action will cause the browser to make a call to the server.Selenium Documentation. and that Selenium should wait for a new page to load. you can “assertText”. They are also used to automatically generate Assertions. • Actions are commands that generally manipulate the state of the application. but they verify that the state of the application conforms to what is expected. etc. In some cases both are required. e. They will succeed immediately if the condition is already true. “verify”. • 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. and in still others the command may take no parameters at all. they consist of the command and two parameters. However. or has an error. All Selenium Assertions can be used in 3 modes: “assert”. and ” waitFor”. selenium variables. text patterns. it depends on the command. • Assertions are like Accessors. For example. This allows a single “assert” to ensure that the application is on the correct page. 3. • Accessors examine the state of the application and store the results in variables. “waitFor” commands wait for some condition to become true (which can be useful for testing Ajax applications).g. Selenium Basics . When a “verify” fails. For example: verifyText //div//a[2] Login The parameters are not always required. Selenium commands come in three “ﬂavors”: Actions.
An HTML table deﬁnes a list of tests where each row deﬁnes the ﬁlesystem path to each test. This consists of an HTML table with three columns. An example tells it all./Login.Selenium Documentation./SearchValues. With a basic knowledge of selenese and Selenium-IDE you can quickly produce and run testcases. but they should be present. from the Selenium-IDE.. Additionally. The ﬁrst column identiﬁes the Selenium command. Each table row represents a new Selenium command. Here is an example of a test that opens a page.3 Test Suites A test suite is a collection of tests. Release 1./SaveValues. Commonly Junit is used to maintain a test suite if one is using Selenium-RC with Java. if C# is the chosen language.0 Selenium scripts that will be run from Selenium-IDE will be be stored in an HTML text ﬁle format. The second and third columns may not require values depending on the chosen Selenium command. and the ﬁnal column contains a value.html" >Login</a></td></tr> <tr><td><a href= ". the second is a target.html" >Test Searching for Values</a></td></tr> <tr><td><a href= ". one after another. When using Selenium-IDE. Often one will run all the tests in a test suite as one continuous batch-job.html" >Test Save</a></td></tr> </table> </body> </html> A ﬁle similar to this would allow running the tests all at once. 3. The syntax again is simple. Since the whole reason for using Sel-RC is to make use of programming logic for your testing this usually isn’t a problem. <html> <head> <title>Test Suite Function Tests . This is done via programming and can be done a number of ways. Nunit could be employed. Test suites can also be maintained when using Selenium-RC. Test Suites 13 . If using an interpreted language like Python with Selenium-RC than some simple programming would be involved in setting up a test suite.Priority 1</title> </head> <body> <table> <tr><td><b>Suite Of Tests</b></td></tr> <tr><td><a href= ". test suites also can be deﬁned using a simple HTML ﬁle. 3.
waitForPageToLoad pauses execution until an expected new page loads. We recommend beginning with the Selenium IDE and its context-sensitive. and you can have a simple script done in just a minute or two. This will allow you to get familiar with the most common Selenium commands quickly. as deﬁned by its HTML tag. verifyTextPresent veriﬁes expected text is somewhere on the page. Called automatically when clickAndWait is used. These are probably the most commonly used commands for building tests. and optionally waits for a new page to load. verifyTable veriﬁes a table’s expected contents. 14 Chapter 3. verifyText veriﬁes expected text and it’s corresponding HTML tag are present on the page. open opens a page using a URL. Release 1. verifyElementPresent veriﬁes an expected UI element.0 3.4 Commonly Used Selenium Commands To conclude our introduction of Selenium. 3. we’ll show you a few typical Selenium commands. waitForElementPresent pauses execution until an expected UI element. is present on the page. right-click. menu. verifyTitle/assertTitle veriﬁes an expected page title. you’re ready to start writing your ﬁrst scripts. click/clickAndWait performs a click operation. Chapter 3 gets you started and then guides you through all the features of the Selenium-IDE. is present on the page.5 Summary Now that you’ve seen an introduction to Selenium.Selenium Documentation. Selenium Basics . as deﬁned by its HTML tag.
This chapter is all about the Selenium IDE and how to use it effectively. so you will need to click ‘Allow’ to proceed with the installation.1 Introduction The Selenium-IDE (Integrated Development Environment) is the tool you use to develop your Selenium test cases. It’s an easy-to-use Firefox plug-in and is generally the most efﬁcient way to develop test cases. 4.2 Installing the IDE Using Firefox. but also an excellent way of learning Selenium script syntax. as shown in the following screenshot. 15 . download the IDE from the SeleniumHQ downloads page Firefox will protect you from installing addons from unfamiliar locations.CHAPTER FOUR SELENIUM-IDE 4. This is not only a time-saver.. ﬁrst.
0 When downloading from Firefox. you’ll be presented with the following window.Selenium Documentation. Select Install Now. and when the 16 Chapter 4. Selenium-IDE . The Firefox Add-ons window pops up. Release 1. ﬁrst showing a progress bar.
0 download is complete. After Firefox reboots you will ﬁnd the Selenium-IDE listed under the Firefox Tools menu.2. Restart Firefox. Installing the IDE 17 .Selenium Documentation. Release 1. 4. displays the following.
Selenium Documentation.3 Opening the IDE To run the Selenium-IDE. 18 Chapter 4. or creating new test cases. It opens as follows with an empty script-editing window and a menu for loading.0 4. Selenium-IDE . simply select it from the Firefox Tools menu. Release 1.
open.1 Menu Bar The File menu allows you to create. paste. is the record button. IDE Features 19 . including a step feature for debugging your test cases. the one with the red-dot. and specify the format (language) used when saving your test cases. The Help menu is the standard Firefox Help menu. Release 1. 4. The Options menu allows the changing of settings. The right-most button. and select all operations for editing the commands in your test case. add user-deﬁned user extensions to the base set of Selenium commands. delete. and save test case and test suite ﬁles.Selenium Documentation.0 4.2 Toolbar The toolbar contains buttons for controlling the execution of your test cases.4. You can set the timeout value for certain commands. undo.4. The Edit menu allows copy. 4. only one item on this menu–UI-Element Documentation–pertains to Selenium-IDE.4.4 IDE Features 4.
Release 1. The other tab . When only a single test is loaded this button and the Run All button have the same effect. Record: Records the user’s browser actions.4. The ﬁrst parameter speciﬁed for a command in the Reference tab of the bottom pane always goes in the Target ﬁeld. it always goes in the Value ﬁeld. Run: Runs the currently selected test. These are entry ﬁelds where you can modify the currently selected command. Apply Rollup Rules: This advanced feature allows repetitive sequences of Selenium commands to be grouped into a single action. See the Options menu for details.Selenium Documentation. Run All: Runs the entire test suite when a test suite with multiple test cases is loaded. Step: Allows you to “step” through a test case by running it one command at a time. Most users will probably not need this button. cut and paste operations. By default. If a second parameter is speciﬁed by the Reference tab. The TestRunner is not commonly used now and is likely to be deprecated. Detailed documentation on rollup rules can be found in the UI-Element Documentation on the Help menu. The Command.0 Speed Control: controls how fast your test case runs. Selenium-IDE .Source displays the test case in the native format in which the ﬁle will be stored. Use for debugging test cases.3 Test Case Pane Your script is displayed in the test case pane. and Value entry ﬁelds display the currently selected command along with its parameters. or a scripting language like Python. The Source view also allows one to edit the test case in its raw form. including copy. one for displaying the command and their parameters in a readable “table” format. 20 Chapter 4. this is HTML although it can be changed to a programming language such as Java or C#. TestRunner Mode: Allows you to run the test case in a browser loaded with the Selenium-Core TestRunner. Target. It has two tabs. Pause/Resume: Allows stopping and re-starting of a running test case. 4. This button is for evaluating test cases for backwards compatibility with the TestRunner.
Log When you run your test case. 4. whether from Table or Source mode. a drop-down list will be populated based on the ﬁrst characters you type. If there is a mismatch in any of these three areas. the command will not run correctly.4. and Rollup– depending on which tab is selected. it is still often necessary to consult the Selenium Reference document. the Reference pane will display documentation on the current command. These messages are often useful for test case debugging. Also notice the Info button is a drop-down allowing selection of different levels of information to log. IDE Features 21 . 4.0 If you start typing in the Command ﬁeld. Reference The Reference tab is the default selection whenever you are entering or modifying Selenese commands and parameters in Table mode. UI-Element. it is critically important to ensure that the parameters speciﬁed in the Target and Value ﬁelds match those speciﬁed in the parameter list in the Reference pane.4 Log/Reference/UI-Element/Rollup Pane The bottom pane is used for four different functions–Log. error messages and information messages showing the progress are displayed in this pane automatically. even if you do not ﬁrst select the Log tab. the order of parameters provided must match the order speciﬁed. When entering or modifying commands. Release 1. Reference. In Table mode. While the Reference tab is invaluable as a quick reference. The number of parameters provided must match the number speciﬁed. Notice the Clear button for clearing the Log.4.Selenium Documentation. you can then select your desired command from the drop-down. and the type of parameters provided must match the type speciﬁed.
there may only be one Selenium command listed. With Selenium-IDE recording. Now.. This will cause unexpected test case failures. Typically.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. this will include: • clicking a link . Selenium-IDE will automatically insert commands into your test case based on your actions. Let’s see how this works. Here we’ll simply describe how to add them to your test case. Otherwise.5 Building Test Cases There are three primary methods for developing test cases. 22 Chapter 4.type command • selecting options from a drop-down listbox .2 Adding Veriﬁcations and Asserts With the Context Menu Your test cases will also need to check the properties of a web-page. 4. • Following a link usually records a click command.0 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. your test case will continue running commands before the page has loaded all its UI elements. 4. the record button is ON by default. When Selenium-IDE is ﬁrst opened. You will often need to change this to clickAndWait to ensure your test case pauses until the new page is completely loaded. and deselecting “Start recording immediately on open. Frequently.1 Recording Many ﬁrst-time users begin by recording a test case from their interactions with a website. You will see a context menu showing verify and/or assert commands. This requires assert and verify commands. Selenium-IDE . We won’t describe the speciﬁcs of these commands here.select command • clicking checkboxes or radio buttons .Selenium Documentation.click or clickAndWait commands • entering values . If you do not want Selenium-IDE to begin recording automatically you can turn this off by going under Options > Options. a test developer will require all three techniques. you will need for a selected UI element on the current web-page. along with the parameters. The ﬁrst time you use Selenium. Selenium-IDE will attempt to predict what command.5.5. that is in the chapter on “Selenese” Selenium Commands..” During recording. Open a web-page of your choosing and select a block of text on the page. A paragraph or a heading will work ﬁne. The context menu should give you a verifyTextPresent command and the suggested parameter should be the text itself. you will ﬁnd additional commands will quickly be added to this menu. right-click the selected text. 4. go to the browser displaying your test application and right click anywhere on the page. Release 1. As you use the IDE however.
left-click on the line where you want to insert a new command. just create empty comments. 4. for testing your currently selected UI element. left-click between the commands where you want to insert a new command. Your comment will appear in purple font. Release 1. if one is required). Once you select these other options. To do this. You can learn a lot about the Selenium commands simply by experimenting with the IDE. many more commands. in the Test Case Pane. You may need to use Show All Available Commands to see options other than verifyTextPresent. or a user control like a button or a checkbox. the more commonly used ones will show up on the primary context menu. For example. Now use the command editing text ﬁelds to enter your new command and its parameters. again.5. These comments are ignored when the test case is run. notice the Show All Available Commands menu option. <!-. the IDE will add a blank line just ahead of the line you selected. Source View Select the point in your test case where you want to insert the comment. Insert Comment Comments may be added to make your test case more readable. Table View Select the line in your test case where you want to insert the comment. i. Source View Select the point in your test case where you want to insert the command. Try a few more UI elements. and second parameter (again. This shows many. Try right-clicking an image. 4. feel free to use the IDE to record and select commands into a test case and then run it. Right-click and select Insert Comment. Comments may also be used to add vertical white space (one or more blank lines) in your tests.5. these commands will be explained in detail in the chapter on Selenium commands.. Add an HTML-style comment.your comment here -->. selecting verifyElementPresent for an image should later cause that command to be available on the primary context menu the next time you select an image and right-click. in the Test Case Pane. Building Test Cases 23 .e. Now use the Command ﬁeld to enter the comment. an empty comment won’t. Again. To do this. and enter the HTML tags needed to create a 3-column row containing the Command.0 Also. An empty command will cause an error during execution. For now though. Be sure to save your test before switching back to Table view. ﬁrst parameter (if one is required by the Command).3 Editing Insert Command Table View Select the point in your test case where you want to insert the command.Selenium Documentation. along with suggested parameters. Right-click and select Insert Command.
Run a Test Case Click the Run button to run the currently displayed test case. You can run a test case all at once. Target. and you can do a batch run of an entire test suite.5. If the test cases of your test suite have not been saved. simply modify which line you wish– command.portal.7 Using Base URL to Run Test Cases in Different Domains The Base URL ﬁeld at the top of the Selenium-IDE window is very useful for allowing test cases to be run across different domains.Selenium Documentation. right-click. This is useful for debugging your test case. Start from the Middle You can tell the IDE to begin running from a speciﬁc command in the middle of the test case.0 Edit a Command or Comment Table View Simply select the line to be changed and edit it using the Command. there are Save and Open commands under the File menu. To set a breakpoint. Source View Since Source view provides the equivalent of a WYSIWYG editor. This is also available from the context menu. Run Any Single Command Double-click any single command to run it by itself. Suppose that a site named. To set a startpoint. Stop and Start The Pause button can be used to stop the test case while it is running. Stop in the Middle You can set a breakpoint in the test case to cause it to stop on a particular command. and from the context menu select Toggle Breakpoint. parameter. you’ll be prompted to save them before saving the test suite. Release 1. When you open an existing test case or suite. This also is used for debugging. This is useful when writing a single command. 4. Selenium distinguishes between test cases and test suites. Selenium-IDE displays its Selenium commands in the Test Case Pane. or save the test suite. select a command. select a command. It lets you immediately test a command you are constructing. and from the context menu select Set/Clear Start Point.6 Running Test Cases The IDE allows many options for running your test case. The icon of this button then changes to indicate the Resume button. right-click. and Value ﬁelds. run a single command you are currently developing. run it one line at a time. Selenium-IDE . Run a Test Suite Click the Run All button to run all the test cases in the currently loaded test suite. 4. To save your Selenium-IDE tests for later use you can either save the individual test cases. stop and start it.4 Opening and Saving a Test Case Like most programs. To continue click Resume. You can double-click it to see if it runs correctly. when you are not sure if it is correct. However. Execution of test cases is very ﬂexible in the IDE. or comment. 4.com had an in-house beta 24 Chapter 4.
html: This same test case with a modiﬁed. That is. Release 1. Selenium-IDE will then create an absolute URL by appending the open command’s argument onto the end of the value of Base URL.0 site named. We won’t teach debugging here as most new users to Selenium will already have some basic experience with debugging. the test case below would be run against. However.1 Breakpoints and Startpoints The Sel-IDE supports the setting of breakpoints and the ability to start and stop the running of a test case.8. Debugging 25 . right-click.com/about. For example. This is a normal part of test case development.8 Debugging Debugging means ﬁnding and ﬁxing errors in your test case. Any test cases for these sites that begin with an open statement should specify a relative URL as the argument to open rather than an absolute URL (one starting with a protocol such as http: or https:). from any point within the test case.com/about. For example. select a command.Selenium Documentation. suppose your test case ﬁrst logs into the website and then performs a series of tests and you are trying to debug one of those tests. and from the context menu select Toggle Breakpoint.news.portal. we recommend you ask one of the developers in your organization.8.portal. It is also sometimes useful to run a test case from somewhere in the middle to the end of the test case or up to a breakpoint that follows the starting point.html: Base URL setting would be run against 4.portal. If this is new to you. To set a breakpoint.com. Then click the Run button to run your test case from the beginning up to the breakpoint. one can run up to a speciﬁc command in the middle of the test case and inspect how the test case behaves at that point. 4. To do this.news. you 4. set a breakpoint on the command just before the one to be examined.
among others.8.8. Simply right-click the webpage and select ‘View->Page Source. 4. with highlighting on the portion representing your selection. You can login once. The HTML opens in a separate window. select a command. It can be used with any command that identiﬁes a UI element on a webpage.5 Locator Assistance Whenever Selenium-IDE records a locator-type argument. the separate HTML window will contain just a small amount of source. 1.2 Stepping Through a Testcase To execute a test case one command at a time (“step through” it). type. Immediately pause the executing test case with the Pause button.8. To set a startpoint. when debugging a test case. Then rightclick the webpage and select View Selection Source. Alternatively. i. you simply must look at the page source (the HTML for the webpage you’re trying to test) to determine a problem. select just that portion of the webpage for which you want to see the source. clickAndWait. This feature can be 26 Chapter 4. then run your test case from a startpoint placed after the login portion of your test case. click. Repeatedly select the Step button.Selenium Documentation.e. follow these steps: 1.3 Find Button The Find button is used to see which UI element on the currently displayed webpage (in the browser) is used in the currently selected Selenium command.0 only need to login once. 4. In this case. select any command that has a locator parameter. Use its Search feature (Edit=>Find) to search for a keyword to ﬁnd the HTML for the UI element you’re trying to test. right-click. From Table view. 4.8. Click the Find button. Start the test case running with the Run button from the toolbar. it stores additional information which allows the user to view other possible locator-type arguments that could be used instead. and certain assert and verify commands. Firefox makes this easy. 1. Now look on the webpage: There should be a bright green rectangle enclosing the element speciﬁed by the locator parameter. Release 1. Then click the Run button to execute the test case beginning at that startpoint. but you need to keep rerunning your tests as you are developing them.4 Page Source for Debugging Often. That will prevent you from having to manually logout each time you rerun your test case. and from the context menu select Set/Clear Start Point. Selenium-IDE . 4. This is useful when building a locator for a command’s ﬁrst parameter (see the section on locators in the Selenium Commands chapter).
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). Writing a Test Suite 27 . the new test case will appear immediately below the previous test case. and is often needed to help one build a different type of locator than the type that was recorded. The test suite pane can be manually opened or closed via selecting a small dot halfway down the right edge of the pane (which is the left edge of the entire Selenium-IDE window if the pane is closed).Selenium Documentation. 4. Users who want to create or modify a test suite by adding pre-existing test cases must manually edit a test suite ﬁle. A test suite ﬁle is an HTML ﬁle containing a one-column table.0 very useful for learning more about locators. Selenium-IDE does not yet support loading pre-existing test cases into a test suite. Release 1. Below is a snapshot showing the contents of this drop-down for one command. In the latter case. The example below is of a test suite containing four test cases: 4.9 Writing a Test Suite A test suite is a collection of test cases which is displayed in the leftmost pane in the IDE. Note that the ﬁrst column of the drop-down provides alternative locators. whereas the second column indicates the type of each alternative. Each cell of each row in the <tbody> section contains a link to a test case. The test suite pane will be automatically opened when an existing test suite is opened or when the user selects the New Test Case item from the File menu.9.
look at the page created by its author. put the pathname to its location on your computer in the Selenium Core extensions ﬁeld of Selenium-IDE’s Options=>Options=>General tab./c. However.html" >D Links</a></td></tr> </tbody> </table> </body> </html> Note: Test case ﬁles should not have to be co-located with the test suite ﬁle that invokes them.html" >B Links</a></td></tr> <tr><td><a href= ".Selenium Documentation.html" >A Links</a></td></tr> <tr><td><a href= ". Perhaps the most popular of all Selenium-IDE extensions is one which provides ﬂow control in the form of while loops and primitive conditionals. There are a number of useful extensions created by users. Often this is in the form of customized commands although this extensibility is not limited to additional commands. a bug prevents Windows users from being able to place the test cases elsewhere than with the test suite that invokes them.html" >C Links</a></td></tr> <tr><td><a href= ". 28 Chapter 4./b. Selenium-IDE . Release 1. For an example of how to use the functionality provided by this extension.10 User Extensions User extensions are JavaScript ﬁles that allow one to create his or her own customizations and features to add additional functionality. charset=UTF-8" > <title>Sample Selenium Test Suite</title> </head> <body> <table cellpadding= "1" cellspacing= "1" border= "1" > <thead> <tr><td>Test Cases for De Anza A-Z Directory Links</td></tr> </thead> <tbody> <tr><td><a href= ".0 <html> <head> <meta http-equiv= "Content-Type" content= "text/html. This extension is the goto_sel_ide. at the time of this writing. 4.js. that is indeed the case. To install this extension./d./a. And on Mac OS and Linux systems.
4. for more information. Your test case will be translated into a series of functions in the language you choose.12 Executing Selenium-IDE Tests on Different Browsers While Selenium-IDE can only run tests against Firefox.11. allows you to select a language for saving and displaying the test case. Essentially.0 After selecting the OK button. This topic is covered in the Run Selenese tests section on Selenium-RC chapter.11 Format Format. See issue 1008. This message can be occasionally displayed in the Table tab when Selenium IDE is launched.e. using a simple command-line interface that invokes the Selenium-RC server. The workaround is to close and reopen Selenium IDE. Also. The -htmlSuite command-line option is the particular feature of interest.13 Troubleshooting Below is a list of image/explanation pairs which describe frequent sources of problems with SeleniumIDE: Table view is not available with this format. If you are able to reproduce this reliably then please provide details so that we can work on a ﬁx.Selenium Documentation. The default is HTML. See issue 1010. you must close and reopen Selenium-IDE in order for the extensions ﬁle to be read. PHP. Release 1. Each supported language has conﬁguration settings which are editable. Information on writing your own extensions can be found near the bottom of the Selenium Reference document. This is under the Options=>Options=>Format tab. Java. this feature is used to translate your test case into a programming language. i. Note: At the time of this writing. An enhancement request has been raised to improve this error message. Select the language. error loading test case: no command found You’ve used File=>Open to try to open a test suite ﬁle. Use File=>Open Test Suite instead. Format 29 . you will be using with Selenium-RC for developing your test programs. Then simply save the test case using File=>Save. program code supporting your test is generated for you by Selenium-IDE. If you will be using Selenium-RC to run your test cases. note that if the generated code does not suit your needs. 4. this feature is not yet supported by the Selenium developers. 4. tests developed with Selenium-IDE can be run against other browsers. Any change you make to an extension will also require you to close and reopen SeleniumIDE. 4. However the author has altered the C# format in a limited manner and it has worked well. under the Options menu. you can alter it by editing a conﬁguration ﬁle which deﬁnes the generation process.
“Component returned failure code: 0x80520012 (NS_ERROR_FILE_NOT_FOUND) [nsIFileInputStream. An enhancement request has been raised to improve this error message. Whenever your attempt to use variable substitution fails as is the case for the open command above.init]” nresult: “0x80520012 (NS_ERROR_FILE_NOT_FOUND)” location: “JS frame :: chrome://selenium-ide/content/ﬁleutils.js :: anonymous :: line 48” data: no] One of the test cases in your test suite cannot be found.. Also. See issue 1011. 30 Chapter 4.0 This type of error may indicate a timing problem. investigate using an appropriate waitFor* or *AndWait command before the failing command. Try putting a pause 5000 before the command to determine whether the problem is indeed related to timing. the element speciﬁed by a locator in your command wasn’t fully loaded when the command was executed.html extension both in their ﬁlenames. make sure that your actual test case ﬁles have the . it indicates that you haven’t actually created the variable whose value you’re trying to access.. If so. i. Selenium-IDE is very space-sensitive! An extra space before or after a command will cause it to be unrecognizable. Release 1. Make sure that the test case is indeed located where the test suite indicates it is located. the ﬁrst required parameter must go in the Target ﬁeld. the two parameters for the store command have been erroneously placed in the reverse order of what is required. In the example above. and in the test suite ﬁle where they are referenced.e.Selenium Documentation.. This is sometimes due to putting the variable in the Value ﬁeld when it should be in the Target ﬁeld or vice versa. error loading test case: [Exception. For any Selenese command. Selenium-IDE . and the second required parameter (if one exists) must go in the Value ﬁeld.
Selenium Documentation. In the example above. Thus. However. Selenium-IDE is correct to generate an error.0 This defect has been raised. This type of error message makes it appear that Selenium-IDE has generated a failure where there is none. See issue 1013. Release 1. This defect has been raised. Be sure you have speciﬁed the proper pathname to the extensions ﬁle via Options=>Options=>General in the Selenium Core extensions ﬁeld. which is confusing. but is misleading in the nature of the error. See issue 1012. Selenium-IDE must be restarted after any change to either an extensions ﬁle or to the contents of the Selenium Core extensions ﬁeld. note that the parameter for verifyTitle has two spaces between the words “Selenium” and “web” The page’s actual title has only one space between these words. Selenium-IDE is correct that the actual value does not match the value speciﬁed in such test cases. 4. Also. Troubleshooting 31 . The problem is that the log ﬁle error messages collapse a series of two or more spaces into a single space.13. Your extension ﬁle’s contents have not been read by Selenium-IDE.
Selenium Documentation. Selenium-IDE . Release 1.0 32 Chapter 4.
you’ll probably want to abort your test case so that you can investigate the cause and ﬁx the issue(s) promptly. and the web designers frequently change the speciﬁc image ﬁle along with its position on the page. Here we explain those commands in detail.. an element is present somewhere on the page? 2. There’s very little point checking that the ﬁrst paragraph on the page is the correct one if your test has already failed when checking that the browser is displaying the expected page. If you’re not on the correct page. It is important that you understand these different methods because these methods deﬁne what you are actually testing. you are testing for the existence of an image on the home page.1. however. 5. Selenese allows multiple ways of checking for UI elements. the text and its position at the top of the page are probably relevant for your test. and we present the many choices you have in testing your web application when using Selenium. are the set of commands that run your tests. Effectively an “assert” will fail the test and abort the current test case. and start each group with an “assert” followed by one or more “verify” test commands. A sequence of these commands is a test script. you may want to check many attributes of a page without aborting the test case on the ﬁrst failure as this will allow you to review all failures on the page and take the appropriate action. 1. speciﬁc text is somewhere on the page? 3... whereas a “verify” will fail the test and continue to run the test case. On the other hand. For example. 5. An example follows: 33 . if you are testing a text heading.CHAPTER FIVE SELENIUM COMMANDS Selenium commands. will you test that. If.1 Verifying Page Elements Verifying UI elements on a web page is probably the most common feature of your automated tests. speciﬁc text is at a speciﬁc location on the page? For example. The best use of this feature is to logically group your test commands.
verifyElementPresent can be used to check the existence of any HTML tag within the page. 34 Chapter 5. Do not use this when you also need to test where the text occurs on the page. Command verifyElementPresent Target //div/p/img Value This command veriﬁes that an image. The test case then “asserts” the ﬁrst column in the second row of the ﬁrst table contains the expected value.3 Value Downloads Selenium IDE June 3.1 1. that the text string “Marketing Analysis” appears somewhere on the page currently being tested. and that it follows a <div> tag and a <p> tag.2 1.3 verifyElementPresent Use this command when you must test for the presence of a speciﬁc UI element. This veriﬁcation does not check the text.2 verifyTextPresent The command verifyTextPresent is used to verify speciﬁc text exists somewhere on the page. locators are explained in the next section. speciﬁed by the existence of an <img> HTML tag.Selenium Documentation. Use verifyTextPresent when you are interested in only the text itself being present on the page. 5.0 beta 2 The above example ﬁrst opens a page and then “asserts” that the correct page is loaded by comparing the title with the expected value. You can check the existence of links. divisions <div>. Selenium Commands . The ﬁrst (and only) parameter is a locator for telling the Selenese command how to ﬁnd the element. Here are a few more examples.2. etc. and only if this passed will the remaining cells in that row be “veriﬁed”. Release 1. For example: Command verifyTextPresent Target Marketing Analysis Value This would cause Selenium to search for.0 Command open assertTitle verifyText assertTable verifyTable verifyTable Target /download/ Downloads //h2 1. One common use is to check for the presence of an image. 5.2. rather then its content.. Only if this passes will the following command run and “verify” that the text is present in the expected location. is present on the page.1. It takes a single argument–the text pattern to be veriﬁed. paragraphs. Again.1. only the HTML tag. and verify. 2008 1.2. Locators are explained in the next section.
0 5. With this strategy.2 Locating Elements For many Selenium commands. This target identiﬁes an element in the content of the web application. The locator type can be omitted in many cases. For instance.2. a target is required. then the ﬁrst element with a name attribute matching the location will be used. Command verifyText Target //table/tr/td/div/p Value This is my text and it occurs right after the div inside the table. 5. 5. 5. the ﬁrst element with the id attribute value matching the location will be used.1. verifyText must use a locator.1 Locating by Identiﬁer This is probably the most common method of locating elements and is the catch-all default when no recognised locator type is used. Use this when you know an element’s id attribute. the identifier= in the ﬁrst three examples above is not necessary. and consists of the location strategy followed by the location in the format locatorType=location. 5.2 Locating by Id This type of locator is more limited than the identiﬁer locator type. but also more explicit.4 verifyText Use verifyText when both the text and its UI element must be tested. Locating Elements 35 .. The various locator types are explained below with examples for each. If no element has a matching id attribute.Selenium Documentation.2. If you choose an XPath or DOM locator.2. Release 1. you can verify that speciﬁc text appears at a speciﬁc location on the page relative to other UI components on the page.
the three types of locators above allow Selenium to test a UI element independent of its location on the page. 5. Selenium Commands .2. becomes very important.3 Locating by Name The name locator type will locate the ﬁrst element with a matching name attribute. Selenium users can leverage this powerful language to target elements in their web applications. Release 1. XPath extends beyond (as well as supporting) the simple methods of locating by id 36 Chapter 5. then you can use ﬁlters to further reﬁne your location strategy. You may or may not want to also test whether the page structure changes.. or really via any HTML property.Selenium Documentation. but its functionality must be regression tested. So if the page structure and organization is altered. If multiple elements have the same value for a name attribute. In the case where web designers frequently alter the page.2. the test will still pass. testing via id and name attributes. The default ﬁlter type is value (matching the value attribute).4 Locating by XPath XPath is the language used for locating nodes in an XML document.0 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> type= type= type= "password" /> "submit" value= "Login" /> "button" value= "Clear" /> • id=loginForm (3) 5. As HTML can be an implementation of XML (XHTML).
Input with attribute named ‘name’ and the value ‘continue’ and attribute named ‘type’ and the value ‘button’ • //form[@id=’loginForm’]/input[4] (7) . XPath locators can also be used to specify elements via attributes other than id and name. or relative to an element that does have an id or name attribute. You can use XPath to either locate the element in absolute terms (not advised).First input child element of the form element with attribute named ‘id’ and the value ‘loginForm’ • //input[@name=’continue’][@type=’button’] (7) .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) . Locating Elements 37 . 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. the following references are recommended: • W3Schools XPath Tutorial • W3C XPath Recommendation 5.The form element with attribute named ‘id’ and the value ‘loginForm’ • xpath=//form[input/\@name=’username’] (4) .First input element with attribute named ‘name’ and the value ‘username’ • //form[@id=’loginForm’]/input[1] (4) . and opens up all sorts of new possibilities such as locating the third checkbox on the page. it is not necessary to include the xpath= label when specifying an XPath locator.First form element with an input child element with attribute named ‘name’ and the value ‘username’ • //input[@name=’username’] (4) . Since only xpath locators start with “//”. One of the main reasons for using XPath is when you don’t have a suitable id or name attribute for the element you wish to locate.0 or name attributes. 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.2. but in order to learn more.) .Fourth input child element of the form element with attribute named ‘id’ and value ‘loginForm’ These examples cover some basics.Selenium Documentation. This is much less likely to change and can make your tests more robust. Release 1.
0 • XPath Tutorial .2. If two links with the same text are present.5 Locating Hyperlinks by Link Text This is a simple method of locating a hyperlink in your web page by using the text of the link.suggests XPath and can be used to test XPath results. Release 1. then the ﬁrst match will be used.with interactive examples. This location strategy takes JavaScript that evaluates to an element on the page. • Firebug .forms[0] (3) 38 Chapter 5. Selenium Commands . There are also a couple of very useful Firefox Add-ons that can assist in discovering the XPath of an element: • XPath Checker .2. it is not necessary to include the dom= label when specifying a DOM locator.6 Locating by DOM The Document Object Model represents an HTML document and can be accessed using JavaScript.Selenium Documentation.getElementById(’loginForm’) (3) • dom=document.html" >Continue</a> <a href= "cancel. 1 2 3 4 5 6 7 <html> <body> <p>Are you sure you want to do this?</p> <a href= "continue.html" >Cancel</a> </body> <html> • link=Continue (4) • link=Cancel (5) 5. 5. which can be simply the element’s location using the hierarchical dotted notation.XPath suggestions are just one of the many powerful features of this very useful add-on.forms[’loginForm’] (3) • dom=document. Since only dom locators start with “document”. 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> type= type= type= "password" /> "submit" value= "Login" /> "button" value= "Clear" /> • dom=document.
2.passfield (5) • css=#loginForm input[type="button"] (4) • css=#loginForm input:nth-child(2) (5) For more information about CSS Selectors. These Selectors can be used by Selenium as another locating strategy..forms[0].forms[0]. A good reference exists on W3Schools. 5.2.7 Locating by CSS CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents. Locating Elements 39 . CSS uses Selectors for binding style properties to elements in the document. Note: Most experienced Selenium users recommend CSS as their locating strategy of choice as it’s considerably faster than XPath and can ﬁnd the most complicated objects in an intrinsic HTML document.elements[0] (4) • document.username (4) • document. 5.2.elements[3] (7) You can use Selenium itself as well as other sites and extensions to explore the DOM of your web application.. Release 1.0 • document.forms[0]. 5.required[type="text"] (4) • css=input. See Locating by Identiﬁer.Selenium Documentation.elements[’username’] (4) • document.forms[0]. the best place to go is the W3C publication.
and exact. Patterns allow you to describe.. For example. 40 Chapter 5. a single character.1 Globbing Patterns Most people are familiar with globbing as it is utilized in ﬁlename expansion at a DOS or Unix/Linux command line such as ls *. link locators can utilize a pattern. Globbing is fairly limited. and verifyPrompt. Below is an example of two commands that use globbing patterns. However. globbing is used to display all the ﬁles ending with a . the click command will work even if the link text is changed to “Film & Television Department” or “Film and Television Department”.0 • Locators starting with “//” will use the XPath locator strategy.3 Matching Text Patterns Like locators. if the page’s owner should shorten the title to just “Film & Television Department. Examples of commands which require patterns are verifyTextPresent. the verifyTitle will pass as long as the two words “Film” and “Television” appear (in that order) anywhere in the page’s title. In this case.”. Command click verifyTitle Target link=glob:Film*Television Department glob:*Film*Television* Value The actual title of the page reached by clicking on the link was “De Anza Film And Television Department .c extension that exist in the current directory. 5. And as has been mentioned above. • Locators starting with “document” will use the DOM locator strategy. globbing includes a third special character. Release 1. [ ] (character class) which translates to “match any single character found inside the square brackets. The actual link text on the page being tested was “Film/Television Department”. There are three types of patterns: globbing. the ?. See Locating by XPath. However. regular expressions. Only two special characters are supported in the Selenium implementation: * which translates to “match anything. To specify a globbing pattern parameter for a Selenese command. nothing. or many characters. verifyAlert. The glob pattern’s asterisk will match “anything or nothing” between the word “Film” and the word “Television”.” i. verifyText.e. verifyTitle. patterns are a type of parameter frequently required by Selenese commands. you can also omit the label and specify just the pattern itself. Selenium globbing patterns only support the asterisk and character class. Selenium Commands .c.Selenium Documentation. See Locating by DOM 5. by using a pattern rather than the exact text.3. 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.Menu”. you can preﬁx the pattern with a glob: label. assertConﬁrmation. By using a pattern rather than the exact text. via the use of special characters. what text is expected rather than having to specify that text exactly. because globbing patterns are the default.” the test would still pass.
[] * + ? {1.* (“dot star”). regexp: [0-9]+ is a simple pattern that will match a decimal number of any length. and a host of tools. The former is case-sensitive.3. sed. Whereas Selenese globbing patterns support only the * and [ ] (character class) features.2 Regular Expression Patterns Regular expression patterns are the most powerful of the three types of patterns that Selenese supports. This two-character sequence can be translated as “0 or more occurrences of any character” or more simply.3. For example. Matching Text Patterns 41 .Selenium Documentation. Below are a subset of those special characters: PATTERN . The ﬁrst one uses what is probably the most commonly used regular expression pattern–.” It is the equivalent of the one-character globbing pattern * (a single asterisk).yahoo.com/forecast/USAK0012.2}:[0-9]{2} [ap]m Value Let’s examine the regular expression above one part at a time: Sunrise: * [0-9]{1. Regular expressions are also supported by most high-level programming languages. Command click verifyTitle Target link=regexp:Film. A few examples will help clarify how regular expression patterns can be used with Selenese commands.*Film. regular expression patterns allow a user to perform many tasks that would be very difﬁcult otherwise. Alaska contains info on the sunrise time: Command open verifyTextPresent Target. and awk.* Value The example above is functionally equivalent to the earlier example that used globbing patterns for this same test. the latter is case-insensitive. including the Linux/Unix command-line utilities grep. In Selenese.html regexp:Sunrise: *[0-9]{1. The only differences are the preﬁx (regexp: instead of glob:) and the “anything or nothing” pattern (. many text editors. Release 1. Selenese regular expression patterns offer the same wide array of special characters that exist in JavaScript.* instead of just *). The more complex example below tests that the Yahoo! Weather page for Anchorage.0 5. “anything or nothing.*Television.*Television Department regexp:.
This happens because Selenium will reach the AndWait‘s timeout without seeing any navigation or refresh being made. select //select glob:Real * In order to ensure that the “Real *” item would be selected. as waitForElementPresent or waitForVisible. The best approach would be to wait for the needed element in a dynamic period and then continue the execution as soon as the element is found. It uses no special characters at all.6 Sequence of Evaluation and Flow Control When a script runs. Pausing the test execution for a certain period of time is also not a good approach as web element might appear later or earlier than the stipulated period depending on the system’s responsiveness. 5. data is retrieved from server without refreshing the page.).g. while the AndWait alternative (e.4 The “AndWait” Commands The difference between a command and its AndWait alternative is that the regular command (e. if you needed to look for an actual asterisk character (which is special for both globbing and regular expression patterns). So. 42 Chapter 5. The AndWait alternative is always used when the action causes the browser to navigate to another page or reload the present one. one command after another. For example. This is done using waitFor commands.0 5. which wait dynamically. 5. if there was an earlier select option labeled “Real Numbers. Thus. 5. if you wanted to select an item labeled “Real *” from a dropdown. it simply runs in sequence. your test will fail. The asterisk in the glob:Real * pattern will match anything or nothing. So.5 The waitFor Commands in AJAX applications In AJAX driven web applications. causing Selenium to raise a timeout exception. load or other uncontrolled factors of the moment. Using andWait commands will not work as the page is not actually refreshed.3.3 Exact Patterns The exact type of Selenium pattern is of marginal usefulness.” it would be the option selected rather than the “Real *” option. globbing patterns and regular expression patterns are sufﬁcient for the vast majority of us.g. if you use an AndWait command for an action that does not trigger a navigation/refresh. the following code might work or it might not. Release 1. Be aware. clickAndWait) tells Selenium to wait for the page to load after the action has been done. checking for the desired condition every second and continuing to the next command in the script as soon as the condition is met. click) will do the action and continue with the following command as fast as it can. leading to test failures. the exact pattern would be one way to do that.Selenium Documentation. Selenium Commands .
However. programming logic is often needed. Install the goto_sel_ide. Here are a couple more commonly used store commands. consider a JavaScript snippet or the goto_sel_ide. Selenium variables can be used to store values passed to your test program from the command-line. A Selenium variable may also be used within a locator expression.) or iteration (for. The plain store command is the most basic of the many store commands and can be used to simply store a constant value in a selenium variable. An equivalent store command exists for each verify and assert command. 5. Most testers will export the test script into a programming language ﬁle that uses the Selenium-RC API (see the Selenium-IDE chapter).). Command store Target paul@mysite. 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. If this is your case. the text value to be stored and a selenium variable. It takes two parameters. does not support condition statements (if-else. Use the standard variable naming conventions of only alphanumeric characters when choosing a name for your variable. However. It simply stores a boolean value–“true” or “false”–depending on whether the UI element is found. enclose the variable in curly brackets ({}) and precede it with a dollar sign like this. when they have many junior-level people running tests for them. some organizations prefer to run their scripts from SeleniumIDE whenever possible (for instance. possibly involving multiple pages. while. 3.js extension. 5.0 Selenese. for a functional test of dynamic content. from another program. by itself. you’ll want to use the stored value of your variable. when combined with a data-driven test design (discussed in a later section).org Value userName Later in your script. Command verifyText Target //div/p Value ${userName} A common use of variables is for storing input for an input ﬁeld. or when programming skills are lacking). Store Commands and Selenium Variables 43 . Release 1. Many useful tests can be conducted without ﬂow control.7 Store Commands and Selenium Variables You can use Selenium variables to store constants at the beginning of a script. Also. or from a ﬁle. When ﬂow control is needed. there are three options: 1.Selenium Documentation. Run a small JavaScript snippet from within the script using the storeEval command. Run the script using Selenium-RC and a client library such as Java or PHP to utilize the programming language’s ﬂow control features.js extension.7. etc. 5. To access the value of a variable. etc.7.1 storeElementPresent This corresponds to verifyElementPresent. 2.
special syntax is required–the JavaScript snippet must be enclosed inside curly braces and preceded by the label javascript. and waitForEval. even when the parameter is not speciﬁed to be of type script.1 JavaScript Usage with Script Parameters Several Selenese commands specify a script parameter including assertEval. It uses a locater to identify speciﬁc page text..7.3 storeEval This command takes a script as its ﬁrst parameter. you must refer to it as storedVars[’yourVariableName’].7. normally the Target ﬁeld (because a script parameter is normally the ﬁrst or only parameter). The text. A Selenium-IDE user would simply place a snippet of JavaScript code into the appropriate ﬁeld. An associative array has string indexes rather than sequential numeric indexes. as in javascript {*yourCodeHere*}. The associative array containing your test case’s variables is named storedVars. StoreText can be used to extract text from the page being tested.8.8. if found. Selenium Commands .toUpperCase() storedVars[’name’].0 5. in this case the JavaScript String object’s toUpperCase method and toLowerCase method. 5. StoreEval allows the test to store the result of running the script in a variable.8 JavaScript and Selenese Parameters JavaScript can be used with two types of Selenese parameters: script and non-script (usually expressions). in this case. Embedding JavaScript within Selenese is covered in the next section. Release 1.Selenium Documentation. All variables created in your test case are stored in a JavaScript associative array. storeEval.2 JavaScript Usage with Non-Script Parameters JavaScript can also be used to help generate values for parameters.toLowerCase() Value name uc lc 5. These parameters require no special syntax. 5. However.2 storeText StoreText corresponds to verifyText. is stored in the variable. Whenever you wish to access or manipulate a variable within a JavaScript snippet. Command store storeEval storeEval Target Edith Wharton storedVars[’name’]. In most cases. Below is an example in which the type command’s second parameter value is generated via JavaScript code using this special syntax: 44 Chapter 5. verifyEval. you’ll want to access and/or manipulate a test case variable inside the JavaScript snippet used as a Selenese parameter. 5.
html" . echo .9." ). Finally. Username is ${userName} Value 5.windowName).toUpperCase()} 5. echo statements can be used to print the contents of Selenium variables. "Selenium" ). Release 1.childNodes[0].The Selenese Print Command 45 . output( "Alert is gone. } function open_window(windowName){ window. } </script> </head> <body> 5.nodeValue=resultText.getElementById( ’output’ ). Popups. } function show_prompt(){ var response = prompt( "What’s the best web QA tool?" . and Multiple Windows Suppose that you are testing a page that looks like this." ). This is useful for providing informational progress notes in your test which display on the console as your test is running." ). } } function show_alert(){ alert( "I’m blocking!" ). if (confirmation==true){ output( "Confirmed. These notes also can be used to provide context within your test result reports. Command echo echo Target Testing page footer now.0 Command store type Target league of nations q Value searchString javascript{storedVars[’searchString’]. } function show_confirm(){ var confirmation=confirm( "Chose an option.Selenium Documentation.10 Alerts.open( "newWindow.9 echo . } else{ output( "Rejected!" ). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <!DOCTYPE HTML> <html> <head> <script type= "text/javascript" > function output(resultText){ document. output(response).
You’ll notice that after you close the alert the text “Alert is gone. Release 1. Alerts. it is helpful to understand the commonality between them.Selenium Documentation.” But this is Selenium-IDE handling and closing the alert for you. Value You may be thinking “Thats odd. and verify the text is added after you close the alert.” is displayed on the page. Selenium can cover JavaScript pop-ups. JavaScript pop-ups will not appear. This will return true or false. Your test will look something like this: Command open click assertAlert verifyTextPresent Target / btnAlert I’m blocking Alert is gone. You must include an assertion of the alert to acknowledge it’s presence. If you just want to assert that an alert is present but either don’t know or don’t care what text it contains. However. Fortunately. with false halting the test. you can use assertAlertPresent.] 5. 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. But before we begin covering alerts/conﬁrms/prompts in individual detail. If you remove that step and replay the test you will get the following error [error] Error: There was an unexpected Alert! [I’m blocking!]. Now run through the same steps with Selenium IDE recording. you must call it’s assertFoo(pattern) function. open the HTML sample above in a browser and click on the “Show alert” button.0 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. as well as moving focus to newly opened popup windows. To handle a pop-up. To begin. I never tried to assert that alert. just because you cannot see the pop-up doesn’t mean you don’t have do deal with it. This is because the function calls are actually being overridden at runtime by Selenium’s own JavaScript. Selenium Commands ..10.1 Alerts Let’s start with asserts because they are the simplest pop-up to handle. 46 Chapter 5.
but click on the “Cancel” button in the popup. You may notice that you cannot replay this test. and Multiple Windows 47 . Rejected Value The chooseCancelOnNextConfirmation function tells Selenium that all following conﬁrmation should return false. However. Selenium can’t know that you’re cancelling before you open a conﬁrmation) Simply switch these two commands and your test will run ﬁne. Release 1.10. then assert the output text.2 Conﬁrmations Conﬁrmations behave in much the same way as alerts. This is because the order of events Selenium-IDE records causes the click and chooseCancelOnNextConﬁrmation to be put in the wrong order (it makes sense if you think about it.0 5. It can be reset by calling chooseOkOnNextConﬁrmation. Your test may look something like this: Command open click chooseCancelOnNextConﬁrmation assertConﬁrmation verifyTextPresent Target / btnConﬁrm Choose and option. with assertConfirmation and assertConfirmationPresent offering the same characteristics as their alert counterparts. Popups. Try recording clicking on the “Show conﬁrm box” button in the sample page. because Selenium complains that there is an unhandled conﬁrmation. by default Selenium will select OK when a conﬁrmation pops up.10.Selenium Documentation. 5. Alerts.
Release 1.Selenium Documentation. Selenium Commands .0 48 Chapter 5.
CHAPTER SIX SELENIUM-RC 6. we will describe how the components of Selenium-RC operate and the role each plays in running your test scripts. In the Adding Some Spice to Your Tests section.1 Introduction Selenium-RC is the solution for tests that need more than simple browser actions and linear execution. querying a database. all of them can be achieved by using programming techniques with a language-speciﬁc Selenium-RC client library. Selenium-RC uses the full power of programming languages to create more complex tests like reading and writing ﬁles. you’ll ﬁnd examples that demonstrate the advantages of using a programming language for your tests. You’ll want to use Selenium-RC whenever your test requires logic not supported by Selenium-IDE. 6. 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. What logic could this be? For example. Selenium-IDE does not directly support: • condition statements • iteration • logging and reporting of test results • error handling.2 How Selenium-RC Works First. and emailing test results. 49 .
intercepting and verifying HTTP messages passed between the browser and the AUT. Selenium-RC . Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands.0 6. Release 1.1 RC Components Selenium-RC components are: • The Selenium Server which launches and kills browsers... The browser. interprets and runs the Selenese commands passed from the test program. 50 Chapter 6.Selenium Documentation. using its JavaScript interpreter. Here is a simpliﬁed architecture diagram.2... and acts as an HTTP proxy.
you simply write a program that runs a set of Selenium commands using a client library API. Installation 51 . And. So to create a test program. This occurs when your test program opens the browser (using a client library API function).0 6. A Selenium client library provides a programming interface (API). you can generate the Selenium-RC code. and reports back to your program the results of running those tests. See the Selenium-IDE chapter for speciﬁcs on exporting RC code from Selenium-IDE.2. or possibly take corrective action if it was an unexpected error.e.3 Installation After downloading the Selenium-RC zip ﬁle from the downloads page. interprets them. The Selenium-IDE can translate (using its Export menu item) its Selenium commands into a client-driver’s API function calls.jar).1 Installing Selenium Server The Selenium-RC server is simply a Java jar ﬁle (selenium-server. you simply need to: • Install the Selenium-RC Server. These folders have all the components you need for using Selenium-RC with the programming language of your choice. 6. Release 1. The client library also receives the result of that command and passes it back to your program. optionally. if you already have a Selenese test script created in the SeleniumIDE. which run Selenium commands from your own program. The client library takes a Selenese command and passes it to the Selenium Server for processing a speciﬁc action or test against the application under test (AUT). 6. 6. you’ll notice it has several subfolders. Just downloading the zip ﬁle and extracting the server in the desired directory is sufﬁcient. There is a different client library for each supported language. actually a set of JavaScript functions which interprets and executes Selenese commands using the browser’s built-in JavaScript interpreter.2.3 Client Libraries The client libraries provide the programming support that allows you to run Selenium commands from a program of your own design. a set of functions.Selenium Documentation. Within each interface. Once you’ve chosen a language to work with.2 Selenium Server Selenium Server receives Selenium commands from your test program. which doesn’t require any special installation.3. Selenium-Core is a JavaScript program. i.. The Server receives the Selenese commands from your test program using simple HTTP GET/POST requests. • Set up a programming project using a language speciﬁc client driver. The RC server bundles Selenium Core and automatically injects it into the browser. there is a programming function that supports each Selenese command.3. This means you can use any programming language that can send HTTP requests to automate Selenium tests on the browser. Your program can receive the result and store it into a program variable and report it as a success or failure. 6.
4 Using the Python Client Driver • Download Selenium-RC from the SeleniumHQ downloads page • Extract the ﬁle selenium.3 Using the Java Client Driver • Download Selenium-RC from the SeleniumHQ downloads page.) • Create a new project.Selenium Documentation. • Extract the ﬁle selenium-java-client-driver. Release 1.5 or later). or TestNg to run your test. For details on Java test project conﬁguration.sh on Linux) containing the command above. java -jar selenium-server. • From Selenium-IDE. Then make a shortcut to that executable on your desktop and simply double-click the icon to start the server. export a script to a Java ﬁle and include it in your Java project.jar This can be simpliﬁed by creating a batch or shell executable ﬁle (.jar. 6. see the Appendix sections Conﬁguring Selenium-RC With Eclipse and Conﬁguring Selenium-RC With Intellij. NetBeans. • Execute your test from the Java IDE or from the command-line. • Add the selenium-java-client-driver. These concepts are explained later in this section.jar.py • Either write your Selenium test in Python or export a script from Selenium-IDE to a python ﬁle. • Add to your test’s path the ﬁle selenium.bat on Windows and . 6. etc. The API is presented later in this chapter. Netweaver. Selenium-RC . • Open your desired Java IDE (Eclipse. • Add to your project classpath the ﬁle selenium-java-client-driver.3. Go to the directory where Selenium-RC’s server is located and run the following from a command-line console.py 52 Chapter 6. For the server to run you’ll need Java installed and the PATH environment variable correctly conﬁgured to run it from the console.jar ﬁles to your project as references. or write your Selenium test in Java using the selenium-java-client API. or you can write your own simple main() program.3.0 6. You can either use JUnit. • Run Selenium server from the console. you’re ready to start using Selenium-RC.3. You can check that you have Java correctly installed by running the following on a console: java -version If you get a version number (which needs to be 1.2 Running Selenium Server Before starting any tests you must start the server. IntelliJ.
Selenium.Selenium Documentation.core. see the Selenium-Client documentation 6. • Run Selenium server from console • Run your test either from the IDE. If you’re not familiar yet with NUnit. VB.3. ThoughtWorks.IntegrationTests. These concepts are explained later in this chapter. Mini::Test or RSpec). ThoughtWorks.NET Client Driver • Download Selenium-RC from the SeleniumHQ downloads page • Extract the folder • Download and install NUnit ( Note: You can use NUnit as your test engine. or export a script from Selenium-IDE to a C# ﬁle and copy this code into the class ﬁle you just created.Net IDE (Visual Studio.NET client driver conﬁguration.dll.dll.dll and ThoughtWorks. 6. For details on Ruby client driver conﬁguration.dll.UnitTests. from the NUnit GUI or from the command line For speciﬁc details on . install it from RubyForge • Run gem install selenium-client • At the top of your test script. add require "selenium/client" • Write your test script using any Ruby test harness (eg Test::Unit.dll) • Add references to the following DLLs: nmock. MonoDevelop) • Create a class library (. 6. • Write your own simple main() program or you can include NUnit in your project for running your test.6 Using the Ruby Client Driver • If you do not already have RubyGems. nunit.dll.Selenium. see the appendix Python Client Driver Conﬁguration.0 • Run Selenium server from the console • Execute your test from a console or your Python IDE For details on Python client driver conﬁguration.3. SharpDevelop. you can also write a simple main() function to run your tests.3.Net language (C#. however NUnit is very useful as a test engine.5 Using the . see the appendix .Core. • Execute your test in the same way you would run any other Ruby script. nunit. • Run Selenium-RC server from the console. Installation 53 .) • Open your desired .dll • Write your Selenium test in a . framework.Selenium. Release 1.Net).NET client driver conﬁguration with Visual Studio.
Stop(). NUnit.1 Sample Test Script Let’s start with an example Selenese test script. "*firefox" .com 6. Imagine recording the following test with Seleniumopen / type q selenium rc IDE. [SetUp] public void SetupTest() { selenium = new DefaultSelenium( "localhost" . } catch (Exception) 54 Chapter 6.oriented programming language. private StringBuilder verificationErrors.Text.Start(). select one of these buttons. Selenium-RC .Text. In C#: using using using using using using System. To see an example in a speciﬁc language. System.Framework.2 Selenese as Programming Code Here is the test script exported (via Selenium-IDE) to each of the supported programming languages. 4444. namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium. } [TearDown] public void TeardownTest() { try { selenium. ". System.Selenium Documentation. Selenium.4. clickAndWait btnG assertTextPresent Results * for selenium rc Note: This example would work with the Google search page. System. 6. If you have at least basic knowledge of an object. In this section. Release 1.google.4 From Selenese to a Program The primary task for using Selenium-RC is to convert your Selenese into a programming language.0 6.Threading. selenium. you will understand how Selenium runs Selenese commands by reading one of these examples.4. verificationErrors = new StringBuilder().RegularExpressions. we provide several different language-speciﬁc examples.
selenium. } } } In Java: /** Add JUnit framework to your classpath if not already there * for this example to work / * package com.regex. verificationErrors.util. } [Test] public void TheNewTest() { selenium.google.type( "q" .AreEqual( "selenium rc .Selenium Documentation. Test::Exception. selenium. selenium. } } In Perl: use use use use use use strict.Type( "q" .thoughtworks.waitForPageToLoad( "30000" ).google.4.open( "/" ). import com.example. browser => "*firefox" .selenium.0 { // Ignore errors if unable to close the browser } Assert. 6. selenium.Open( "/" ).*. selenium. "*firefox" ). Time::HiRes qw( sleep ) .ToString()).WaitForPageToLoad( "30000" ). selenium.com/" . selenium. From Selenese to a Program 55 .Google Search" . assertTrue(selenium. Test::WWW::Selenium. import java.isTextPresent( "Results * for selenium rc" )). "selenium rc" ). Release 1.com/" ). my $sel = Test::WWW::Selenium->new( host => "localhost" .click( "btnG" ).tests.AreEqual( "" . } public void testNew() throws Exception { selenium. "selenium rc" ).GetTitle()). Assert. port => 4444. public class NewTest extends SeleneseTestCase { public void setUp() throws Exception { setUp( ". browser_url => ". warnings.Click( "btnG" ).Pattern. Test::More "no_plan" .
time. } function testMyTestCase() { $this->open( " / " ). " selenium rc " ).type( " q " . Release 1. $sel->click_ok( "btnG" ). class Example extends PHPUnit_Extensions_SeleniumTestCase { function setUp() { $this->setBrowser( " *firefox " ). In PHP: <?php require_once ’PHPUnit/Extensions/SeleniumTestCase.Selenium Documentation. $this->waitForPageToLoad( " 30000 " ). self.com/ " ) self.is_text_present( " Results * for selenium rc " )) def tearDown(self): self.php’ .open( " / " ) sel.selenium. $this->assertTrue($this->isTextPresent( " Results * for selenium rc " )).google.TestCase): def setUp(self): self.0 $sel->open_ok( "/" ). $this->setBrowserUrl( ". 4444.stop() self.failUnless(sel.click( " btnG " ) sel.com/ " ).start() def test_new(self): sel = self. $sel->wait_for_page_to_load_ok( "30000" ). " selenium rc " ) sel. ". $sel->is_text_present_ok( "Results * for selenium rc" ).wait_for_page_to_load( " 30000 " ) self. " *firefox " .verificationErrors = [] self.google.selenium = selenium( " localhost " . $sel->type_ok( "q" . $this->type( " q " . Selenium-RC .verificationErrors) 56 Chapter 6. } } ?> in Python: from selenium import selenium import unittest.selenium sel. $this->click( " btnG " ). re class NewTest(unittest.assertEqual([]. "selenium rc" ).selenium.
• Write a very simple main program that executes the generated code.start end @selenium.wait_for_page_to_load " 30000 " assert @selenium.stop unless $selenium assert_equal []. @verification_errors end def test_new @selenium.0 in Ruby: require " selenium " require " test/unit " class NewTest < Test::Unit::TestCase def setup @verification_errors = [] if $selenium @selenium = $selenium else @selenium = Selenium::SeleniumDriver.5. The language-speciﬁc APIs tend to differ from one to another.type " q " . Optionally. " *firefox " . " ht @selenium.is_text_present( " Results * for selenium rc " ) end end In the next section we’ll explain how to build a test program using the generated code.Selenium Documentation. Here.new( " localhost " . optionally modifying the result.open " / " @selenium.click " btnG " @selenium.set_context( " test_new " ) end def teardown @selenium. you can adopt a test engine platform like JUnit or TestNG for Java.5 Programming Your Test Now we’ll illustrate how to program your own tests using examples in each of the supported programming languages. 6. we show language-speciﬁc examples. There are essentially two tasks: • Generate your script into a programming language from Selenium-IDE. Programming Your Test 57 . or NUnit for . " selenium rc " @selenium. • Java • C# 6. so you’ll ﬁnd a separate explanation for each. Release 1. 4444.NET if you are using one of those languages.
If you are already a “java-shop” chances are your developers will already have some experience with one of these test frameworks. This example has comments added manually for additional clarity. "*iehta".com/" . "*firefox" ).Selenium Documentation. // We specify the package of our tests import com. Selenium-RC .isTextPresent( "Results * for selenium rc" )). selenium. You will probably want to rename the test class from “NewTest” to something of your own choosing. // This is the driver’s import. selenium. assertTrue(selenium.*.thoughtworks. You can remove the module if it’s not used in your // script.regex. ". people use either JUnit or TestNG as the test engine.waitForPageToLoad( "30000" ). // We instantiate and start the browser } public void testNew() throws Exception { selenium.0 • Python • Ruby • Perl.5.com/").google. 4444.util. "selenium rc" ). PHP 6. The Selenium-IDE generated code will look like this. Release 1.type( "q" .selenium.open( "/" ).Pattern. // These are the real test steps } } 58 Chapter 6. Some development environments like Eclipse have direct support for these via plug-ins. Teaching JUnit or TestNG is beyond the scope of this document however materials may be found online and there are publications available.click( "btnG" ).1 Java For Java. public class NewTest extends SeleneseTestCase { // We create our Selenium test case public void setUp() throws Exception { setUp( ". This makes it even easier.example. // Selenium-IDE add the Pattern module because it’s sometimes used for // regex validations. package com.google. Also. import java. You’ll use this for instantiating a // browser and making it do what you need. selenium. you will need to change the browser-open parameters in the statement: selenium = new DefaultSelenium("localhost".
com/" ). using using using using using using System. } [TearDown] public void TeardownTest() { try { selenium. you will need to change the browser-open parameters in the statement: selenium = new DefaultSelenium("localhost". NUnit.0 6. 4444. Selenium-IDE assumes you will use NUnit as your testing framework. private StringBuilder verificationErrors. System. You will probably have to rename the test class from “NewTest” to something of your own choosing. System.5. Release 1.Text. ". You can see this in the generated code below. namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium.NET.Selenium Documentation.NET Client Driver works with Microsoft.Text. verificationErrors = new StringBuilder().2 C# The .Threading.RegularExpressions. [SetUp] public void SetupTest() { selenium = new DefaultSelenium( "localhost" . } 6. 4444.com/"). Programming Your Test 59 . It includes the using statement for NUnit along with corresponding NUnit attributes identifying the role for each member function of the test class. "*iehta" . The generated code will look similar to this.google. It can be used with any . "*iehta". System.google.NET testing framework like NUnit or the Visual Studio 2005 Team System. selenium. Selenium. ". Also.Start().Framework.5.
// Assert that page title is . // Read the keyed search term and assert it. Release 1.GetTitle()).GetTitle()). re # This are the basic imports added by Selenium-IDE by default. Assert.IsTextPresent( "www. // Click on Search button. selenium.google. // Assert Title of page.Google Search" Assert. Selenium-RC . Assert. } } } You can allow NUnit to manage the execution of your tests.AreEqual( "Google" .Selenium Documentation.AreEqual( "Selenium OpenQA" . selenium. 60 Chapter 6.html>_.org/library/unittest.openqa. // Provide search term as "Selenium OpenQA" selenium. SetupTest(). you can write a simple main() program that instantiates the test object and runs each of the three methods. Or alternatively.Click( "btnG" ). Assert.WaitForPageToLoad( "5000" ). TheNewTest().org" )). // Assert that "( "q" .ToString()).5. time. selenium.GetValue( "q" )). selenium. "Selenium OpenQA" ). } [Test] public void TheNewTest() { // Open Google search engine. The basic test structure is: from selenium import selenium # This is the driver’s import.org" is available in search results.com/" ).AreEqual( "Selenium OpenQA .openqa. // Wait for page to load. selenium. You’ll use this class for instantiating a # browser and making it do what you need. 6.AreEqual( "" . selenium.Open( " catch (Exception) { // Ignore errors if unable to close the browser } Assert. and TeardownTest() in turn. verificationErrors. import unittest.python. To learn Pyunit refer to its ofﬁcial documentation <(selenium."Selenium OpenQA .3 Python Pyunit is the test framework to use for Python.Google Search" .
is_text_present( " Results * for selenium rc " )) # These are the real test steps def tearDown(self): self.verificationErrors) # And make the test fail if we found that any verification errors # were found 6.assertEqual([]. " selenium rc " ) sel. In fact.com/ " ) self.TestCase): # We create our unittest test case def setUp(self): self.type( " q " . " = selenium( " localhost " .0 # You can remove the modules if they are not used in your script.5.selenium" each time we want to call the browser). Release 1. Therefore.verificationErrors = [] # This is an empty array where we will store any verification errors # we find in our tests self. not the old Selenium gem. class NewTest(unittest.5.start() # We instantiate and start the browser def test_new(self): # This is the test code.google. Here you should put the actions you need # the browser to do during your test.failUnless(sel.wait_for_page_to_load( " 30000 " ) self. This is a problem because the ofﬁcial Ruby driver for Selenium is the Selenium-Client gem. it is advisable to update any Ruby scripts generated by the IDE as follows: 1. self. 4444.selenium. the Selenium gem is no longer even under active development.4 Ruby Selenium-IDE generates reasonable Ruby. but requires the old Selenium gem. sel. On line 11.new Selenium::SeleniumDriver.new to You probably also want to change the class name to something more informative than “Untitled. " *firefox " . as described 6.selenium.Selenium Documentation. sel = self. On line 1.selenium # We assign the browser to the variable "sel" (just to save us from # typing "self.stop() # we close the browser (I’d recommend you to comment this line while # you are creating and debugging your tests) self. change require "selenium" to require "selenium/client" 2. change Selenium::Client::Driver.open( " / " ) sel. Programming Your Test 61 .” and change the test method’s name to something other than “test_untitled.” Here is a simple example created by modifying the Ruby code generated by Selenium IDE.click( " btnG " ) sel.
0 above.start # Print a message in the browser-side log and status bar # (optional). :port => 4444. Ruby 1.8’s default test framework. # load the Selenium-Client gem require " selenium/client " # Load Test::Unit. assert_equal []. @verification_errors end # This is the main body of your test. require " test/unit " class Untitled < Test::Unit::TestCase # The setup method is called before each test. Selenium-RC . :timeout_in_second => 60 # Start the browser session @selenium. :browser => " *chrome " .Selenium Documentation.new \ :host => " localhost " . @verification_errors = [] # Create a new instance of the Selenium-Client driver.open " / " # Type ’selenium rc’ into the field named ’q’ @selenium. # If you prefer RSpec. def teardown # Stop the browser session.set_context( " test_untitled " ) end # The teardown method is called after each test. " selenium rc " # Click the button named "btnG" @selenium. @selenium. def setup # This array is used to capture errors and display them at the # end of the test run.type " q " . Release 1.google. def test_untitled # Open the root of the site we specified when we created the # new driver instance. :url => ". see the examples in the Selenium-Client # documentation. @selenium. if any. above.click " btnG " 62 Chapter 6.com/ " . @selenium = Selenium::Client::Driver.stop # Print the array of error messages. @selenium.
5. much of the interface will be self-explanatory. because that # was specified when we created the new driver instance. above.6. In Java: setUp( ". @verification_errors << $! end end end 6. we explain the most critical and possibly less obvious aspects. 4444. PHP The members of the documentation team have not used Selenium-RC with Perl or PHP. to support Perl and PHP users. # Notice that the star (*) is a wildcard that matches any # number of characters. Learning the API 63 . assuming you understand Selenese. "*firefox" ).Start(). Release 1. @selenium. 6. port => 4444. We would love to include some examples from you and your experiences.google. push it onto the array of errors. ". however.Selenium Documentation. Here.1 Starting the Browser In C#: selenium = new DefaultSelenium( "localhost" .com/" selenium. 6.is_text_present( " Results * for selenium rc " ) rescue Test::Unit::AssertionFailedError # If the assertion fails.5 Perl. 6.wait_for_page_to_load begin # Test whether the search results contain the expected text. "*firefox" .6 Learning the API The Selenium-RC API uses naming conventions that.com/" .0 # Wait for the search results page to load. If you are using Selenium-RC with either of these two languages please contact the Documentation Team (see the chapter on contributing).google. # Note that we don’t need to set a timeout here. In Perl: my $sel = Test::WWW::Selenium->new( host => "localhost" . assert @selenium.
4444. by using the locator and the string you speciﬁed during the method call. 64 Chapter 6. Release 1.google.google. In PHP: $this->setBrowser("*firefox"). " string to type " ) In the background the browser will actually perform a type operation. like open or type or the verify commands.com/"). " *firefox " .start Each of these examples opens the browser and represents that browser by assigning a “browser instance” to a program variable. " @selenium. This program variable is then used to call methods from the browser. " = selenium( " localhost " . so in this case localhost is passed. For example. Usually. Note that some of the client libraries require the browser to be started explicitly by calling its start() method.6. i.0 browser => "*firefox" . This is a required parameter. this is the same machine as where the client is running. In some clients this is an optional parameter. These methods execute the Selenium commands. to call the type method of the selenium object: selenium. $this->setBrowserUrl(". browser_url => " In Ruby: @selenium = Selenium::ClientDriver. This also is optional in some client drivers. 4444.2 Running Commands Once you have the browser initialized and assigned to a variable (generally named “selenium”) you can make it run Selenese commands by calling the respective methods from the browser variable.new( " localhost " . Selenium-RC . essentially identical to a user typing input into the browser. The parameters required when creating the browser instance are: host Speciﬁes the IP address of the computer where the server is located.com/" ). This is required by all the client libs and is integral information for starting up the browser-proxy-AUT communication. 6.com/ " ) self.Selenium Documentation.e. port Speciﬁes the TCP/IP socket where the server is listening waiting for the client to establish a connection. browser The browser in which you want to run the tests. url The base url of the application under test. " *firefox " .type( " field-id " .google. In Python: self.selenium.
4 Test Reporting Examples To illustrate. after the initial. we’ll direct you to some speciﬁc tools in some of the other languages supported by Selenium. Release 1.7. 6. 6.7. Test Reports in Java • If Selenium Test cases are developed using JUnit then JUnit Report can be used to generate test reports. learning curve you will naturally develop what works best for your own situation. along with their primary function of providing a ﬂexible test engine for executing your tests. The ones listed here are commonly used and have been used extensively (and therefore recommended) by the authors of this guide. Reporting Results 65 . 6.7. Refer to JUnit Report for speciﬁcs. Rather.7 Reporting Results Selenium-RC does not have its own mechanism for reporting results. but what if you simply want something quick that’s already done for you? Often an existing library or test framework can meet your needs faster than developing your own test reporting code. The TestNG framework generates an HTML report which list details of tests. We won’t teach the frameworks themselves here. it allows you to build your reporting customized to your needs using features of your chosen programming language. JUnit and TestNG.2 Test Report Libraries Also available are third-party libraries speciﬁcally created for reporting test results in your chosen programming language. That may gradually lead to you developing your own reporting. There are good books available on these test frameworks however along with information on the internet. These. • If Selenium Test cases are developed using TestNG then no external task is required to generate test reports.NET also has its own.Selenium Documentation. 6. 6. We will simply introduce the framework features that relate to Selenium along with some techniques you can apply.0 6. These often support a variety of formats such as HTML or PDF. That’s great. possibly in parallel to using a library or test framework. but short. . include library code for reporting results. NUnit. See TestNG Report for more. Java has two commonly used test frameworks.7. that’s beyond the scope of this user guide. Regardless.3 What’s The Best Approach? Most people new to the testing frameworks will being with the framework’s built-in reporting features.1 Test Framework Reporting Tools Test frameworks are available for many programming languages. From there most will examine any available libraries as that’s less time consuming than developing your own. For example.7. As you begin to use Selenium no doubt you will start putting in your own “print statements” for reporting progress.
Note: If you are interested in a language independent log of what’s going on. ReportNG provides a simple. Program ﬂow is controlled using condition statements and iteration. for a very nice summary report try using TestNG-xslt. You can do some conditions by embedding javascript in Selenese parameters. colour-coded view of the test results. Release 1. In this section we’ll show some examples of how programming language constructs can be combined with Selenium to solve common testing problems. See TestNG-xslt for more. Selenium-RC . the Selenium-IDE does not support iteration and standard condition statements. Test Reports for Python • When using Python Client Driver then HTMLTestRunner can be used to generate a Test Report. take a look at Selenium Server Logging 6. Please refer to Logging Selenium. Basically. • Also. In addition you can report progress information using I/O.8 Adding Some Spice to Your Tests Now we’ll get to the whole reason for using Selenium-RC. See ReportNG for more. Logging Selenium extends the Java client driver to add this Selenese logging ability. 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.0 • ReportNG is a HTML reporting plug-in for the TestNG framework. It’s the same as for any program. adding programming logic to your tests.Selenium Documentation. A TestNG-xslt Report looks like this. It is intended as a replacement for the default TestNG HTML report. See HTMLTestRunner. 66 Chapter 6. You will ﬁnd as you transition from the simple tests of the existence of page elements to tests of dynamic functionality involving multiple web-pages and varying data that you will require programming logic for verifying expected results. Refer to RSpec Report 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.
foreach (String s in arr) { sel. But multiple copies of the same code is not good program practice because it’s more work to maintain.type( "q" .. For example.waitForPageToLoad( "30000" ). Adding Some Spice to Your Tests 67 . In addition.8. "selenium " +s). A common problem encountered while running Selenium tests occurs when an expected element is not available on page. assertTrue( "Expected text: " +s+ " is missing on page. "rc" . sel. you may want to to execute a search multiple times.2 Condition Statements To illustrate using conditions in tests we’ll start with an example. // Execute loop for each String in array ’arr’." .0 however iteration is impossible. "grid" }. Using the same Google search example we used earlier.1 Iteration Iteration is one of the most common things people need to do in their tests.Selenium Documentation. Release 1.click( "btnG" ). 6.isTextPresent( "Results * for selenium " + s)). For example. let’s check the Selenium search results. perhaps for verifying your test results you need to process a “result set” returned from a database. String[] arr = { "ide" .8. we can iterate over the search results for a more ﬂexible and maintainable solution. In C#: // Collection of String values. although the code is simple and can be easily adapted to the other supported languages. you may need exception handling for error recovery. By using a programming language. For these reasons and others. and most conditions will be much easier in a programming language. we have written this section to illustrate the use of common programming techniques to give you greater ‘veriﬁcation power’ in your automated testing. when running the following line: 6. } 6. sel.open( "/" ). If you have some basic knowledge of an object-oriented programming language you shouldn’t have difﬁculty understanding this section.8. Or. The examples in this section are written in C# and Java. sel. sel.
// Create array in java scri script += "var cnt = 0. public static String[] getAllCheckboxIds () { String script = "var inputId = new Array(). In this case one could evaluate JavaScript from selenium RC to get ids of all check boxes and then exercise them. // Create array in java scrip script += "inputFields = window.getEval(script). If element ‘q’ is not on the page then an exception is thrown: com. String[] checkboxIds = selenium. 6.id ." + // Save check box id to inp "cnt++. "}" .id !=null " + "&& inputFields[i]. i<inputFields.thoughtworks." . // Counter for check box ids." + // increment the counter.type( "q" .3 Executing JavaScript from Your Test JavaScript comes very handy in exercising an application which is not directly supported by selenium.getAttribute(’type’) == ’checkbox’) {" . A better approach is to ﬁrst validate if the element is really present and then take alternatives when it it is not." ) } The advantage of this approach is to continue with test execution even if some UI elements are not available on page. // end of for. Release 1." )." .printf( "Element: " +q+ " is not available on page.SeleniumException: ERROR: Element q not found This can cause your test to abort." . Selenium-RC .0 selenium.length. script += "var inputFields = new Array(). "Selenium rc" ).8.getElementsByTagName(’input’). // Loop through the script += "if(inputFields[i]. } else { System.Selenium Documentation. "}" + // end of if. But often that is not desirable as your test script has many other subsequent tests to perform.// Convert array in to string.out. For some tests that’s what you want.id !=’undefined’ " + "&& inputFields[i]. i++) {" . script += "for(var i=0.toString().split( ". // If element is available on page then perform type operation.isElementPresent( "q" )) { selenium. Let’s look at this using Java. // If input fie script += "inputId[cnt]=inputFields[i]. script += "inputId. } To count number of images on a page: 68 Chapter 6. if(selenium.document.selenium. // Split the s return checkboxIds. "selenium " +s)." . The getEval method of selenium API can be used to execute JavaScript from selenium RC. Consider an application having check boxes with no static identiﬁers." .type( "q" .
jar To see the list of options.Selenium Documentation. command line options can be used to change the default server behaviour.length.proxyPort.jar -h You’ll see a list of all the options you can use with the server and a brief description of each. $ java -jar selenium-server.9.1 Proxy Conﬁguration If your AUT is behind an HTTP proxy which requires authentication then you should conﬁgure http.0 you can probably skip this section.9. $ java -jar selenium-server.0 selenium.document.0. Remember to use window object in case of DOM expressions as by default selenium window is referred to. http. the server is started by running the following.proxyPassword using the following command.getEval( "window. Release 1." ). Recall. http. prior to version 1.proxyHost=proxy.proxyHost.9. not the test window. Server Options 69 .proxyPort=8080 -Dhttp. so we’ve provided explanations for some of the more important options.com -Dhttp.proxyUser and http. The provided descriptions will not always be enough. since multiwindow mode is the default behavior.jar -Dhttp. 6.images. However.9 Server Options When the server is launched. Selenium by default ran the application under test in a sub frame as shown here. $ java -jar selenium-server.2 Multi-Window Mode If you are using Selenium 1. 6. 6. 6. run the server with the -h option.
Selenium-RC .0 Some applications didn’t run correctly in a sub frame. and needed to be loaded into the top frame of the window. 70 Chapter 6. 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. Release 1.Selenium Documentation.
Selenium Documentation, Release 1.0
6.9.3 Specifying the Firefox Proﬁle
Firefox will not run two instances simultaneously unless you specify a separate proﬁle for each instance. Selenium-RC 1.0 and later runs in a separate proﬁle automatically, so if you are using Selenium 1.0, you can probably skip this section. However,), you will need to explicitly specify the proﬁle. First, to create a separate Firefox proﬁle, follow this procedure. Open the Windows Start menu, select “Run”, then type and enter one of the following:
firefox.exe -profilemanager
6.9. Server Options
71
Selenium Documentation, Release 1.0
firefox.exe -P
Create the new proﬁle using the dialog. Then when you run Selenium Server,, regardless of whether they are proﬁle ﬁles or not. More information about Firefox proﬁles can be found in Mozilla’s Knowledge Base
6.9.jar -htmlSuite "*firefox" "" "c:\absolute
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 speciﬁed number of seconds for the test to complete; if the test doesn’t complete within that amount of time, the command will exit with a non-zero exit code and no results ﬁle.
6.9.5 Selenium Server Logging
Server-Side Logs When launching selenium server the -log option can be used to record valuable debugging information reported by the Selenium Server to a text ﬁle.
java -jar selenium-server.jar -log selenium.log
This log ﬁle is more verbose than the standard console logs (it includes DEBUG level logging messages). The log ﬁle
72
Chapter 6. Selenium-RC
Selenium Documentation, Release 1.0
TIMESTAMP(HH:mm:ss) LEVEL [THREAD] LOGGER - MESSAGE
This message may be multiline. Browser-Side Logs.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.
6.10 Specifying the Path to a Speciﬁc Browser
You can specify to Selenium-RC a path to a speciﬁc browser. This is useful if you have different versions of the same browser and you wish to use a speciﬁc one. Also, this is used to allow your tests to run against a browser not directly supported by Selenium-RC. When specifying the run mode, use the *custom speciﬁer followed by the full path to the browser’s executable:
*custom <path to browser>
6.11 Selenium-RC Architecture
Note: This topic tries to explain the technical implementation behind Selenium-RC. It’s not fundamental for a Selenium user to know this, but could be useful for understanding some of the problems you might ﬁnd in the future. To understand in detail how Selenium-RC Server works and why it uses proxy injection and heightened privilege modes you must ﬁrst understand the same origin policy.
6.11.1 The Same Origin Policy).
6.10. Specifying the Path to a Speciﬁc Browser
73
Here is an architectural diagram. Selenium-RC is not. Note: You can ﬁnd additional information about this topic on Wikipedia pages about Same Origin Policy and XSS.0 Historically. Release 1. It. restricted by the Same Origin Policy. 6. Selenium-Core was limited by this problem since it was implemented in JavaScript. this is why any HTTP request that the browser does will pass through Selenium server and the response will pass through it and not from the real server.2 Proxy Injection The ﬁrst method Selenium used to avoid the The Same Origin Policy was Proxy Injection. essentially. 2 The browser is launched with a conﬁguration proﬁle that has set localhost:4444 as the HTTP proxy. Selenium-RC . The proxy is a third person in the middle that passes the ball between the two parts. It then masks the AUT under a ﬁctional URL (embedding Selenium-Core and the set of tests and delivering them as if they were coming from the same origin). Its use of the Selenium Server as a proxy avoids this problem. however. Being a proxy gives Selenium Server the capability of “lying” about the AUT’s real URL. tells the browser that the browser is working on a single “spoofed” website that the Server provides.Selenium Documentation.11. In Proxy Injection Mode. that sits between the browser and the Application Under Test. 1 74 Chapter 6. the Selenium Server acts as a client-conﬁgured 1 HTTP proxy 2 . It acts as a “web server” that delivers the AUT to the browser.
typically opening a page of the AUT. Selenium-Core instructs the browser to act on that ﬁrst instruction. The client-driver passes a Selenese command to the server. The browser receives the open request and asks for the website’s content from the Selenium-RC server (set as the HTTP proxy for the browser to use). 4. 3. The client/driver establishes a connection with the selenium-RC server. Selenium-RC server launches a browser (or reuses an old one) with a URL that injects SeleniumCore’s JavaScript into the browser-loaded web page. Release 1.0 As a test suite starts in your favorite language. 6. The Server interprets the command and then triggers the corresponding JavaScript execution to execute that command within the browser. 6. Selenium-RC server communicates with the Web server asking for the page and once it receives it. 2. 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). the following happens: 1.11. 5.Selenium Documentation. Selenium-RC Architecture 75 . 7.
By using these browser modes. The client/driver establishes a connection with the selenium-RC server. which allows websites to do things that are not commonly permitted (as doing XSS. Selenium-RC server launches a browser (or reuses an old one) with a URL that will load SeleniumCore in the web page.3 Heightened Privileges Browsers This workﬂow in this method is very similar to Proxy Injection but the main difference is that the browsers are launched in a special mode called Heightened Privileges. As a test suite starts in your favorite language. the following happens: 1. The browser receives the web page and renders it in the frame/window reserved for it. Here is the architectural diagram. Selenium Core is able to directly open the AUT and read/interact with its content without having to pass the whole AUT through the Selenium-RC server. 76 Chapter 6. Selenium-Core gets the ﬁrst instruction from the client/driver (via another HTTP request made to the Selenium-RC Server).Selenium Documentation.0 8. or ﬁlling ﬁle upload inputs and pretty useful stuff for Selenium). 6. 3. Selenium-RC .11. Release 1. 2.
Selenium-Core acts on that ﬁrst instruction. Selenium-RC supports this. Once the browser receives the web page. and should not be used unless required by legacy test programs. This tricks the browser into thinking it’s accessing a site different from your AUT and effectively suppresses the popups. Handling HTTPS and Security Popups 77 . You specify the run mode when your test program initializes Selenium. your browser will trust the application you are testing by installing a security certiﬁcate which you already own. However. If you are using Selenium 1. Selenium-RC.0 beta 1.0 4. Another method used with earlier versions of Selenium was to install the Cybervillians security certiﬁcate provided with your Selenium installation. use *chrome or *iehta. Otherwise.). and should not use. 6. In earlier versions. these older run modes.0 you do not need.Selenium Documentation.12. 6. Most users should no longer need to do this however. Using these run modes.12. In Selenium-RC 1. (again when using a run mode that support this) will install its own security certiﬁcate. and these popups cannot be closed using Selenium-RC.0 beta 2 and later use *ﬁrefox or *iexplore for the run mode. typically opening a page of the AUT. The browser receives the open request and asks the Web Server for the page. you may need to explicitly install this security certiﬁcate. you must use a run mode that supports this and handles the security certiﬁcate for you. if you are running Selenium-RC in proxy injection mode. To get around this. In version 1. These were considered ‘experimental modes although they became quite stable and many people used them. it will assume that application is not ‘trusted’. To ensure the HTTPS site is genuine. the browser will need a security certiﬁcate. to your client machine in a place where the browser can access it. for the run mode.1 Security Certiﬁcates Explained Normally. In earlier versions of Selenium-RC. Their use will present limitations with security certiﬁcate handling and with the running of multiple windows if your application opens additional browser windows. 5. including Selenium-RC 1. When dealing with HTTPS in a Selenium-RC test. It responds by alerting you with popup messages. These are provided for backwards compatibility only. *chrome or *iehta were the run modes that supported HTTPS and the handling of security popups. When this occurs the browser displays security popups. Release 1. Selenium-RC will handle it for you.0 the run modes *ﬁrefox or *iexplore are recommended. 6.12 Handling HTTPS and Security Popups Many applications switch from using HTTP to HTTPS when they need to send encrypted information such as passwords or credit card information. when the browser accesses the AUT using HTTPS. renders it in the frame/window reserved for it. When Selenium loads your browser it injects code to intercept messages between the browser and the server. This is common with many of today’s web applications. temporarily. The browser now thinks untrusted software is trying to look like your application. you will not need to install any special security certiﬁcates.
6.. We present them along with their solutions here. If so.1 Unable to Connect to Server When your test program cannot connect to the Selenium Server... you pass in the path to the browsers executable within the API call. Consult your browser’s documentation for details.org website for supported browsers. you may still run your Selenium tests against a browser of your choosing by using the “*custom” run-mode (i. but if you launch the browser using the “*custom” run mode. One may need to set the MOZ_NO_REMOTE environment variable to make Mozilla browsers behave a little more predictably. in place of *ﬁrefox or *iexplore) when your test application starts the browser.Inner Exception Message: No connection could be made because the target machine actively refused it.14.0 6.13 Supporting Additional Browsers and Browser Conﬁgurations The Selenium API supports running against multiple browsers in addition to Internet Explorer and Mozilla Firefox. Release 1.exe&2=h 6. it’s generally better to use the binary executable (e.13.Selenium Documentation. It should display this message or a similar one: "Unable to connect to remote server. With this. This can also be done from the Server in interactive mode. Be aware that Mozilla browsers can vary in how they start and stop. you must manually conﬁgure the browser to use the Selenium Server as a proxy. ﬁrefox-bin) directly.NET and XP Service Pack 2) If you see a message like this.g.1 Running Tests with Different Browser Conﬁgurations Normally Selenium-RC automatically conﬁgures the browser. but instructions for this can differ radically from browser to browser.. you can launch Firefox with a custom conﬁguration like this: cmd=getNewBrowserSession&1=*custom c: \P rogram Files \M ozilla Firefox \f irefox. when a browser is not directly supported. 78 Chapter 6. Unix users should avoid launching the browser using a shell script..exe&2=htt Note that when launching the browser this way. cmd=getNewBrowserSession&1=*custom c: \P rogram Files \M ozilla Firefox \M yBrowser. be sure you started the Selenium Server. an exception will be thrown in your test program. In addition. you can force Selenium RC to launch the browser as-is. For example." (using .. Selenium-RC . without using an automatic conﬁguration.e. Normally this just means opening your browser preferences and specifying “localhost:4444” as an HTTP proxy. See the SeleniumHQ. 6. then there is a problem with the connectivity between the Selenium Client Library and the Selenium Server.14 Troubleshooting Common Problems When getting started with Selenium-RC there’s a few potential problems that are commonly encountered.
6. 6. you do want to run Selenium Server on a remote machine. sorry. If unfamilar with these. This can easily happen. it inserts a dummy URL. • You speciﬁed the path to the browser explicitly (using “*custom”–see above) but the path is incorrect. We recommend beginning this way since it reduces the inﬂuence of potential networking problems which you’re getting started. however. you can use common networking tools like ping. 6. See the section on Firefox proﬁles under Server Options. If. you didn’t specify a separate proﬁle when you started the Selenium Server.3 Selenium Cannot Find the AUT If your test program starts the browser successfully. When you use Selenium-IDE to export your script. Check the parameters you passed to Selenium when you program opens the browser. etc to ensure you have a valid network connection.2 Unable to Load the Browser Ok. Release 1.lang. telnet.Selenium Documentation. many people choose to run the tests this way. The error from the test program looks like this: Error: java. Also check the user group to be sure there are no known issues with your browser and the “*custom” parameters. most people begin by running thier test program (with a Selenium Client Library) and the Selenium Server on the same machine.14. the most likely cause is your test program is not using the correct URL. Assuming your operating system has typical networking and TCP/IP settings you should have little difﬁculty.0) cannot start because the browser is already open and you did not specify a separate proﬁle. In truth.RuntimeException: Firefox refused shutdown while preparing a profile Here’s the complete error message from the server: 6. If you have difﬁculty connecting. your system administrator can assist you. Check to be sure the path is correct. but if the Selenium Server cannot load the browser you will likley see this error.14. not a friendly error message. the connectivity should be ﬁne assuming you have valid TCP/IP connectivity between the two machines. • The run mode you’re using doesn’t match any browser on your machine.4 Firefox Refused Shutdown While Preparing a Proﬁle This most often occurs when your run your Selenium-RC test program against Firefox. You must manually change the URL to the correct one for your application to be tested.14. (500) Internal Server Error This could be caused by • Firefox (prior to Selenium 1. To do this use “localhost” as your connection parameter. ifconﬁg(Unix)/ipconﬁg (Windows). Troubleshooting Common Problems 79 . but you already have a Firefox browser session running and. but the browser doesn’t display the website you’re testing.0 When starting with Selenium-RC.14.
openqa.5. see the section on Specifying a Separate Firefox Proﬁle 6... it only appears to exist when the proxy is properly conﬁgured.0)” while starting server This error says you’re not using a correct version of Java.com HTTP/1.... java -version You should see a message showing the Java version..waitForFullProfileToBeCreated(FirefoxCustomProfileLauncher..Preparing Firefox profile.openqa..0 16:20:03. *iexplore. use the latest release version of Selenium with the most widely used version of your browser. Release 1.com/seleniumserver/“. When in doubt.14.1 java.. To check double-check your java version.idc.server.lock To resolve this.92 does not support Firefox 3.. run this from the command line. 6.FirefoxCustomProfileLaunc her. But don’t forget to check which browser versions are supported by the version of Selenium you are using.selenium.5 Versioning Problems Make sure your version of Selenium supports the version of your browser. *opera.google.. java version "1.lang. mixed mode) If you see a lower version number. Selenium Server attempts To conﬁgure the global proxy settings in the Internet Options Control Panel. 16:20:27.Selenium Documentation.6 Error message: “(Unsupported major. Standard Edition (build 1..selenium.FirefoxCustomProfileLaunc her$FileLockRemainedException: Lock file still present! C:\DOCUME~1\jsvec\LOCALS ~1\Temp\customProfileDir203138\parent. Try 80 Chapter 6.. Proxy Conﬁguration highly depends on how the browser is launched with *ﬁrefox..14. you could be having a problem with Internet Explorer’s proxy settings.0_07-b03) Java HotSpot(TM) Client VM (build 1.RuntimeException: Firefox refused shutdown while preparing a profile at org.. You must make sure that those are correctly conﬁgured when Selenium Server launches the browser.822 WARN . you may need to update the JRE. • *iexplore: If the browser is launched using *iexplore. The “selenium-server” directory doesn’t exist on google. Caused by: org.5.server.java:277) ... At times you may be lucky (I was). Selenium-RC .browserlaunchers.com..5 or higher. then it must be because the Selenium Server was not correctly conﬁgured as a proxy..14. or you may simply need to add it to your PATH environment variable.....GET /selenium-server/driver/?cmd=getNewBrowserSession&1=*fir efox&2=http%3a%2f%2fsage-webapp1. The Selenium Server requires Java 1.7 404 error when running the getNewBrowserSession command If you’re getting a 404 error while attempting to open a page on “. or *custom. Selenium-RC 0...919 INFO . For example.0_07-b03.0_07" Java(TM) 2 Runtime Environment. 6.browserlaunchers.5..minor version 49.
6. – If you need to use a proxy to access the application you want to test. Release 1.com/blah/blah/blah“). as described in RFC 1738. and so ther are no known issues with this functionality. otherwise you’ll get a 404 error. • HTTP basic authentication dialogs: These dialogs prompt for a username/password to login to the site. Often it is impossible to reproduce the problem with a debugger because the trouble stems from race conditions which are not reproducible when the debugger’s overhead is added to the system. Double-check that you’ve conﬁgured your proxy settings correctly.. • For other browsers (*ﬁrefox. accesses a page from and then accesses a page from) or switching protocols (moving from to). This is most typically encountered with AJAX pages which are working with sections of a page or subframes that load and/or reload independently of the larger page. You may need to know how to manage these. Try conﬁguring the browser to use the wrong proxy server hostname. Permission issues are covered in some detail in the tutorial. but you may need to conﬁgure your 6.Selenium Documentation. • SSL certiﬁcate warnings: Selenium RC automatically attempts to spoof SSL certiﬁcates when it is enabled as a proxy. Click on the “Connections” tab and click on “LAN Settings”. If you’re encountering 404 errors and have followed this user guide carefully post your results to user group for some help from the user community. • *custom: When using *custom you must conﬁgure the proxy correctly(manually).g. then the browser will be unable to connect to the Internet. Read the section about the The Same Origin Policy. To check whether you’ve conﬁgured the proxy correctly is to attempt to intentionally conﬁgure the browser incorrectly. use a username and password in the URL. This error can be intermittent. see the Proxy Conﬁguration for more details. If your browser is conﬁgured correctly. Each type of popup needs to be addressed differently. which is one way to make sure that one is adjusting the relevant settings. or are no longer available (after the page has started to be unloaded). or with *iehta browser launcher.14.0 looking at your Internet Options control panel.14.8 Permission Denied Error The most common reason for this error is that your session is attempting to violate the same-origin policy by crossing domain boundaries (e. 6.proxyHost”. like this: open(“. To login to a site that requires HTTP basic authentication..9 Handling Browser Popup Windows There are several kinds of “Popups” that you can get during a Selenium test. you’ll need to start Selenium Server with “-Dhttp. If you had successfully conﬁgured the browser’s proxy settings incorrectly. Proxy Injection carefully. – You may also try conﬁguring your proxy manually and then launching the browser with *custom.14. Troubleshooting Common Problems 81 . you should never see SSL certiﬁcate warnings. or the wrong port. see more on this in the section on HTTPS. *opera) we automatically hard-code the proxy for you.
Note: This section is not yet developed.12 Is it ok to load a custom pop-up as the parent page is loading (i.14 Safari and MultiWindow Mode Note: This section is not yet developed. These interceptors work best in catching new windows if the windows are loaded AFTER the onload() function. On most Linux distributions. cmd=getNewBrowserSession&1=*firefox /usr/local/firefox/firefox-bin&2=. which is usually too early for us to protect the page. If you’re seeing an alert pop-up. • modal JavaScript alert/conﬁrmation/prompt dialogs: Selenium tries to conceal those dialogs from you (by replacing window.c 6.Selenium Documentation. before the parent page’s javascript window. 6. Comment this line like this: “//user_pref(“browser.google.startup. 6. Release 1.13 Problems With Verify Commands If you export your tests from Selenium-IDE. If executing Firefox through a shell script. like this. Selenium-RC .e. 0).14.14. See the sections on these topics in Chapter 4.14.14.10 On Linux. versions of Selenium before 1.startup. Selenese contains commands for asserting or verifying alert and conﬁrmation popups.0 browser to trust our dangerous “CyberVillains” SSL certiﬁcate authority.js -> user_pref(“browser. why isn’t my Firefox browser session closing? On Unix/Linux you must invoke “ﬁrefox-bin” directly. 6.conﬁrm and window. leaving the browser running.alert. so if you are using a previous version.. the real ﬁrefox-bin is located on: 82 Chapter 6. 6.prompt) so they won’t stop the execution of your page. Selenium may not recognize windows loaded before the onload function.onload() function runs)? No. refer to the HTTPS section for how to do this. Selenium relies on interceptors to determine window names as they are being loaded.15 Firefox on Linux On Unix/Linux.11 Firefox *chrome doesn’t work with custom proﬁle Check Firefox proﬁle folder -> prefs. Again. 0). 6. so make sure that executable is on the path. it’s probably because it ﬁred during the page load process.14.page”. you may ﬁnd yourself getting empty verify strings from your tests (depending on the programming language used).14. when it comes time to kill the browser Selenium RC will kill the shell script. You can specify the path to ﬁrefox-bin directly.” and try again. make sure that the real executable is on the path.page”.0 needed to invoke “ﬁrefox-bin” directly. window.
Opera or Safari but not with IE. For example: //td[@style="background-color:yellow"] This would work perfectly in Firefox. So.x/ Where the x.x/" If necessary.x is the version number you currently have.x/firefox-bin " 6. you will have to add the following to your . but you can easily code your test to detect the situation and try the alternative locator that only works in IE. to add that path to the user’s path.x.14. 6. you should use: //td[@style="BACKGROUND-COLOR:yellow"] This is a problem if your test is intended to work on multiple browsers. IE interprets the keys in @style as uppercase. Release 1. like this: " *firefox /usr/lib/firefox-x.x.bashrc ﬁle: export PATH= "$PATH:/usr/lib/firefox-x.0 /usr/lib/firefox-x.16 IE and Style Attributes If you are running your tests on Internet Explorer and you cannot locate elements using their style attribute.Selenium Documentation.17 Where can I Ask Questions that Aren’t Answered Here? Try our user group 6. you can specify the path to ﬁrefox-bin directly in your test.14. So. even if the source code is in lowercase. Troubleshooting Common Problems 83 .x.14.x.
Selenium-RC .Selenium Documentation. Release 1.0 84 Chapter 6.
your application will be undergoing platform changes. the priority for each of those tests. a content test. 7. and trademarks information? • Does each page begin with heading text using the <h1> tag? And. time allowed for the project.2. These terms are by no means standard. you. the tester.1 Introducing Test Design In this subsection we describe a few types of different tests you can do with Selenium. priorities set by the project manager and so on. will certainly make many decisions on what to test. 7. • Does the application’s home page contain an image expected to be at the top of the page? • Does each page of the website contain a footer area with links to the company contact page. or ﬁles will likely be moved to different locations. but we provide this as a framework for relating Selenium test automation to the decisions a quality assurance professional will make when deciding what tests to perform. We will deﬁne some terms here to help us categorize the types of testing typical for a web-application. 85 .2 What to Test? What parts of your application should you test? That depends on aspects of your project: user expectations. This may not be new to you. is a simple test for the existence of a static. UI element. content tests may prove valuable.CHAPTER SEVEN TEST DESIGN CONSIDERATIONS NOTE: Some sections of this chapter are not yet complete. We’ve created a few terms here of our own for the purposes of categorizing the types of test you may perform on your web application. although the concepts we present here are typical for webapplication testing.1 Testing for Expected Content The simplest type of test. If. non-changing. For instance • Does each page have its expected page title? This can be used to verify your test found an expected page after following a link. does each page have the correct text within that header? You may or may not need content tests. however. privacy policy. Once the project boundaries are deﬁned though. 7. If your page content is not likely to be affected then it may be more efﬁcient to test page content manually. and whether to automate those tests or not.
An example will help. User input can be via text-input ﬁelds. So. and returning some type of results.generated fresh. Need to include a description of how to design this test and a simple example. 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). Submit and Cancel operations. etc.for example. 7. Suppose each data result. Testing for these involves clicking each link and verifying the expected page behind that link loads correctly. and ‘q2’ on the next instance of the same page. requiring some type of user input.2. new. or any other browser-supported input.2 Testing Links A frequent source of errors for web-sites is broken links and missing pages behind those broken links. These names can be static .Selenium Documentation. Dynamic HTML of an object might look as: <input type= "checkbox" value= "true" id= "addForm:_ID74:_ID75:0:_ID79:0: checkBox" name= "addForm:_ID74:_ID75:0:_ID79:0:checkBox" /> This is HTML snippet for a check box. drop-down lists. and unique for every instance of a web page. Then.4 Testing Dynamic Elements Every web page element has an Identiﬁer. say for example a list of documents. In Ajax-driven web applications. For example. for a particular search. 86 Chapter 7. Dynamic names are usually on a result page of some given function. when you enter a search term into Google. the search results page returns a different data set where each document in the result set uses different Identiﬁers.2. a name that can be use to locate the element. Should that go in this section or in a separate section? 7. checkboxes. Release 1.2. These names can also be dynamic . For example. the text ﬁeld in which you type your query is always named ‘q’. some web servers might name a text entry ﬁeld ‘q1’ on the ﬁrst instance of a page. in.3 Function Tests These would be tests of a speciﬁc function within your application. Test Design ConsIDerations . This means your test script could be looking at a different ﬁeld name every time you run the script. had a unique Identiﬁer for each speciﬁc document.5 Ajax Tests Ajax is a technology which supports dynamic real-time UI elements such as animation and RSS feeds. Dynamic content involve UI elements who Identifying properties change each time you open the page displaying them.0 7. the search results page returns a data set with one set of documents and their correponding Identiﬁers. Often a function test will involve multiple pages with a formbased input page containing a collection of input ﬁelds.2. In this case 7. data is retrieved from the application server without refreshing the page. and one or more response pages. An example would be a result set of data returned to the user. in a different search.
However. Verify When should you use an assert command and when should you use a verify command? This is up to you. The advantage: you have an immediate visual of whether the checks (those using asserts anyway) passed. In contrast. If not. The disavantage: you have to do more work to examine your test results. however you still need to open the logs and examine the results. (verify/assertElementPresent) • Must I test both. you will need to look at the results of a console printout or a log output by your test application. Verifying Results 87 .1 Assert vs. you will need to decide • Do I only check that the text exists on the page? (verify/assertTextPresent) • Do I only check that the HTML element exists on the page? That is. each with it’s own log. so you have no information on their status. or other content is not to be checked.0 7. Test engines such as TestNG and JUnit have plugins for commonly used development environments (Chap 5) which conveniently ﬂag these tests as failed tests. That is. for instance if HTML changes frequently by your programmers. or an image. 7. It depends on the requirements for your test. You only care that some type of image exists. this will be time-consuming. For Java.3. Sometimes. In this case you can use verify/assertElementPresent. Realize that verify/assertText is the most speciﬁc test. Most of these are easily changed in either Sel-IDE or Sel-RC. but will pass the test when the programmers change the HTML used to present that text. verifyTextPresent makes more sense. The difference is in what you want to happen when the check fails. This can fail if either the HTML element (tag) OR the text is not what your test is expecting. and the mechanics of using them. you won’t get feedback from TestNG or JUnit. only the HTML tag is what is relevant. When constructing your tests.Selenium Documentation. verify commands will not terminate the test. It can check for the content. perhaps often.2 Trade-offs: assertTextPresent. you can go with your best guess and can always change the test later. But you don’t care what the content is. Sometimes. 7. If the test fails you will immediately know the test did not pass. say a paragraph. assertElementPresent. of course.3. or heading text. that is. If you are running hundreds of tests. Rather. or speciﬁc text. perhaps your webdesigners are frequently changing the page and you don’t want your test to fail everytime they do this because the changes themeselves are expected periodically. Alternatively. The disadvantage: when a check does fail. Do you want your test to terminate or continue and record that the check failed? Here’s the tradeoff. If your test uses only verify commands you are guaranteed (assuming no unexpected exceptions) the test will run to completion whether the checks ﬁnd defects in the AUT or not. If you use an assert.3 Verifying Results 7. It will ensure that a particular type of element exists (and if using Xpath can ensure it exists relative to other objects within the page). image. the text. the test will stop at that point and not run any subsequent checks. that is what you want. If in doubt. please refer to Chapter 4 ﬁrst. assertText You should now be familiar with these commands. Logging Selenium (Chap 5) is a convenient logging utility for recording the results of verify commands. a speciﬁc image ﬁle. there are other checks which were never performed. depend on the requirements for the application you’re testing. the element and it’s text content? (verify/assertText) There is no right answer. And you will need to take the time to look through this output everytime you run your test. Release 1. Which. and if the requirements are not clear.3. assume you still need to check that something is on the page.
But what are the tradeoffs of each of these locator types? Recall we can locate an object using • the element ID • the element name attribute • an Xpath statement • document object model (DOM) Generally. For others. That is. but they do depend do depend on the requirements of your AUT. <a class= "button" id= "adminHomeForm" onclick= "return oamSubmitForm(’adminHomeForm’. Release 1. and Xpath appears to the preferred choice. If you must test that an image displaying the company logo appears at the top of the page within a header section Xpath may be the better locator.1 Locating Dynamic Objects First. 7. we will contrast that with a static object. With ID and name locators. you must use an Xpath locator. Its ID remains constant within all instances of this page. not so much. There is an advantage to using Xpath or DOM that locating via ID or name attributes do not have. It’s a fairly complex anchor tag when compared to most HTML tags.0 Getting a feel for these types of decisions will come with time and a little experience. ’adminHomeForm:_ID38’). 7.Selenium Documentation. The HTML will be the same each time this page is loaded in the browser. and you will have to give it your best guess. For example. 88 Chapter 7. Sometimes though.4. you can use Xpath or DOM to specify this. If the page source does not have an ID or name attribute you have no choice but to use an Xpath or DOM locator." href= "#" >View Archived Allocation Events</a> This is HTML anchor tag deﬁning an button with an ID attribute of “adminHomeForm”. if there is a link that must occur within the second paragragh within a <div> section. and easy to change in your test. using an ID locator is more efﬁcient as it makes your test code more readable. So. for your test script to click this button you simply need to use the following selenium command. Xpath statements have been known to be slow in Internet Explorer due to limations of IE’s Xpath processor. Using the name attribute also has similar advantages.4 Choosing a Location Strategy You know from the Selenese section there are multiple ways of selecting an object on a page. For example. possibly because Xpath provides a rich set of possibilities for Identifying an object–it is quite ﬂexible. Until now. With Xpath and DOM you can locate an object with respect to another object on the page. and to do so. These also give the best performance. you can only specify that they occur on the page– somewhere on the page. They are easy concepts. but it is still a static tag. when this page is displayed. assuming the ID used by the AUT’s page source is a meaningful one. Test Design ConsIDerations . all the AUT page elements we have been considering have been static objects. you must understand what a dynamic object is. These are objects who’s html page source is the same each time the page is loaded in the browser. The purpose of this subsection is to help you anticipate your needs so you can make these decisions more efﬁciently. It appears at the time of writing that DOM locators are not commonly used now. For some projects the requirements are clear and therefore your tests will be clear. this UI element will always have this Identiﬁer.
{ // If the ID starts with addForm if(checkboxids[i].Selenium Documentation.click(checkboxids[i]). So. HTML for a dynamic page element might look like this.click( "adminHomeForm" ). Your application. // Collect all input IDs on page. for the checkbox you can simply use click //input Or. may generate HTML with IDs that are generated dynamically and therefore the ID itself varies on different instances of the webpage under test.indexOf( "addForm" ) > -1) { selenium. For instance.IsBlankOrNull(checkboxids[i])) // If collected ID is not null. 7. To correct this. again in Selelenium-RC selenium.0 click adminHomeForm Or. however. in Selenium-RC selenium. a simple solution would be to just use an XPath locator rather than trying to use an ID locator. will not be found. The next time this page is loaded the Identiﬁer will be a different value from the one used in the Selenium command and therefore. Another solution is to capture this ID from the website itself. Release 1. using a standard locator would look something like the following. Given the dynamically generated Identiﬁer. The click operation will fail with an “element not found” error.getAllFields(). a programmed solution is required.4. It can be done like this. String[] checkboxids = selenium. this approach would not work. Choosing a Location Strategy 89 . before you need to use it in a Selenium command. click addForm:_ID74:_ID75:0:_ID79:0:checkBox Or. . if it is not the ﬁrst input element on the page (which it likely is not) try a more detailed Xpath statement. if(!GenericValidator. Its ID and name attributes (both addForm:_ID74:_ID75:0:_ID79:0:checkBox) are dynamically generated values. click //input[3] Or click //div/p[2]/input[3] If however. In this case.click("addForm:_ID74:_ID75:0:_ID79:0:checkBox).
Automatically generated (non-descriptive) element IDs (i.getElementByID(’" +linkID+ "’).isBlankOrNull(linkID)) { // Find the inner HTML of link. boolean isSecondInstanceLink = false. each time the application is deployed. element IDs should be explicitly created by the application designer. String[] links = selenium. a page with two links having the same name and the same html name.click(editInfo). Release 1.innerHTML" ). Now if href is used to click the link.equalsIgnoreCase( "expectedlink" )) { // If it is second appearance of link then save the link ID and break the loop. Consider one more example of a Dynamic object. // Desired link. Second. // If retrieved link is expected link. if(isSecondInstanceLink) { editInfo = linkID. Test Design ConsIDerations . } // Set the second appearance of Autumn term link to true as isSecondInstanceLink = true. different element IDs could be generated. Clicking on the second link can be achieved as follows.getAllLinks(). id_147) tend to cause two problems: ﬁrst.getEval ( "window. // Flag for second appearance of link. it would always be clicking on the ﬁrst element. 90 Chapter 7.Selenium Documentation.2 How can I avoid using complex xpath expressions in my test? Where possible.0 } } This approach will work if there is only one ﬁeld whose ID has the text ‘addForm’ appended to it. a non-descriptive element id makes it hard for automation testers to keep track of and determine which element IDs to use (which ID is associated with which GUI object). not automatically generated.4.e. // Collect all links. break. if(editTermSectionInfo. for(String linkID: links) { // If retrieved link is not null if(!GenericValidator. 7. String editInfo = null. If the element ID changes then your test will fail. selenium. String editTermSectionInfo = selenium. // Loop through collected links. } } } // Click on link.document.
7. The test script then uses the UI Map for locating the elements to be tested. a page element implemented with Ajax is an element that can be dynamically refreshed without having to refresh the entire page.5 Testing Ajax Applications We introduced the special characteristics of AJAX technology earlier in this chapter.org/display/SIDE/Contributed+Extensions+and+Formats#ContributedExtensionsandFormatsUIElementLocator 7.4. 7. Basically. Consider a page which brings a link (link=ajaxLink) on click of a button on page (without refreshing the page) This could be handled by Selenium using a for loop.4.3 Performance Considerations for Locators 7.0 You might consider trying the UI-Element extension in this situation. 7. Waiting for an Ajax Element For an Ajax element using Selenium’s waitForPageToLoad wouldn’t work since the page is not actually loaded to refresh the Ajax element. 7.isElementPresent( "link=ajaxLink" )) break. if (second >= 60) break. } This certainly isn’t the only solution. Release 1. A better approach is to wait for a predeﬁned period and then continue execution as soon as the element is found. Basically. Thread.. locators.5. for an application’s UI elements.5. a UI map is a repository of test script objects that correspond to UI elements of the application being tested. 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. Pausing the test execution for a speciﬁed period of time is also not good because the web element might appear later than expected leading to invalid test failures (reported failures that aren’t actually failures).openqa. for (int second = 0. // Loop initialization.4 Custom Locators This section is not yet developed.sleep(1000).6 UI Mapping A UI map is a mechanism that stores Identiﬁers. Testing Ajax Applications 91 . try { if (selenium.Selenium Documentation. or in our case. second++) { // If loop is reached 60 seconds then break the loop. // Search for element "link=ajaxLink" and if available then break loop. } catch (Exception e) // Pause for 1 second.
test. selenium. there is a central location for easily ﬁnding that object. a UI map has two signiﬁcant advantages.type(admin. Release 1. selenium. Even regular users of the application would have difﬁculty understanding what the script does.click(admin. "xxxxxxxx" ). selenium.click(admin. • Using a centralized location for UI objects instead of having them scattered throughout the script. selenium.username. selenium.open( ". Test Design ConsIDerations .click( "loginForm:btnLogin" ). or for that matter.) An even better test script could look like this. selenium. Consider the following example (in java) of selenium tests for a website: public void testNew() throws Exception { selenium.events. To summarize. } This script is incomprehensible to anyone who isn’t very familiar with the AUT’s page source.type( "loginForm:tbUsername" .waitForPageToLoad( "30000" ).test.createnewevent). Also.waitForPageToLoad( "30000" ). "xxxxxxxx" ). selenium.Selenium Documentation. selenium.click( "addEditEventForm:_IDcancel" ). • Cryptic HTML Identiﬁers and names can be given more human-readable names improving the readability of test scripts. selenium.click( "adminHomeForm:_activitynew" ). in multiple test scripts.click(admin. selenium. A better script would be: public void testNew() throws Exception { selenium. selenium. selenium.waitForPageToLoad( "30000" ). selenium.0 What makes a UI map heplful? Its primary purpose for making test script management much easier.loginbutton).events.click(admin.waitForPageToLoad( "30000" ). selenium. This makes script maintanence more efﬁcient.viewoldevents). selenium.com" ). } There are no comments provided but it is more comprehensible because of the keywords used in scripts.click( "adminHomeForm:_activityold" ).waitForPageToLoad( "30000" ). it allows changing the Identifer in a single place. selenium. public void testNew() throws Exception { // Open app url.open( ". When a locator needs to be edited.com" ). rather than having to make the change in multiple places within a test script.events.com" ). selenium. (please be aware that UI Map is NOT a replacement for comments! Comments are still important for documenting an automated test.test. rather than having to search through test script code.waitForPageToLoad( "30000" ).cancel). 92 Chapter 7.open( ".
// Click on View Old Events button. A properties ﬁle contains key/value pairs.0 // Provide admin username.type(admin.viewoldevents). 7. Values are read from the properties ﬁle and used in the Test Class to implement the UI Map. properties ﬁles can be used in java.createnewevent).click(admin. "xxxxxxxx" ).cancel = addEditEventForm:_IDcancel admin.7. To achieve this.events.7 Bitmap Comparison This section has not been developed yet. selenium.7.click(admin.1 Data Driven Testing This section needs an introduction and it has not been completed yet. // Click on Login button. admin. selenium.click(admin. // Click on Create New Event button.username.events. but we have introduced a layer of abstraction between the test script and the UI elements.events. In Python: # Collection of String values source = open( " input_file. For more on Properties ﬁles refer to the following link.createnewevent = adminHomeForm:_activitynew admin. selenium.waitForPageToLoad( "30000" ).loginbutton = loginForm:btnLogin admin.loginbutton). } The idea is to have a centralized location for objects and using comprehensible names for those objects. Consider a property ﬁle prop.events. selenium.events. " r " ) values = source. selenium.username = loginForm:tbUsername admin. // Click on Cancel button.waitForPageToLoad( "30000" ). selenium. Release 1.waitForPageToLoad( "30000" ).close() # Execute For loop for each String in the values array for search in values: sel.events. selenium. 7. where each key and value are strings.Selenium Documentation.txt " .viewoldevents = adminHomeForm:_activityold The locators will still refer to html objects. Bitmap Comparison 93 .properties which assigns as ‘aliases’ easily understood Identiﬁers for the HTML objects used earlier.open( " / " ) 7. selenium.cancel).click(admin.readlines() source.
and iterates over the array doing a search and assert on each string. // Get connection to DB.microsoft. // Prepare connection url. 7. search) sel. Test automation tools. 7.handling support can be used for error handling and recovery. An example of establishing a DB connection and retrieving data from the DB would be: In Java: // Load Microsoft SQL Server JDBC driver. Release 1. Test Design ConsIDerations .click( " btnG " ) sel.SQLServerDriver" ).180:1433.forName( "com.jdbc.2 Recovering From Failure A quick note though–recognize that your programming language’s exception.3 Database Validations Since you can also do database queries from your favorite programming language.Selenium Documentation. This is called Data Driven Testing and is a very common testing task. This is a very basic example of what you can do. assuming you have database support functions. Selenium included.sqlserver.8. why not use them for some data validations/retrieval on the Application Under Test? Consider the example of a registration process where a registered email address is to be retrieved from the database. but the Idea is to show you things that can easily be done with either a programming or scripting language when they’re difﬁcult or even impossible to do using Selenium-IDE. This ﬁle contains a different search string on each line.8.0 sel. This section has not been developed yet.1. The Python script above opens a text ﬁle. String url = "jdbc:sqlserver://192.waitForPageToLoad( " 30000 " ) self.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. Class.168. 7. 94 Chapter 7.failUnless(sel.8 Handling Errors Note: This section is not yet developed. generally handle this as it’s a common reason for test automation.8.DatabaseName=TEST_DB" . The code then saves this in an array of strings. 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.1 Error Reporting 7.type( " q " .
Handling Errors 95 . "username" . // Fetch value of "email_address" from "result" object.8.type( "userID" .getConnection(url. // Use the fetched value to login to application. selenium. // Send SQL SELECT statements to the database via the Statement. Release 1. This wouldn’t take too much work from what you’ve already seen. 7. ResultSet result = stmt. "password" ).0 public static Connection con = DriverManager.executeQuery ( "select top 1 email_address from user_register_table" ). A more complex test could be to validate that inactive users are not able to login to the application. // Create statement object which would be used in writing DDL and DML // SQL statement. This is a very simple example of data retrieval from a DB in Java. String emailaddress = result.Selenium Documentation.createStatement().getString( "email_address" ). emailaddress). public static Statement stmt = con.executeQuery // method which returns the requested information as rows of data in a // ResultSet object.
0 96 Chapter 7. Release 1.Selenium Documentation. Test Design ConsIDerations .
seleniumhq.org/how_it_works. We would love to have you contribute. and would like to contribute.CHAPTER EIGHT SELENIUM-GRID Please refer to the Selenium Grid website This section is not yet developed. 97 . If there is a member of the community who is experienced in SeleniumGrid. please contact the Documentation Team.
0 98 Chapter 8. Selenium-Grid . Release 1.Selenium Documentation.
For each action foo there is also an action fooAndWait registered. but it has not been reviewed and edited. which types the text twice into a text box.replaceText(element. On startup. adding your own actions. and the PageBot object prototype. // Replace the element text with the new text this. using name patterns to recognize which ones are actions. assertions and locator-strategies. Selenium. which will be passed the second and third column values in the test. Selenium will automatically look through methods on these prototypes. that makes sure that the element 99 . verifyFooa nd waitForFoo registered. valueToType).findElement(locator).doTypeRepeated = function(locator. The following examples give an indication of how Selenium can be extended with JavaScript.1 Introduction It can be quite simple to extend Selenium. // Create the text to type var valueToType = text + text. assertions and locators. text) { // All locator-strategies are automatically handled by "findElement" var element = this. which will also auto-generate “verify” and “waitFor” commands.3 Accessors/Assertions All getFoo and isFoo methods on the Selenium prototype are added as accessors (storeFoo). An action method can take up to two parameters.prototype. For each accessor there is an assertFoo.CHAPTER NINE USER-EXTENSIONS NOTE: This section is close to completion. 9. An assert method can take up to 2 parameters. 9. You can also deﬁne your own assertions literally as simple “assert” methods. 9. Example: Add a “typeRepeated” action to Selenium.page().2 Actions All methods on the Selenium prototype beginning with “do” are added as actions. which will be passed the second and third column values in the test.page(). }. This is done with JavaScript by adding methods to the Selenium object prototype. Example: Add a valueRepeated assertion.
assertNotFoo. User-Extensions . i < allElements. Release 1.4 Locator Strategies All locateElementByFoo methods on the PageBot prototype are added as locator-strategies. Selenium. Selenium.1 Automatic availability of storeFoo. and waitForNotFoo commands.3. the ﬁrst being the locator string (minus the preﬁx). and waitForNotTextLength commands. PageBot. if you add a getTextLength() method.getTextLength = function(locator. that ﬁnds the ﬁrst element a value attribute equal to the the supplied value repeated.getText(locator). actualValue). verifyTextLength.findElement(locator). for (var i = 0. }. assertFoo. 9. // Get the actual element value var actualValue = element. }. text) { return this.prototype. assertNotTextLength. i++) { var testElement = allElements[i]. Example: Add a “valuerepeated=” locator.page().Selenium Documentation. The 2 commands that would be available in tests would be assertValueRepeated and verifyValueRepeated.value. text) { // All locator-strategies are automatically handled by "findElement" var element = this.matches(expectedValue. and the second being the document in which to search. storeValueRepeated. waitForFoo. inDocument) { // Create the text to search for var expectedValue = text + text. looking for ones that have // a value === our expected value var allElements = inDocument.length. assertTextLength. waitForFoo and waitForNotFoo for every getFoo All getFoo and isFoo methods on the Selenium prototype automatically result in the availability of storeFoo. Example. the following commands will automatically be available: storeTextLength. verifyFoo. // The "inDocument" is a the document you are searching. waitForTextLength.prototype.length.assertValueRepeated = function(locator. Also note that the assertValueRepeated method described above could have been implemented using isValueRepeated.locateElementByValueRepeated = function(text. waitForValueRepeated and waitForNotValueRepeated. // Create the text to verify var expectedValue = text + text.prototype. assertNotFoo. 9. 100 Chapter 9. A locator strategy takes 2 parameters. verifyNotTextLength.0 value consists of the supplied text repeated.getElementsByTagName( "*" ). // Loop through all elements. verifyNotFoo. // Make sure the actual value matches the expected Assert. with the added beneﬁt of also automatically getting assertNotValueRepeated. assertFoo.
Your user-extension will not yet be loaded. Below. Click on OK. create a new command. 9. } } return null. 2. 6.5. js ﬁle.ca/" ). Place your user extension in the same directory as your Selenium Server.6 Using User-Extensions With Selenium RC If you Google “Selenium RC user-extension” ten times you will ﬁnd ten different approaches to using this feature.) HttpCommandProcessor proc. 9. Create your user extension and save it as user-extensions. 4444. First. Options 4. 2. This can be done in the test setup. If you are using client code generated by the Selenium-IDE you will need to make a couple small edits.6.value && testElement. is the ofﬁcial Selenium suggested approach. Using User-Extensions With Selenium-IDE 101 . Click on Tools. 5.5 Using User-Extensions With Selenium-IDE User-extensions are very easy to use with the selenium IDE. Open Firefox and open Selenium-IDE.value === expectedValue) { return testElement. Next. 3.js. In Selenium Core Extensions click on Browse and ﬁnd the user-extensions. 1. it’s good practice to keep things consistent. you will need to create an HttpCommandProcessor object with class scope (outside the SetupTest method.Selenium Documentation. "*iexplore" . ". }. instantiate that HttpCommandProcessor object DefaultSelenium object. your user-extension should now be an options in the Commands dropdown. 1. you must close and restart Selenium-IDE.1 Example C# 1. While this name isn’t technically necessary. In your empty test. as you would the proc = new HttpCommandProcessor( "localhost" . Release 1. 9. 9. just below private StringBuilder verificationErrors.0 if (testElement.
4444. [SetUp] public void SetupTest() { proc = new HttpCommandProcessor( "localhost" . Selenium automatically does this to keep common JavaScript naming conventions. proc. System. Instantiate the DefaultSelenium object using the HttpCommandProcessor object you created.0 1. Notice that the ﬁrst letter of your function is lower case.Threading. regardless of the capitalization in your user-extension. Within your test code. "*iexplore". Start the test server using the -userExtensions argument and pass in your user-extensinos.Selenium Documentation.Start().RegularExpressions.js using using using using using using System. private HttpCommandProcessor proc.jar -userExtensions user-extensions. Remember that user extensions designed for Selenium-IDE will only take two arguments. private StringBuilder verificationErrors. selenium. 4444. java -jar selenium-server. inputParams). This method takes two arguments: a string to identify the userextension method you want to use and string array to pass arguments. User-Extensions . selenium = new DefaultSelenium(proc). System. "*iexplore" selenium = new DefaultSelenium(proc). execute your user-extension by calling it with the DoCommand() method of HttpCommandProcessor. but a longer array will map each index to the corresponding user-extension parameter. } 102 Chapter 9. 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. 1. Release 1. In this case there is only one string in the array because there is only one parameter for our user extension. namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium.Text.Framework. NUnit. Selenium. string[] inputParams = { "Hello World" }. Because JavaScript is case sensitive. System. verificationErrors = new StringBuilder().Text. //selenium = new DefaultSelenium("localhost". 1.DoCommand( "alertWrapper" .js ﬁle.
0 [TearDown] public void TeardownTest() { try { selenium. Using User-Extensions With Selenium RC 103 . } } } 9.}. inputParams). } catch (Exception) { // Ignore errors if unable to close the browser } Assert.Stop().6.Open( "/" ).Selenium Documentation. string[] inputParams = { "Hello World" .DoCommand( "alertWrapper" . proc.ToString()). } [Test] public void TheNewTest() { selenium. Release 1. verificationErrors.AreEqual( "" .
Selenium Documentation. Release 1. User-Extensions .0 104 Chapter 9.
for example. in a joint email to the WebDriver and Selenium community on August 6. The WebDriver integration is currently undergoing testing. This will address a number of Selenium 1. The best explanation for why WebDriver and Selenium are merging was detailed by Simon Stewart. The primary new feature will be the integration of the WebDriver API into Selenium-RC. • Additional functionality addressing testing problems not well-supported in Selenium 1. WebDriver does not depend on a javascript core embedded within the browser.0 release. 2009. Users new to Selenium. should wait until Selenium 2.CHAPTER TEN SELENIUM 2.0 AND WEBDRIVER The Selenium developers are working towards a Selenium 2. It also provides an alternative API with functionality not supported in Selenium-RC. And we’ve got a gorgeous API). We encourage advanced Selenium users to try it out. partly because selenium addresses some shortcomings in webdriver (such as supporting a broader range of browsers) and partly because the main selenium contributors and I felt that it was the best way to offer users the best possible framework.0 is ofﬁcially released. Integrating WebDriver into Selenium is the current result of those efforts.1 What is WebDriver? WebDriver uses a different underlying framework from Selenium’s javascript Selenium-Core.0 is currently under development. 105 . The developers of Selenium and of WebDriver felt they could make signiﬁcant gains for the Open Source test automation community be combining forces and merging their ideas and technologies.” PLEASE NOTE: Selenium 2. the creator of WebDriver. 10. WebDriver’s goal is to provide an API that establishes • A well-designed standard programming interface for web-app testing. therefore it is able to avoid some long-running Selenium limitations. Integrating WebDriver is another step in that process. “Why are the projects merging? Partly because webdriver addresses some shortcomings in selenium (by being able to bypass the JS sandbox. The Selenium developers strive to continuously improve Selenium.0. • Improved consistency between browsers. The goal is to develop a standardized Selenium API that provides additional support for a larger number of browsers along with improved support for advanced web-app testing problems.0 limitations along with providing an alternative programming interface.
so it can be used equally well with JUnit. 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.0. Now. we’ll refer to that as $WEBDRIVER_HOME. You’ll start by using the HtmlUnit Driver. • AJAX-based UI elements. // And now use this to visit Google driver. package org. you won’t see a new browser window open.Selenium Documentation.selenium.2 When to Use WebDriver? One should use WebDriver when requiring improved support for • Mult-browser testing including improved functionality for browsers not well-supported by Selenium-1. which will help make your tests easier to read and maintain.openqa. • Page navigation.openqa. An easy way to get started is this example. From now on. // not the implementation. This “Getting Started” guide introduces you to WebDriver’s Java API and helps get you started becoming familiar with it. Selenium 2. popups.HtmlUnitDriver. org.selenium.By. 10. and in particular to verify that they work as expected.example. and alerts. TestNG or from a plain old “main” method.selenium. and you don’t need to remember to start any additional processes or run any installers before using it. It aims to provide a friendly API that’s easy to explore and understand. • Drag-and-drop. WebDriver driver = new HtmlUnitDriver().com" ).selenium.openqa. which searches for the term “Cheese” on Google and then outputs the result page’s title to the console.3 The 5 Minute Getting Started Guide WebDriver is a tool for automating testing web applications. Release 1. multiple browser windows. import import import import org. • Handling multiple frames. Start by Downloading the latest binaries and unpack them into a directory.google..WebElement.selenium. You’re now ready to write some code.htmlunit. 106 Chapter 10. org.get( ". org.WebDriver. Because of this. It’s not tied to any particular test framework.0 and WebDriver . This is a pure Java driver that runs entirely in-memory.0 10.
org.selenium. 10.selenium.out. The 5 Minute Getting Started Guide 107 . // Now submit the form.name( "q" )).selenium.selenium.WebElement.3.openqa. which looks like: package org. while (System.c // If results have been returned.openqa.example. Congratulations.name( "q" )).openqa.WebDriver.currentTimeMillis() < end) { // Browsers which render content (such as Firefox and IE) // return "RenderedWebElements" RenderedWebElement resultsDiv = (RenderedWebElement) driver. // Sleep until the div we want is visible or 5 seconds is over long end = System.isDisplayed()) { break. org.sendKeys( "Cheese!" ).openqa.findElement(By. you shall use a page that requires Javascript to work properly. // Enter something to search for element.Selenium Documentation. Release 1. // Go to the Google Suggest home page driver.selenium.get( "" ).google.sendKeys( "Cheese" ).openqa. if (resultsDiv.List. Make sure that Firefox is installed on your machine and is in the normal location for your OS.FirefoxDriver.firefox.findElement(By. org. Once that’s done. // Enter the query string "Cheese" WebElement query = driver.selenium. // the results are displayed in a drop down. WebDriver will find the form for us from the element element. you’ve managed to get started with WebDriver! In this next example. org.RenderedWebElement.0 // Find the text input element by its name WebElement element = driver. // Check the title of the page System. query.currentTimeMillis() + 5000.getTitle()).By.submit().util. import import import import import org.findElement(By. } } Compile and run this.println( "Page title is: " + driver. create a new class called GoogleSuggest. public class GoogleSuggest { public static void main(String[] args) throws Exception { // The Firefox driver supports javascript WebDriver driver = new FirefoxDriver(). such as Google Suggest. import java. You should see a line with the title of the Google search results as output on the console. You will also be using the Firefox Driver.
and how to use frames and windows.openqa. there’s “actual safety”. this additional ﬂexibility comes at the cost of slower overall speed.ChromeDriver You can ﬁnd out more information about each of these by following the links in the table.htmlunit. As a developer you may be comfortable with this. it is possible to pick the most appropriate driver for a given test. let’s start with the HtmlUnit Driver: WebDriver driver = new HtmlUnitDriver(). Firstly. which refers to whether or not an observer believes the tests work as they should. you’ll see the list of suggestions being printed to the console. and will depend on their familiarity with the application under test. To support higher “perceived safety”. or the CSS properties that apply to it. This can be measured and quantiﬁed. Release 1. However.out. and so can be used to detect information such as the position of an element on a page. but sometimes it’s good to be able to test using a real browser. Often.chrome.HtmlUnitDriver org.openqa. These are: Name of driver HtmlUnit Driver Firefox Driver Internet Explorer Driver Chrome Driver Available on which OS? All All Windows All Class to instantiate org. This has the added advantage that this driver actually renders content to a screen.openqa.1 Which Implementation of WebDriver Should I Use? WebDriver is the name of the key interface against which tests should be written. For sheer speed. To keep things simple. there’s “perceived safety”.Selenium Documentation.4 Next Steps For Using WebDriver 10.getText()).4. but there are several implementations.0 } } // And now list the suggestions List<WebElement> allSuggestions = driver. and your testing framework.FirefoxDriver org. this idea is referred to as “safety”. let’s take the Next Steps! 10. In the Next Steps section you will learn more about how to use WebDriver for things such as navigating forward and backward in your browser’s history. That’s all there is to using WebDriver! Hopefully. Secondly.selenium. and it falls into two parts.xpath( "//td[@class=’gac for (WebElement suggestion : allSuggestions) { System.0 and WebDriver . Which you use depends on what you want to do. which refers to whether or not the tests work as they should. the HtmlUnit Driver is great.selenium. but it’s not graphical.ﬁrefox. } } } When you run this program.ie. This varies from person to person.openqa. If you’re ready.findElements(By. which means that you can’t watch what’s happening. WebDriver. It also provides a more complete discussion of the examples than The 5 Minute Getting Started Guide. By writing your tests against the WebDriver interface.selenium. Selenium 2.InternetExplorerDriver org. this will have whet your appetite for more.selenium.println(suggestion. you may wish to choose a driver such as the Firefox Driver. 108 Chapter 10. especially when you’re showing a demo of your application (or running the tests) for an audience.
Don’t worry! WebDriver will attempt to do the Right Thing. the “onload” event has ﬁred) before returning control to your test or script.3 Interacting With the Page Just being able to go to places isn’t terribly useful. element = driver. Next Steps For Using WebDriver 109 .name( "passwd" )).sendKeys( " and some" .findElement(By. the HTML elements within a page. What we’d really like to do is to interact with the pages. element = driver.xpath( "//input[@id=’passwd-id’]" )).google.ARROW_DOWN). we need to ﬁnd one. For example. If nothing can be found.4.4. which makes it possible to test keyboard shortcuts such as those used on GMail. WebDriver offers a number of ways of ﬁnding elements. Instead. A side-effect of this is that typing something into a text ﬁeld won’t automatically clear it. then only the ﬁrst will be returned. we represent all types of elements using the same interface: Web Element. not all of them will make sense or be valid. or. This means that although you may see a lot of possible methods you could invoke when you hit your IDE’s auto-complete key combination.findElement(By.Selenium Documentation. but be careful! The text must be an exact match! You should also be careful when using XPATH in WebDriver. what you type will be appended to what’s already there.get( "( "some text" ). It is possible to call sendKeys on any element. Release 1.0 10. First of all. WebDriver will wait until the page has fully loaded (that is. If there’s more than one element that matches the query.4. You can also look for a link by its text. you may want to enter some text into a text ﬁeld: element.2 Navigating The ﬁrst thing you’ll want to do with WebDriver is navigate to a page. 10.id( "passwd-id" )). So. WebDriver has an “Object-based” API. The normal way to do this is by calling “get”: driver. If you need to ensure such pages are fully loaded then you can use “waits”. a NoSuchElementException will be thrown. element = driver.. more speciﬁcally. you’ve got an element. for example) an exception will be thrown. and if you call a method that makes no sense (“setSelected()” on a “meta” tag.com" ). What can you do with it? First of all. You can simulate pressing the arrow keys by using the “Keys” class: element.findElement(By. Keys. You can easily clear the contents of a text ﬁeld or textarea: 10.
Selenium Documentation, Release 1.0
element.clear();
10.4.4 Filling In Forms
We’ve already seen how to enter text into a textarea or text ﬁeld, but what about the other elements? You can “toggle” the state of checkboxes, and you can use “setSelected” to set something like an OPTION tag selected. Dealing with SELECT tags isn’t too bad:
WebElement select = driver.findElement(By.xpath( "//select" )); List<WebElement> allOptions = select.findElements(By.tagName( "option" )); for (WebElement option : allOptions) { System.out.println(String.format( "Value is: %s" , option.getValue())); option.setSelected(); }
This will ﬁnd the ﬁrst “SELECT” element on the page, and cycle through each of it’s OPTIONs in turn, printing out their values, and selecting each in turn. As you can see, this isn’t the most efﬁcient way of dealing with SELECT elements. WebDriver’s 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 you’ve ﬁ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 isn’t in a form, then the NoSuchElementException will be thrown:
element.submit();
10.4.5 Getting Visual Information And Drag And Drop
Sometimes you want to extract some visual information out of an element, perhaps to see if it’s visible or where it is on screen. You can ﬁnd out this information by casting the element to a RenderedWebElement:
WebElement plain = driver.findElement(By.name( "q" )); RenderedWebElement element = (RenderedWebElement) element;
110
Chapter 10. Selenium 2.0 and WebDriver
Selenium Documentation, Release 1.0
Not all drivers render their content to the screen (such as the HtmlUnit Driver), so it’s 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);
10.4.6 Moving Between Windows and Frames
It’s rare for a modern web application not to have any frames or to be constrained to a single window. WebDriver supports moving between named windows using the “switchTo” method:
driver.switchTo()); }
You can also swing from frame to frame (or into iframes):
driver.switchTo().frame( "frameName" );
It’s 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*.
10.4.7 Navigation: History and Location
Earlier, we covered navigating to a page using the “get” command (:
10.4. Next Steps For Using WebDriver
111
Selenium Documentation, Release 1.0
driver.navigate().to( "" );
To reiterate: “navigate().to()” and “get()” do exactly the same thing. One’s just a lot easier to type than the other! The “navigate” interface also exposes the ability to move backwards and forwards in your browser’s history:
driver.navigate().forward(); driver.navigate().back();
Please be aware that this functionality depends entirely on the underlying browser. It’s just possible that something unexpected may happen when you call these methods if you’re 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( "" ); // Now set the cookie. This one’s 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 }
10.4.9 Next, Next Steps!
This has been a high level walkthrough of WebDriver and some of its key capabilities. You may want to look at the Test Design Considerations chapter to get some ideas about how you can reduce the pain of maintaining your tests and how to make your code more modular.
10.5 WebDriver Implementations
10.5.1 HtmlUnit Driver
This is currently the fastest and most lightweight implementation of WebDriver. As the name suggests, this is based on HtmlUnit. Pros • Fastest implementation of WebDriver 112 Chapter 10. Selenium 2.0 and WebDriver
Although the DOM is deﬁned 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. knowing that there are more and more sites that rely on JavaScript? We took the conservative approach. When we say “JavaScript” we actually mean “JavaScript and the DOM”. enabling JavaScript support is very easy: HtmlUnitDriver driver = new HtmlUnitDriver(). With WebDriver. 10. Enabling JavaScript If you can’t wait. we had to make a choice.5. • Supports JavaScript. This will cause the HtmlUnit Driver to emulate Internet Explorer’s JavaScript handling by default. do we enable HtmlUnit’s JavaScript capabilities and run the risk of teams running into problems that only manifest themselves there. HtmlUnit has an impressively complete implementation of the DOM and has good support for using JavaScript. WebDriver Implementations 113 . we reassess this decision: we hope to enable JavaScript by default on the HtmlUnit at some point. despite its ability to mimic other browsers. and by default have disabled support when we use HtmlUnit.5.setJavascriptEnabled(true).Selenium Documentation. 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.0 • A pure Java solution and so it is platform independent. or do we leave JavaScript disabled. Release 1.2 Firefox Driver Pros • Runs in a real browser and supports JavaScript • Faster than the Internet Explorer Driver Cons • Slower than the HtmlUnit Driver 10. driver. With each release of both WebDriver and HtmlUnit.
contains all the dependencies (including the common library) required to run the Firefox Driver.ﬁrefox.3 Internet Explorer Driver This driver has been tested with Internet Explorer 6. Pros • Runs in a real browser and supports JavaScript Cons • Obviously the Internet Explorer Driver will only work on Windows! • Comparatively slow (though still pretty snappy :) 114 Chapter 10.0 and WebDriver . the Firefox driver creates an anonymous proﬁle Installing a Downloaded Binary The “wedriver-all.jar on your CLASSPATH.exe Windows Vista \Program Files (x86)\Mozilla Firefox\ﬁrefox.Selenium Documentation. 10. It has also been successfully tested on Vista. This defaults to driver. and WebDriver will do everything else for you.5. driver.jar or webdriver-all.bin webThe name of the proﬁle to use when starting Firefox. though.exe By default.reap_proﬁle 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.zip” which may be downloaded from the website.ﬁrefox. In order to use it: • Copy all the “jar” ﬁles on to your CLASSPATH. Selenium 2.getProperty() and set using System. 7 and 8 on XP.app/Contents/MacOS/ﬁrefox Windows XP %PROGRAMFILES%\Mozilla Firefox\ﬁrefox. Release 1. If you’re just interested in using this driver.0 Before Going Any Further The Firefox Driver contains everything it needs in the JAR ﬁle. carry on reading! Important System Properties The following system properties (read 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.proﬁle WebDriver creating an anonymous proﬁle webShould be “true” if temporary ﬁles and proﬁles should not be deleted driver. then all you need to do is put the webdriver-firefox. If you want to dig deeper.
Selenium Documentation.4 Chrome Driver See below for instructions on how to install the Chrome Driver.setProperty() in Java code or the -DpropertyName=value command line ﬂag) are used by the Chrome Driver: Property webdriver. You do not need to run an installer before using the Internet Explorer Driver. Please report any problems through the issue tracker. WebDriver Implementations 115 . Important System Properties The following system properties (read using System. 10.getProperty() and set using System. Cons • Slower than the HtmlUnit Driver Before Going Any Further The Chrome Driver contains everything it needs in the JAR ﬁle. and WebDriver will do everything else for you. Note that Chrome Driver is one of the newest drivers.5. Pros • Runs in a real browser and supports JavaScript • Because Chrome is a Webkit-based browser.chrome. If you’re just interested in using this driver.bin webdriver. Should be “true” if temporary ﬁles and proﬁles should not be deleted Normally the Chrome binary is assumed to be in the default location for your particular operating system: 10. the Chrome Driver may allow you to verify that your site works in Safari. then all you need to do is put webdriver-all.0 Installing Simply add webdriver-all. though some conﬁguration is required. Release 1.jar to your CLASSPATH.0 and above. Note that since Chrome uses its own V8 JavaScript engine rather than Safari’s Nitro engine. Required Conﬁguration Add every site you intend to visit to your “Trusted Sites” If you do not do this. JavaScript execution may differ.reap_proﬁle What it means The location of the binary used to control Chrome.5. then you will not be able to interact with the page. The Chrome Driver_ works with Google Chrome version 4.jar on your CLASSPATH.
exe C:\Users%USERNAME%\AppData\Local\Google\Chrome\Application\chrome.open( ". 10. In order to use it 116 Chapter 10.quit().google. // Get the underlying WebDriver implementation back.google. // A "base url".0 OS Linux Mac Windows XP Windows Vista Expected Location of Chrome /usr/bin/google-chrome /Applications/Google Chrome. // Create the Selenium implementation Selenium selenium = new WebDriverBackedSelenium(driver. It is used like so: // You may use any WebDriver implementation. Release 1.type( "name=q" . This will refer to the // same WebDriver instance as the "driver" variable above. Firefox is used here as an example WebDriver driver = new FirefoxDriver(). contains all the dependencies required to run the Chrome Driver. the JVM will continue running after //the browser has been closed.click( "name=btnG" ). Call stop on the WebDriverBackedSelenium instance //instead of calling driver. Otherwise.app/Contents/MacOS/GoogleChrome or /User/:username/:as_to_the_left %HOMEPATH%\Local Settings\Application Data\Google\Chrome\Application\chrome. selenium.stop().Selenium Documentation. selenium. close the browser.exe Installing a Downloaded Binary The “wedriver-all.0 and WebDriver .com" . // Perform actions with selenium selenium.zip” which may be downloaded from the website.getUnderlyingWebDriver() //Finally. selenium. "cheese" ). baseUrl).6. WebDriver driverInstance = ((WebDriverBackedSelenium) selenium). Selenium 2.com" ). 10.6 Emulating Selenium RC The Java version of WebDriver provides an implementation of the Selenium RC API. used by selenium to resolve relative URLs String baseUrl = ". copy all the “jar” ﬁles on to your CLASSPATH.
setBrowserName( "safari" ). "http:// WebDriver driver = new RemoteWebDriver(executor. CommandExecutor executor = new SeleneseCommandExecutor( "http:localhost:4444/" . but you should also expect support for the Internet Explorer Driver too.6. Also.7 Tips and Tricks 10. so in order to provide that support while still using the WebDriver API. you are limited by the JavaScript sandbox.7. profile. 10.1 Using Drag and Drop It may not be immediately obvious.2 Cons • Does not implement every method • More advanced Selenium usage (using “browserbot” or other built-in JavaScript methods from Selenium Core) may not work • Some methods may be slower due to underlying implementation differences 10.useragent. Tips and Tricks 117 .6. capabilities). Currently.findElement(By.7.3 Backing WebDriver with Selenium WebDriver doesn’t support as many browsers as Selenium RC does. There are currently some major limitations with this approach. 10.2 Changing the user agent This is easy with the Firefox Driver: FirefoxProfile profile = new FirefoxProfile().addAdditionalPreference( "general. RenderedWebElement to = (RenderedWebElement) driver. only the Firefox Driver supports this.id( "one" )).id( "two" )). Release 1.override" .7. you can make use of the SeleneseCommandExecutor It is done like this: Capabilities capabilities = new DesiredCapabilities() capabilities. but if you’re using a browser that supports it you can cast a WebElement to RenderedWebElement and then it’s easy to do drag and drop: // Note the casts RenderedWebElement from = (RenderedWebElement) driver. WebDriver driver = new FirefoxDriver(profile). notably that ﬁndElements doesn’t work as expected. from.findElement(By. "some UA string" ). because we’re using Selenium Core for the heavy lifting of driving the browser.Selenium Documentation.dragAndDropOn(to).0 10. 10.
Selenium Documentation, Release 1.0
10);
Alternatively, if the proﬁle isn’t already registered with Firefox:
File profileDir = new File( "path/to/top/level/of/profile" ); FirefoxProfile profile = new FirefoxProfile(profileDir); profile.addAdditionalPreferences(extraPrefs); WebDriver driver = new FirefoxDriver(profile); Enabling features that might not be wise to use in Firefox);
10.8
118
Chapter 10. Selenium 2.0 and WebDriver
Selenium Documentation, Release 1.0
10.8.1 Matching Implicit Attributes..
10.9.2 With Maven
If you want to use the HtmlUnit Driver, add the following dependency to your pom.xml:
<dependency> <groupId>org.seleniumhq.webdriver</groupId> <artifactId>webdriver-htmlunit</artifactId> <version>0.9.7376</version> </dependency>
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>
10.9. Getting and Using WebDriver
119
Selenium Documentation, Release 1.0
Finally, if you like to use any of our support classes, you should add the following dependency to your pom.xml:
<dependency> <groupId>org.seleniumhq.webdriver</groupId> <artifactId>webdriver-support</artifactId> <version>0.9.7376</version> </dependency>
10.10 Roadmap
The roadmap for WebDriver is available here
10.11 Further Resources
You can ﬁnd further resources for WebDriver in WebDriver’s wiki Appendixes:
120
Chapter 10. Selenium 2.0 and WebDriver
CHAPTER ELEVEN . 121 .NET CLIENT DRIVER CONFIGURATION . To Conﬁgure it with Visual do as Following. • Select Visual C# > Class Library > Name your project > Click on OK button. • Launch Visual Studio and navigate to File > New > Project.NET client Driver can be used with Microsoft Visual Studio.
.0 • A Class (. Rename it as appropriate.cs) is created.Selenium Documentation. • Under right hand pane of Solution Explorer right click on References > Add References.NET client driver conﬁguration . 122 Chapter 11. Release 1.
framework.UnitTests.Selenium.0 • Select following dll ﬁles . ThoughtWorks.nmock.dll. Selenium.Selenium. Release 1.core.dll.IntegrationTests.dll and click on Ok button 123 .dll. nunit.ThoughtWorks. ThoughtWorks.dll.Selenium Documentation. nunit.dll.Core.
124 Chapter 11.Selenium Documentation. Release 1.0 With This Visual Studio is ready for Selenium Test Cases. .NET client driver conﬁguration .
It should not be too different for higher versions of Eclipse • Launch Eclipse.Version: 3.3.0. Perl. • Select File > New > Other. 125 : 12. It is written primarily in Java and is used to develop applications in this language and.CHAPTER TWELVE. Python.1 Conﬁguring Selenium-RC With Eclipse Eclipse is a multi-language software development platform comprising an IDE and a plug-in system to extend it. Cobol. (Europa Release). PHP and more. by means of the various plug-ins. Following lines describes conﬁguration of Selenium-RC with Eclipse . in other languages as well as C/C++.
Selenium Documentation. Java Client Driver Conﬁguration .0 • Java > Java Project > Next 126 Chapter 12. Release 1.
Conﬁguring Selenium-RC With Eclipse 127 .5 selected in this example) > click Next 12.0 • Provide Name to your project. Select JDK in ‘Use a project Speciﬁc JRE’ option (JDK 1.1.Selenium Documentation. Release 1.
Selenium Documentation. Project speciﬁc libraries can be added here.) 128 Chapter 12. (This described in detail in later part of document.0 • Keep ‘JAVA Settings’ intact in next window. Java Client Driver Conﬁguration . Release 1.
0 • Click Finish > Click on Yes in Open Associated Perspective pop up window. 12. Conﬁguring Selenium-RC With Eclipse 129 .Selenium Documentation.1. Release 1.
0 This would create Project Google in Package Explorer/Navigator pane. Release 1.Selenium Documentation. Java Client Driver Conﬁguration . 130 Chapter 12.
Release 1.Selenium Documentation.0 • Right click on src folder and click on New > Folder 12.1. Conﬁguring Selenium-RC With Eclipse 131 .
Release 1.0 Name this folder as com and click on Finish button. 132 Chapter 12. Java Client Driver Conﬁguration .Selenium Documentation. • This should get com package insider src folder.
0 • Following the same steps create core folder inside com 12. Conﬁguring Selenium-RC With Eclipse 133 . Release 1.Selenium Documentation.1.
Java Client Driver Conﬁguration . Release 1. Create one more package inside src folder named testscripts.0 SelTestCase class can be kept inside core package. Test scripts package can further be segregated depending upon the project requirements. Please notice this is about the organization of project and it entirely depends on individual’s choice / organization’s standards. This is a place holder for test scripts. 134 Chapter 12.Selenium Documentation.
e.Selenium Documentation. This is a place holder for jar ﬁles to project (i. Conﬁguring Selenium-RC With Eclipse 135 . Right click on Project name > New > Folder. Selenium client driver. selenium server etc) 12.1. Release 1.0 • Create a folder called lib inside project Google.
136 Chapter 12. Release 1.Selenium Documentation. Java Client Driver Conﬁguration .0 This would create lib folder in Project directory.
1.Selenium Documentation.0 • Right click on lib folder > Build Path > Conﬁgure build Path 12. Release 1. Conﬁguring Selenium-RC With Eclipse 137 .
Java Client Driver Conﬁguration . Release 1. 138 Chapter 12.0 • 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.Selenium Documentation.
1. 12. Release 1.Selenium Documentation. Conﬁguring Selenium-RC With Eclipse 139 .0 After having added jar ﬁles click on OK button.
Selenium Documentation. Release 1.0 Added libraries would appear in Package Explorer as following: 140 Chapter 12. Java Client Driver Conﬁguration .
Conﬁguring Selenium-RC With Intellij 141 .2. Following lines describes conﬁguration of Selenium-RC with IntelliJ 6. Apache Ant and JUnit.0 It should not be very different for higher version of intelliJ. IntelliJ IDEA provides close integration with popular open source development tools such as CVS.0 12. 12. • Open a New Project in IntelliJ IDEA. Release 1. Intellij provides a set of integrated refactoring tools that allow programmers to quickly redesign their code. Subversion.Selenium Documentation.2 Conﬁguring Selenium-RC With Intellij IntelliJ IDEA is a commercial Java IDE by the company JetBrains.
0 • Provide name and location to Project. Java Client Driver Conﬁguration . 142 Chapter 12.Selenium Documentation. • Click Next and provide compiler output path. Release 1.
2.0 • Click Next and select the JDK to be used. Release 1. Conﬁguring Selenium-RC With Intellij 143 . • Click Next and select Single Module Project.Selenium Documentation. 12.
Java Client Driver Conﬁguration .0 • Click Next and select Java module. 144 Chapter 12. • Click Next and select Source directory. Release 1. • Click Next and provide Module name and Module content root.Selenium Documentation.
2. This will launch the Project Pan. Conﬁguring Selenium-RC With Intellij 145 . 12. • Click on Project Structure in Settings pan. Release 1. Adding Libraries to Project: • Click on Settings button in the Project Tool bar.Selenium Documentation.0 • At last click Finish.
Release 1. 146 Chapter 12.Selenium Documentation.0 • Select Module in Project Structure and browse to Dependencies tab. Java Client Driver Conﬁguration .
(Multiple Jars can be selected b holding down the control key.0 • Click on Add button followed by click on Module Library. • Browse to the Selenium directory and select selenium-java-client-driver.jar and seleniumserver.Selenium Documentation. 12.jar. Release 1. Conﬁguring Selenium-RC With Intellij 147 .).2.
Release 1. 148 Chapter 12.Selenium Documentation. Java Client Driver Conﬁguration .0 • Select both jar ﬁles in project pan and click on Apply button.
2.Selenium Documentation. Conﬁguring Selenium-RC With Intellij 149 . 12.0 • Now click ok on Project Structure followed by click on Close on Project Settings pan. Added jars would appear in project Library as following. Release 1.
Selenium Documentation. Java Client Driver Conﬁguration . 150 Chapter 12. Release 1.0 • Create the directory structure in src folder as following.
0 Note: This is not hard and fast convention and might very from project to project. testscripts package contains the test classes which extend the SelTestCase class. • Herein core contains the SelTestCase class which is used to create Selenium object and ﬁre up the browser. Conﬁguring Selenium-RC With Intellij 151 .Selenium Documentation. 12.2. Release 1. Hence extended structure would look as following.
Selenium Documentation. Java Client Driver Conﬁguration .0 152 Chapter 12. Release 1.
• Add to your test’s path the ﬁle selenium.py • Either write your Selenium test in Python or export a script from Selenium-IDE to a python ﬁle.com/Products/activepython/index.py • Run Selenium server from the console • Execute your test from a console or your Python IDE The following steps describe the basic installation procedure. Download Active python’s installer from ActiveState’s ofﬁcial site:. – Windows 1.x-win32-x86. as in most linux distributions python is already pre-installed by default.x.CHAPTER THIRTEEN PYTHON CLIENT DRIVER CONFIGURATION • Download Selenium-RC from the SeleniumHQ downloads page • Extract the ﬁle selenium. • Installing Python Note: This will cover python installation on Windows and Mac only.msi) 153 . After following this. Run the installer downloaded (ActivePython-x.mhtml 2. (even write tests in a text processor and run them from command line!) without any extra work (at least on the Selenium side). the user can start using the desired IDE.x.
Release 1. To install an extra Python.Selenium Documentation. get a universal binary at. 154 Chapter 13.x).org/ (packages for Python 2. Python Client Driver Conﬁguration .5.pythonmac.0 • Mac The latest Mac OS X version (Leopard at this time) comes with Python pre-installed.
You will ﬁnd the module in the extracted folder. Download the last version of Selenium Remote Control from the downloads page 2. • Installing the Selenium driver client for python 1.Selenium Documentation. you’re done! Now any python script that you create can import selenium and start interacting with the browsers. Release 1. It contains a . 155 .dmg ﬁle that you can mount. Extract the content of the downloaded zip ﬁle 3.py) in the folder C:/Python25/Lib (this will allow you to import it directly in any script you write).0 You will get a . it’s located inside seleniumpython-driver-client. Copy the module with the Selenium’s driver for Python (selenium.pkg ﬁle that you can launch. Congratulations.
0 156 Chapter 13. Python Client Driver Conﬁguration . Release 1.Selenium Documentation.
14.CHAPTER FOURTEEN LOCATING TECHNIQUES 14. Useful for forms and tables. 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. which can make them difﬁcult to locate. the contains function can be used.3 contains If an element can be located by a value that could be surrounded by other text. ’text-’)] 14.locate elements based on their siblings. Incidentally. however with CSS locators this is much simpler (and faster).1 Locating elements based on class In order to locate an element based on associated class in XPath you must consider that the element could have multiple classes and deﬁned in any order.1 text Not yet written .1 Useful XPATH patterns 14.1.2 Starting to use CSS instead of XPATH 14. 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.locate elements based on the text content of the node.heading 14. 14. To demonstrate.4 siblings Not yet written .1. this would be much neater (and probably faster) using the CSS locator strategy css=span.1. One simple solution is to use XPath functions and base the location on what you do know about the element. For example.1. ’heading’)]. ’article-heading’)] 157 . • XPath: //div[contains(@class.2 starts-with Many sites use dynamic values for element’s id attributes.2.
Selenium Documentation. Locating Techniques . Release 1.article-heading 158 Chapter 14.0 • CSS: css=div.