========================= Selenium Reference ========================= -------- Concepts -------- A **command** is what tells Selenium what to do. Selenium commands come in two 'flavors', **Actions** and **Assertions**. Each command call is one line in the test table of the form: ======= ====== ===== command target value ======= ====== ===== **Actions** are commands that generally manipulate the state of the application. They do things like "click this link" and "select that option". If an Action fails, or has an error, the execution of the current test is stopped. **Assertions** verify the state of the application conforms to what is expected. Examples include "make sure the page title is X" and "verify that this checkbox is checked". It is possible to tell Selenium to stop the test when an Assertion fails, or to simply record the failure and continue. **Element Locators** tell Selenium which HTML element a command refers to. Many commands require an Element Locator as the "target" attribute. Examples of Element Locators include "elementId" and "document.forms[0].element". These are described more clearly in the next section. **Patterns** are used for various reasons, e.g. to specify the expected value of an input field, or identify a select option. Selenium supports various types of pattern, including regular-expressions, all of which are described in more detail below. ----------------- Element Locators ----------------- Element Locators allow Selenium to identify which HTML element a command refers to. The format of a locator is: *locatorType*\ **=**\ *argument* We support the following strategies for locating elements: **id=**\ *id* Select the element with the specified @id attribute. **name=**\ *name* Select the first element with the specified @name attribute. - username - name=username The name may optionally be following by one or more *element-filters*, separated from the name by whitespace. If the *filterType* is not specified, **value** is assumed. - name=flavour value=chocolate **identifier=**\ *id* Select the element with the specified @id attribute. If no match is found, select the first element whose @name attribute is *id*. **dom=**\ *javascriptExpression* Find an element using JavaScript traversal of the HTML Document Object Model. DOM locators *must* begin with "document.". - dom=document.forms['myForm'].myDropdown - dom=document.images[56] **xpath=**\ *xpathExpression* Locate an element using an XPath expression. - xpath=//img[@alt='The image alt text'] - xpath=//table[@id='table1']//tr[4]/td[2] **link=**\ *textPattern* Select the link (anchor) element which contains text matching the specified *pattern*. - link=The link text If no *locatorType* is specified, Selenium uses: * **dom**, for locators starting with "document." * **xpath**, for locators starting with "//" * **identifier**, otherwise --------------- Element Filters --------------- Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator. Filters look much like locators, ie. *filterType*\ **=**\ *argument* Supported element-filters are: **value=**\ *valuePattern* Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons. **index=**\ *index* Selects a single element based on its position in the list offset from zero). ------------------------ Select Option Specifiers ------------------------ Select Option Specifiers provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Specifier. **label=**\ *labelPattern* matches options based on their labels, i.e. the visible text. - label=regexp:^[Oo]ther **value=**\ *valuePattern* matches options based on their values. - value=other **id=**\ *id* matches options based on their ids. - id=option1 **index=**\ *index* matches an option based on its index (offset from zero). - index=2 If no optionSpecifierType prefix is provided, the default behaviour is to match on **label**. ------------------------ String-match Patterns ------------------------ Various Pattern syntaxes are available for matching string values: **glob:**\ *pattern* Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a kind of limited regular-expression syntax typically used in command-line shells. In a glob pattern, "*" represents any sequence of characters, and "?" represents any single character. Glob patterns match against the entire string. **regexp:**\ *regexp* Match a string using a regular-expression. The full power of JavaScript regular-expressions is available. **exact:**\ *string* Match a string exactly, verbatim, without any of that fancy wildcard stuff. If no pattern prefix is specified, Selenium assumes that it's a "glob" pattern. ---------------- Selenium Actions ---------------- Actions tell Selenium to do something in the application. They generally represent something a user would do. Many **Actions** can be called with the "AndWait" suffix. This suffix tells Selenium that the action will cause the browser to make a call to the server, and that Selenium should wait for a new page to load. **open**\ ( *url* ) Opens a URL in the test frame. This accepts both relative and absolute URLs. The "open" command waits for the page to load before proceeding, ie. the "AndWait" suffix is implicit. *Note*: The URL must be on the same site as Selenium due to security restrictions in the browser (Cross Site Scripting). **examples:** ==== ================= ===== open /mypage open http://localhost/ ==== ================= ===== **click**\ ( *elementLocator* ) Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), use "clickAndWait". **examples:** ============ ================== ===== click aCheckbox clickAndWait submitButton clickAndWait anyLink ============ ================== ===== **type**\ ( *inputLocator*, *value* ) Sets the *value* of an input field, as though you typed it in. Can also be used to set the value of combo boxes, check boxes, etc. In these cases, *value* should be the value of the option selected, not the visible text. **examples:** =========== ========================== ========== type nameField John Smith typeAndWait textBoxThatSubmitsOnChange newValue =========== ========================== ========== **select**\ ( *dropDownLocator*, *optionSpecifier* ) Select an option from a drop-down, based on the *optionSpecifier*. If more than one option matches the specifier (e.g. due to the use of globs like "f*b*", or due to more than one option having the same label or value), then the first matches is selected. **examples:** ============= ================ ========== select dropDown Australian Dollars select dropDown index=0 selectAndWait currencySelector value=AUD selectAndWait currencySelector label=Aus*lian D*rs ============= ================ ========== **check**\ ( *toggleButtonLocator* ) Check a toggle-button (ie. a check-box or radio-button). Note: if addressing the toggle-button element by name, you'll need to append an element-filter (e.g. typically by value), since toggle-button groups consist of input-elements with the same name. **examples:** ============= ======================== ========== check name=flavour value=honey check flavour honey ============= ======================== ========== **uncheck**\ ( *toggleButtonLocator* ) Un-check a toggle-button. **selectWindow**\ ( *windowId* ) Selects a popup window. Once a popup window has been selected, all commands go to that window. To select the main window again, use "null" as the target. **target:** The id of the window to select. **value:** *ignored* **examples:** ============ ============= ===== selectWindow myPopupWindow selectWindow null ============ ============= ===== **goBack**\ () Simulates the user clicking the "back" button on their browser. **examples:** ============= ==== ===== goBackAndWait ============= ==== ===== **close**\ () Simulates the user clicking the "close" button in the titlebar of a popup window. **examples:** ====== ==== ===== close ====== ==== ===== **pause**\ ( *milliseconds* ) Pauses the execution of the test script for a specified amount of time. This is useful for debugging a script or pausing to wait for some server side action. **examples:** ===== ==== ===== pause 5000 pause 2000 ===== ==== ===== **fireEvent**\ ( *elementLocator*, *eventName* ) Explicitly simulate an event, to trigger the corresponding "on\ *event*" handler. **examples:** ========= =========== ======== fireEvent textField focus fireEvent dropDown blur ========= =========== ======== **waitForValue**\ ( *inputLocator*, *value* ) Waits for a specified input (e.g. a hidden field) to have a specified *value*. Will succeed immediately if the input already has the value. This is implemented by polling for the value. Warning: can block indefinitely if the input never has the specified value. **example:** ============ ================ ========== waitForValue finishIndication isfinished ============ ================ ========== **store**\ ( *valueToStore*, *variableName* ) Stores a value into a variable. The value can be constructed using either variable substitution or JavaScript evaluation, as detailed in 'Parameter construction and Variables' (below). **examples:** ========== ============================================ ========= store Mr John Smith fullname store ${title} ${firstname} ${surname} fullname store javascript{Math.round(Math.PI * 100) / 100} PI ========== ============================================ ========= **storeValue**\ ( *inputLocator*, *variableName* ) Stores the value of an input field into a variable. **examples:** ========== ========= ========= storeValue userName userID type userName ${userID} ========== ========= ========= **storeText**\ ( *elementLocator*, *variableName* ) Stores the text of an element into a variable. **examples:** =========== =========== ==================== storeText currentDate expectedStartDate verifyValue startDate ${expectedStartDate} =========== =========== ==================== **storeAttribute**\ ( *elementLocator*\ @\ *attributeName*, *variableName* ) Stores the value of an element attribute into a variable. **examples:** =============== ============== ==================== storeAttribute input1@\ class classOfInput1 verifyAttribute input2@\ class ${classOfInput1} =============== ============== ==================== **chooseCancelOnNextConfirmation**\ () By default, Selenium's overridden window.confirm() function will return true, as if the user had manually clicked OK. After running this command, the next call to confirm() will return false, as if the user had clicked Cancel. **examples:** ============================== ===== ===== chooseCancelOnNextConfirmation ============================== ===== ===== **answerOnNextPrompt**\ ( *answerString* ) Instructs Selenium to return the specified *answerString* in response to the next call to window.prompt(). **examples:** ========================== ========= ===== answerOnNextPrompt Kangaroo ========================== ========= ===== ------------------- Selenium Assertions ------------------- Assertions are used to verify the state of the application. They can be used to check the value of a form field, the presense of some text, or the URL of the current page. All Selenium assertions can be used in 2 modes, "assert" and "verify". These behave identically, except that when an "assert" fails, the test is aborted. When a "verify" fails, the test will continue execution. This allows a single "assert" to ensure that the application is on the correct page, followed by a bunch of "verify" assertions to test form field values, labels, etc. A growing number of assertions have a negative version. In most cases, except where indicated, if the positive assertion is of the form **assertXYZ**, then the negative cases will be of the form **assertNotXYZ**. **assertLocation**\ ( *relativeLocation* ) **examples:** ============== ======= ===== verifyLocation /mypage assertLocation /mypage ============== ======= ===== **assertTitle**\ ( *titlePattern* ) Verifies the title of the current page. **examples:** =========== ======= ===== verifyTitle My Page assertTitle My Page =========== ======= ===== **assertNotTitle**\ ( *titlePattern* ) Verifies that the title of the current page does not match the specified pattern. **assertValue**\ ( *inputLocator*, *valuePattern* ) Verifies the value of an input field (or anything else with a value parameter). For checkbox/radio elements, the value will be "on" or "off" depending on whether the element is checked or not. **examples:** =========== =========================== ========== verifyValue nameField John Smith assertValue document.forms[2].nameField John Smith =========== =========================== ========== **assertNotValue**\ ( *inputLocator*, *valuePattern* ) Verifies the value of an input field does not match the specified pattern. **assertSelected**\ ( *selectLocator*, *optionSpecifier* ) Verifies that the selected option of a drop-down satisfies the *optionSpecifier*. **examples:** ============== =========================== ========== verifySelected dropdown2 John Smith verifySelected dropdown2 value=js*123 assertSelected document.forms[2].dropDown label=J* Smith assertSelected document.forms[2].dropDown index=0 ============== =========================== ========== **assertSelectOptions**\ ( *selectLocator*, *optionLabelList* ) Verifies the labels of all options in a drop-down against a comma-separated list. Commas in an expected option can be escaped as "\,". **examples:** =================== =========================== ==================== verifySelectOptions dropdown2 John Smith,Dave Bird assertSelectOptions document.forms[2].dropDown Smith\\, J,Bird\\, D =================== =========================== ==================== **assertChecked**\ ( *toggleButtonLocator* ) Verifies that the specified toggle-button element is checked. **examples:** ============= ======================== ========== verifyChecked flavour honey ============= ======================== ========== **assertText**\ ( *elementLocator*, *textPattern* ) Verifies the text of an element. This works for any element that contains text. This command uses either the textContent (Mozilla-like browsers) or the innerText (IE-like browsers) of the element, which is the rendered text shown to the user. **examples:** ========== ==================== ========== verifyText statusMessage Successful assertText //div[@id='foo']//h1 Successful ========== ==================== ========== **assertNotText**\ ( *elementLocator*, *textPattern* ) Verifies that the text of an element does not match the specified pattern. **assertAttribute**\ ( *elementLocator*\ @\ *attributeName*, *valuePattern* ) Verifies the value of an element attribute. **examples:** =============== ====================== ========== verifyAttribute txt1@\ class bigAndBold assertAttribute document.images[0]@alt alt-text verifyAttribute //img[@id='foo']/@alt alt-text =============== ====================== ========== **assertNotAttribute**\ ( *elementLocator*\ @\ *attributeName*, *valuePattern* ) Verifies that the value of an element attribute does not match the specified pattern. **assertTextPresent**\ ( *text* ) Verifies that the specified text appears somewhere on the rendered page shown to the user. **examples:** ================= ====================== ===== verifyTextPresent You are now logged in. assertTextPresent You are now logged in. ================= ====================== ===== **assertTextNotPresent**\ ( *text* ) Verifies that the specified text does NOT appear anywhere on the rendered page. **assertElementPresent**\ ( *elementLocator* ) Verifies that the specified element is somewhere on the page. **examples:** ==================== ================= ===== verifyElementPresent submitButton assertElementPresent //img[@alt='foo'] ==================== ================= ===== **assertElementNotPresent**\ ( *elementLocator* ) Verifies that the specified element is NOT on the page. **examples:** ======================= ============ ===== verifyElementNotPresent cancelButton assertElementNotPresent cancelButton ======================= ============ ===== **assertTable**\( *cellAddress*, *valuePattern* ) Verifies the text in a cell of a table. The *cellAddress* syntax *tableName.row.column*, where row and column start at 0. **examples:** =========== =========== ========= verifyTable myTable.1.6 Submitted assertTable results.0.2 13 =========== =========== ========= **assertNotTable**\( *cellAddress*, *valuePattern* ) Verifies that the text in a cell of a table does not match the specified pattern. Note that this will fail if the table cell does not exist. **assertVisible**\ ( *elementLocator* ) Verifies that the specified element is both present *and* visible. An element can be rendered invisible by setting the CSS "visibility" property to "hidden", or the "display" property to "none", either for the element itself or one if its ancestors. **examples:** ============= ======== ===== verifyVisible postcode assertVisible postcode ============= ======== ===== **assertNotVisible**\ ( *elementLocator* ) Verifies that the specified element is NOT visible. Elements that are simply not present are also considered invisible. **examples:** ================ ======== ===== verifyNotVisible postcode assertNotVisible postcode ================ ======== ===== **verifyEditable / assertEditable**\ ( *inputLocator* ) Verifies that the specified element is editable, ie. it's an input element, and hasn't been disabled. **examples:** ============== ======== ===== verifyEditable shape assertEditable colour ============== ======== ===== **assertNotEditable**\ ( *inputLocator* ) Verifies that the specified element is NOT editable, ie. it's NOT an input element, or has been disabled. **assertAlert**\ ( *messagePattern* ) Verifies that a JavaScript alert was generated, with the specified message. If an alert is generated but you do not verify it, the next Selenium action will fail. Alerts must be verified in the order that they were generated. **examples:** ============== ==================== ===== verifyAlert Invalid Phone Number assertAlert Invalid Phone Number ============== ==================== ===== **assertConfirmation**\ ( *messagePattern* ) Verifies that a JavaScript confirmation dialog was generated, with the specified message. By default, the confirm function will return true, having the same effect as manually clicking OK. This can be changed by prior execution of the **chooseCancelOnNextConfirmation** command (see above). Like alerts, any unexpected confirmation will cause the test to fail, and confirmations must be verified in the order that they were generated. **examples:** ================== ==================== ===== assertConfirmation Remove this user? verifyConfirmation Are you sure? ================== ==================== ===== **assertPrompt**\ ( *messagePattern* ) Verifies that a JavaScript prompt dialog was generated, with the specified message. Successful handling of the prompt requires prior execution of the **answerOnNextPrompt** command (see above). Like alerts, unexpected prompts will cause the test to fail, and they must be verified in the order that they were generated. **examples:** ================== ============================= ===== answerOnNextPrompt Joe click id=delegate verifyPrompt Delegate to who? ================== ============================= ===== ------------------------------------------- Handling of alert(), confirm() and prompt() ------------------------------------------- Selenium overrides the default implementations of the JavaScript window.alert(), window.confirm() and window.prompt() functions, enabling tests to simulate the actions of the user when these occur. Under normal condition, no visible JavaScript dialog-box will appear. If your application generates alerts, confirmations, or prompts, you *must* use assertAlert, assertConfirmation and assertPrompt (or their "verify" equivalents) to handle them. Any unhandled alerts will result in the test failing. *PROVISO:* Selenium is unable to handle alerts, confirmations, or prompts raised during processing of the 'onload' event. In such cases a visible dialog-box WILL appear, and Selenium will hang until you manually handle it. This is an unfortunate restriction, but at this time we have no solution. ------------------------------------ Parameter construction and Variables ------------------------------------ All Selenium command parameters can be constructed using both simple variable substitution as well as full JavaScript. Both of these mechanisms can access previously stored variables, but do so using different syntax. **Stored Variables** The commands *store*, *storeValue* and *storeText* can be used to store a variable value for later access. Internally, these variables are stored in a map called "storedVars", with values keyed by the variable name. These commands are documented in the command reference. **Variable substitution** Variable substitution provides a simple way to include a previously stored variable in a command parameter. This is a simple mechanism, by which the variable to substitute is indicated by ${variableName}. Multiple variables can be substituted, and intermixed with static text. Example: ========== ==================== ========== store Mr title storeValue nameField surname store ${title} ${surname} fullname type textElement Full name is: ${fullname} ========== ==================== ========== **JavaScript evaluation** JavaScript evaluation provides the full power of JavaScript in constructing a command parameter. To use this mechanism, the *entire* parameter value must be prefixed by 'javascript{' with a trailing '}'. The text inside the braces is evaluated as a JavaScript expression, and can access previously stored variables using the *storedVars* map detailed above. Note that variable substitution cannot be combined with JavaScript evaluation. Example: ========== ================================================ ========== store javascript{'merchant' + (new Date()).getTime()} merchantId type textElement javascript{storedVars['merchantId'].toUpperCase()} ========== ================================================ ========== ------------------ Extending Selenium ------------------ It can be quite simple to extend Selenium, adding your own actions, assertions and locator-strategies. This is done with JavaScript by adding methods to the Selenium object prototype, and the PageBot object prototype. On startup, Selenium will automatically look through methods on these prototypes, using name patterns to recognise which ones are actions, assertions and locators. The following examples try to give an indication of how Selenium can be extended with JavaScript. **Actions** All *doFoo* methods on the Selenium prototype are added as actions. For each action *foo* there is also an action *fooAndWait* registered. An action method can take up to 2 parameters, which will be passed the second and third column values in the test. Example: Add a "typeRepeated" action to Selenium, which types the text twice into a text box. :: Selenium.prototype.doTypeRepeated = function(locator, text) { // All locator-strategies are automatically handled by "findElement" var element = this.page().findElement(locator); // Create the text to type var valueToType = text + text; // Replace the element text with the new text this.page().replaceText(element, valueToType); }; **Assertions** All *assertFoo* methods on the Selenium prototype are added as assertions. For each assertion *foo* there is an *assertFoo* and *verifyFoo* registered. An assert method can take up to 2 parameters, which will be passed the second and third column values in the test. Example: Add a *valueRepeated* assertion, that makes sure that the element value consists of the supplied text repeated. The 2 commands that would be available in tests would be *assertValueRepeated* and *verifyValueRepeated*. :: Selenium.prototype.assertValueRepeated = function(locator, text) { // All locator-strategies are automatically handled by "findElement" var element = this.page().findElement(locator); // Create the text to verify var expectedValue = text + text; // Get the actual element value var actualValue = element.value; // Make sure the actual value matches the expected Assert.matches(expectedValue, actualValue); }; **Locator Strategies** All *locateElementByFoo* methods on the PageBot prototype are added as locator-strategies. A locator strategy takes 2 parameters, the first being the locator string (minus the prefix), and the second being the document in which to search. Example: Add a "valuerepeated=" locator, that finds the first element a value attribute equal to the the supplied value repeated. :: // The "inDocument" is a the document you are searching. PageBot.prototype.locateElementByValueRepeated = function(text, inDocument) { // Create the text to search for var expectedValue = text + text; // Loop through all elements, looking for ones that have // a value === our expected value var allElements = inDocument.getElementsByTagName("*"); for (var i = 0; i < allElements.length; i++) { var testElement = allElements[i]; if (testElement.value && testElement.value === expectedValue) { return testElement; } } return null; }; **user-extensions.js** By default, Selenium looks for a file called "user-extensions.js", and loads the JavaScript code found in that file. This file provides a convenient location for adding features to Selenium, without needing to modify the core Selenium sources. In the standard distibution, this file does not exist. Users can create this file and place their extension code in this common location, removing the need to modify the Selenium sources, and hopefully assisting with the upgrade process. ------------------ :