Short Notes on Selenium

Introducing Selenium:
Selenium is a robust set of tools that supports rapid development of test automation for web-based applications. Selenium provides a rich set of testing functions specifically geared to the needs of testing of a web application. These operations are highly flexible, allowing many options for locating UI elements and comparing expected test results against actual application behavior.
Selenium is composed of three major tools. Each one has a specific role in aiding the development of web application test automation.
1.Selenium-IDE
2.Selenium-RC (Remote Control)
3.Selenium-Grid

Selenium-IDE is for building Selenium test cases and provides an easy-to-use interface for developing and running individual test cases or entire test suites. Selenium-IDE has a recording feature, which will keep account of user actions as they are performed and store them as a reusable script to play back. It also has a context menu (right-click) integrated with the Firefox browser, which allows the user to pick from a list of assertions and verifications for the selected location. Selenium-IDE also offers full editing of test cases for more precision and control. Although Selenium-IDE is a Firefox only add-on, tests created in it can also be run against other browsers by using Selenium-RC and specifying the name of the test suite on the command line.

Selenium-RC (Remote Control)
Selenium-RC allows the test automation developer to use a programming language for maximum flexibility and extensibility in developing test logic. For instance, if the application under test returns a result set, and if the automated test program needs to run tests on each element in the result set, the programming language’s iteration support can be used to iterate through the result set, calling Selenium commands to run tests on each item. Selenium-RC provides an API (Application Programming Interface) and library for each of its supported languages: HTML, Java, C#, Perl, PHP, Python, and Ruby. This ability to use Selenium-RC with a high-level programming language to develop test cases also allows the automated testing to be integrated with a project’s automated build environment.

Selenium-Grid
Selenium-Grid allows the Selenium-RC solution to scale for large test suites or test suites that must be run in multiple environments. With Selenium-Grid, multiple instances of Selenium-RC are running on various operating system and browser configurations; Each of these when launching register with a hub. When tests are sent to the hub they are then redirected to an available Selenium-RC, which will launch the browser and run the test. This allows for running tests in parallel, with the entire test suite theoretically taking only as long to run as the longest individual test.

What is Selenium?
Selenium is a UI test tool for web applications. Selenium tests run directly in a browser, just as real users do. Those tests can run in Internet Explorer, Mozilla Firefox on Windows, Linux, and Macintosh. No other test tool covers such a wide array of platforms.

What is Selenium IDE?
Selenium IDE is an integrated development environment (thats what IDE stands for for those who don’t know) for Selenium tests. It is implemented as a Firefox extension, and allows you to record, edit, and debug tests. Selenium IDE includes the entire Selenium Core, allowing you to easily and quickly record and play back tests in the actual environment that they will run. Selenium IDE is not only a recording tool: it is a complete IDE. You can choose to use its recording capability, or you may edit your scripts by hand. With autocomplete support and the ability to move commands around quickly, Selenium IDE is the ideal environment for creating Selenium tests no matter what style of tests you prefer.

Installation:
A firefox extension is an installable enhancement to the browser’s functionality and add features to the application or allows existing features to be modified. Since Selenium IDE is a Firefox extension you get it by downloading and installing the firefox extension.
1. Go to SeleniumHQ
2. Click the SeleniumIDE link under the download bullet of the latest version. This will pop up a box and a button should appear briefly that says “Install Now”. Click on that.
3. This will pop up a box and install the extension. Once its finished click the button on the bottom right corner that says “Restart Firefox”.
4.Go to Tools in Firefox there you found the SeleniumIDE.

How do I run/use the Selenium IDE?
These are the main controls of the SeleniumIDE
Record: Records the user’s browser actions.
Run: Runs the currently selected test. When only a single test is loaded this button and the Run All button have the same effect.
Run All: Runs the entire test suite when a test suite with multiple test cases is loaded.
Pause/Resume: Allows stopping and re-starting of a running test case.
Step: Allows you to “step” through a test case by running it one command at a time. Use for debugging test cases.
Speed Control: controls how fast your test case runs.
TestRunner Mode: Allows you to run the test case in a browser loaded with the Selenium-Core TestRunner. The TestRunner is not commonly used now and is likely to be deprecated. This button is for evaluating test cases for backwards compatibility with the TestRunner. Most users will probably not need this button.
Apply Rollup Rules: This advanced feature allows repetitive sequences of Selenium commands to be grouped into a single action. Detailed documentation on rollup rules can be found in the UI-Element Documentation on the Help menu.


How do I run a script that I recorded in Firefox against Internet Explorer?
You would need to install Selenium Core or Selenium RC in order to be able to do this. Selenium Core has to be run on the same webserver as the application you are trying to test. So this probably won’t work for non-developer types who don’t have access to what is put on the webserver. If that is the case then you might want to look into using Selenium RC.For information on using and setting up Selenium Core take a look Here and for using Selenium RC look Here.

What is the difference between run, walk, and step?
The only difference between run and walk is that run is faster. They behave exactly the same way. Step on the other requires you to actually push the blue downward right angle arrow key to continue to the next step. When you use Run and Walk with breakpoints the pause button will turn into a pause/resume button. In order to keep going to the next breakpoint just hit the pause/resume button. If you hit play again from a breakpoint or from any command it will start the script over from the beginning.

How do I use breakpoints?
Sometimes when you are running your scripts something breaks and you might want to see the state of the application just before that break or maybe the script exits before you get a chance to see the error on the screen in these cases breakpoints are awesome. Simply chose the line in your script where you want it to stop and put a break point. You do this by right clicking and selecting “Toggle Breakpoint”. Now when you hit the play button it will stop at that command. Additionally you can set a break point and then step through the application from that point on using the step feature.

Can you give an example of when you would want to save the scripts in a different language.
Sometimes QA people or Buisness Analysts or even end users may want to submit the test they used to create the error back to the developers, in this case the developers may like to have the test in the language which they are writing the application in. It may also be the case that the developers themselves change the language based on what they were given or who they may be giving the tests to. In order to change the language the test is output in go to the Selenium IDE tool bar select Options -> Format and then select the language you want the test in.

What is the difference between deleteCookie and deleteCookieAndWait?
In a nut shell don’t use the “andWait” commands. The “andWait” commands should be gone as of the latest version (they are still there but they all do the same things as their couterpart commands i.e deleteCookieAndWait does exactly what deleteCookie does) but for those still on the old version here is the explanation. Typically anytime you see the “andWait” or “withWait” piece tacked on to the end of a command it simply means that you want your script to stop executing any additional commands until it gets back a response saying the command has finished.

How would you handle situations where you would need to change a piece of data entered each time you run the script?
To be honest I haven’t quite figured out how to do this. I am going to try to play around with it a bit and see if I can figure something out. As soon as I do I’ll post an answer to this.

What does the log at the bottom tell me and how do I interpret what it is saying?
From the point of view of a non-technical person the log basically just tells you information about what has happened. Maybe you clicked the back button and the ide didn’t recognize that click and you then clicked some image. In this case you would get an error stating it could not find the element you told it to find. As it turns out the script isn’t on the right page so of course it wouldn’t find it. There are lots of reasons why you might get an error and usually if you step through your script you will find that you are not on the page you expect to be when the command was trying to be executed or some other trivial thing has happened. The log also has general information in the info tag that tells you which commands have been executed etc. All this maybe helpful when trying to figure out what has gone wrong.

How to Build Test Cases :
There are three primary methods for developing test cases. Frequently, a test developer will require all three techniques.
Recording
Many first-time users begin by recording a test case from their interactions with a website. When Selenium-IDE is first opened, the record button is ON by default. If you do not want Selenium-IDE to begin recording automatically you can turn this off by going under Options > Options... and deselecting “Start recording immediately on open. During recording, Selenium-IDE will automatically insert commands into your test case based on your actions. Typically, this will include:

1.clicking a link - click or clickAndWait commands
2.entering values - type command
3.selecting options from a drop-down listbox - select command
4.clicking checkboxes or radio buttons - click command

Here are some “gotchas” to be aware of:
1.The type command may require clicking on some other area of the web page for it to record.
2.Following a link usually records a click command. You will often need to change this to clickAndWait to ensure your test case pauses until the new page is completely loaded. Otherwise, your test case will continue running commands before the page has loaded all its UI elements. This will cause unexpected test case failures.

Getting Started with SeleniumIDE :
Most people get started with Selenium-IDE. This is what we recommend. It’s an easy way to get familiar with Selenium commands quickly. You can develop your first script in just a few minutes. Selenium-IDE is also very easy to install. See the chapter on Selenium-IDE for specifics.
You may also run your scripts from the Selenium-IDE. It’s simple to use and is recommended for less-technical users. The IDE allows developing and running tests without the need for programming skills as required by Selenium-RC. The Selenium-IDE can serve as an excellent way to train junior-level employees in test automation. Anyone who understands how to conduct manual testing of a website can easily transition to using the Selenium-IDE for running and developing tests.
Some testing tasks are too complex though for the Selenium-IDE. When programming logic is required Selenium-RC must be used. For example, any tests requiring iteration, such as testing each element of a variable length list requires running the script from a programming language. Selenium-IDE does not support iteration or condition statements.
Finally, Selenium-Core is another way of running tests. One can run test scripts from a web-browser using the HTML interface TestRunner.html. This is the original method for running Selenium commands. It has limitations though similar to Selenium-IDE, it does not support iteration.
Selenium-Core also cannot switch between http and https protocols. Since the development of Selenium-IDE and Selenium-RC, more people are use these tools rather than Selenium-Core.

Selenese :
Selenium provides a rich set of commands for fully testing your web-app in virtually any way you can imagine. The command set is often called selenese. These commands essentially create a testing language. In selenese, one can test the existence of UI elements based on their HTML tags, test for specific content, test for broken links, input fields, selection list options, submitting forms, and table data among other things. In addition Selenium commands support testing of window size, mouse position, alerts, Ajax functionality, pop up windows, event handling, and many other web-application features. The Command Reference lists all the available commands.
A command is what tells Selenium what to do. Selenium commands come in three “flavors”: Actions, Accessors and Assertions.
1.Actions are commands that generally manipulate the state of the application. They do things like “click this link” and “select that option”. If an Action fails, or has an error, the execution of the current test is stopped.
2.Many Actions can be called with the “AndWait” suffix, e.g. “clickAndWait”. This suffix tells Selenium that the action will cause the browser to make a call to the server, and that Selenium should wait for a new page to load.
3.Accessors examine the state of the application and store the results in variables, e.g. “storeTitle”. They are also used to automatically generate Assertions.
4.Assertions are like Accessors, but they verify that the state of the application conforms to what is expected. Examples include “make sure the page title is X” and “verify that this checkbox is checked”.
5.All Selenium Assertions can be used in 3 modes: “assert”, “verify”, and ” waitFor”. For example, you can “assertText”, “verifyText” and “waitForText”. When an “assert” fails, the test is aborted. When a “verify” fails, the test will continue execution, logging the failure. This allows a single “assert” to ensure that the application is on the correct page, followed by a bunch of “verify” assertions to test form field values, labels, etc.
6.“waitFor” commands wait for some condition to become true (which can be useful for testing Ajax applications). They will succeed immediately if the condition is already true. However, they will fail and halt the test if the condition does not become true within the current timeout setting (see the setTimeout action below).

Script Syntax :
Selenium commands are simple, they consist of the command and two parameters. For example:
verifyText //div//a[2] Login
The parameters are not always required; it depends on the command. In some cases both are required, in others one parameter is required, and in still others the command may take no parameters at all. Here are a couple more examples:
goBackAndWait verifyTextPresent Welcome to My Home Page
type id=phone (555) 666-7066
type id=address1 ${myVariableAddress}

The command reference describes the parameter requirements for each command.
Parameters vary, however they are typically:
1.a locator for identifying a UI element within a page.
2.a text pattern for verifying or asserting expected page content
3.a text pattern or a selenium variable for entering text in an input field or for selecting an option from an option list.
The Selenese HTML syntax can be used to write and run tests without requiring knowledge of a programming language. With a basic knowledge of selenese and Selenium-IDE you can quickly produce and run testcases.

Test Suites :
A test suite is a collection of tests. Often one will run all the tests in a test suite as one continuous batch-job. When using Selenium-IDE, test suites also can be defined using a simple HTML file. The syntax again is simple. An HTML table defines a list of tests where each row defines the filesystem path to each test. An example tells it all.

A file similar to this would allow running the tests all at once, one after another, from the Selenium-IDE. Test suites can also be maintained when using Selenium-RC. This is done via programming and can be done a number of ways. Commonly Junit is used to maintain a test suite if one is using Selenium-RC with Java.

Selenium IDE + UI-Element Reference :
UI-Element is an extension for the Selenium IDE and Remote Control that makes it possible to define a mapping between semantically meaningful names of elements on webpages, and the elements themselves. The mapping is stored in a file using JavaScript Object Notation. The file may be shared by the IDE and driven tests running via the Selenium server. It also offers a single point of update should the user interface of the application under test change.
Terminology
Page
A unique URL, and the contents available by accessing that URL. A page typically consists of several interactive page elements.
Page element
An element on the actual webpage. Generally speaking, an element is anything the user might interact with, or anything that contains meaningful content. More specifically, an element is realized as a Document Object Model (DOM) node and its contents. So when we refer to a page element, we mean both of the following, at the same time:
1.something on the page
2.its DOM representation, including its relationship with other page elements
Pageset
A set of pages that share some set of common page elements. For example, I might be able to log into my application from several different pages. If certain page elements on each of those pages appear similarly (i.e. their DOM representations are identical), those pages can be grouped into a pageset with respect to these page elements. There is no restriction on how many pagesets a given page can be a member of. Similarly, a UI element belong to multiple pagesets. A pageset is represented by a regular expression which matches the URL's that uniquely identify pages. A pageset also has a name.
UI element
A mapping between a meaningful name for a page element, and the means to locate that page element's DOM node. The page element is located via XPath. UI elements belong to pagesets.
UI argument
An optional piece of logic that determines how the XPath is generated by a UI element. Typically used when similar page elements appear multiple times on the same page, and you want to address them all with a single UI element. For example, if a page presents 20 clickable search results, the index of the search result might be a UI argument.
UI map
A collection of pagesets, which in turn contain UI elements. The UI map is the medium for translating between UI specifier strings, page elements, and UI elements.
UI specifier string
A bit of text containing a pageset name, a UI element name, and optionally arguments that modify the way an XPath is constructed by the UI element. UI specifier strings are intended to be the human-readable identifier for page elements.
Rollup rule
Logic that describes how one or more Selenium commands can be grouped into a single command, and how that single command may be expanded into its component Selenium commands. The single command is referred to simply as a "rollup".
Command matcher
Typically folded into a rollup rule, it matches one or more Selenium commands and optionally sets values for rollup arguments based on the matched commands. A rollup rule usually has one or more command matchers.
Rollup argument
An optional piece of logic that modifies the command expansion of a rollup.

How to use UI-Element?
open
/
clickAndWait
ui=allPages::section(section=topics)
clickAndWait
ui=topicListingPages::topic(topic=Process)
clickAndWait
ui=subtopicListingPages::subtopic(subtopic=Creativity)
click
ui=subtopicArticleListingPages::article(index=2)


Selenium Commands :
To conclude our introduction of Selenium, we’ll show you a few typical Selenium commands. These are probably the most commonly used commands for building tests.

open
opens a page using a URL.
click/clickAndWait
performs a click operation, and optionally waits for a new page to load.
verifyTitle/assertTitle
verifies an expected page title.
verifyTextPresent
verifies expected text is somewhere on the page.
verifyElementPresent
verifies an expected UI element, as defined by its HTML tag, is present on the page.
verifyText
verifies expected text and it’s corresponding HTML tag are present on the page.
verifyTable
verifies a table’s expected contents.
waitForPageToLoad
pauses execution until an expected new page loads. Called automatically when clickAndWait is used.
waitForElementPresent
pauses execution until an expected UI element, as defined by its HTML tag, is present on the page.
verifyTextPresent
The command verifyTextPresent is used to verify specific text exists somewhere on the page. It takes a single argument–the text pattern to be verified. For example:
Command Target Value
verifyTextPresent Marketing Analysis
This would cause Selenium to search for, and verify, that the text string “Marketing Analysis” appears somewhere on the page currently being tested. Use verifyTextPresent when you are interested in only the text itself being present on the page. Do not use this when you also need to test where the text occurs on the page.
verifyElementPresent
Use this command when you must test for the presence of a specific UI element, rather then its content. This verification does not check the text, only the HTML tag. One common use is to check for the presence of an image.
Command Target Value
verifyElementPresent //div/p/img
This command verifies that an image, specified by the existence of an HTML tag, is present on the page, and that it follows a
tag and a tag. The first (and only) parameter is a locator for telling the Selenese command how to find the element. verifyElementPresent can be used to check the existence of any HTML tag within the page. You can check the existence of links, paragraphs, divisions, etc. Here are a few more examples.
Command Target Value
verifyElementPresent //div/p
verifyElementPresent //div/a
verifyElementPresent id=Login
verifyElementPresent link=Go to Marketing Research
verifyElementPresent //a[2]
verifyElementPresent //head/title

verifyText
Use verifyText when both the text and its UI element must be tested. verifyText must use a locator. If you choose an XPath or DOM locator, you can verify that specific text appears at a specific location on the page relative to other UI components on the page.
Command Target Value
verifyText //table/tr/td/div/p This is my text and it occurs right after the div inside the table.

Locating Elements
For many Selenium commands, a target is required. This target identifies an element in the content of the web application, and consists of the location strategy followed by the location in the format locatorType=location. The locator type can be omitted in many cases. The various locator types are explained below with examples for each.

Locating by Identifier
This is probably the most common method of locating elements and is the catch-all default when no recognised locator type is used. With this strategy, the first element with the id attribute value matching the location will be used. If no element has a matching id attribute, then the first element with a name attribute matching the location will be used.


The following locator strategies would return the elements from the HTML snippet above indicated by line number:
1.identifier=loginForm (3)
2.identifier=username (4)
3.identifier=continue (5)
4.continue (5)

Locating by Id
This type of locator is more limited than the identifier locator type, but also more explicit. Use this when you know an element’s id attribute.


1.id=loginForm (3)

Locating by Name
The name locator type will locate the first element with a matching name attribute. If multiple elements have the same value for a name attribute, then you can use filters to further refine your location strategy. The default filter type is value (matching the value attribute).
1.name=username (4)
2.name=continue value=Clear (7)
3.name=continue Clear (7)
4.name=continue type=button (7)

Note :
Unlike some types of XPath and DOM locators, the three types of locators above allow Selenium to test a UI element independent of its location on the page. So if the page structure and organization is altered, the test will still pass. You may or may not want to also test whether the page structure changes. In the case where web designers frequently alter the page, but its functionality must be regression tested, testing via id and name attributes, or really via any HTML property, becomes very important.

Locating by XPath
XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page.

One of the main reasons for using XPath is when you don’t have a suitable id or name attribute for the element you wish to locate. You can use XPath to either locate the element in absolute terms (not advised), or relative to an element that does have an id or name attribute. XPath locators can also be used to specify elements via attributes other than id and name.

Absolute XPaths contain the location of all elements from the root (html) and as a result are likely to fail with only the slightest adjustment to the application. By finding a nearby element with an id or name attribute (ideally a parent element) you can locate your target element based on the relationship. This is much less likely to change and can make your tests more robust.

Since only xpath locators start with “//”, it is not necessary to include the xpath= label when specifying an XPath locator.
1.xpath=/html/body/form[1] (3) - Absolute path (would break if the HTML was changed only slightly)
2.//form[1] (3) - First form element in the HTML
3.xpath=//form[@id='loginForm'] (3) - The form element with attribute named ‘id’ and the value ‘loginForm’
4.xpath=//form[input/\@name='username'] (4) - First form element with an input child element with attribute named ‘name’ and the value ‘username’
5.//input[@name='username'] (4) - First input element with attribute named ‘name’ and the value ‘username’
6.//form[@id='loginForm']/input[1] (4) - First input child element of the form element with attribute named ‘id’ and the value ‘loginForm’
7.//input[@name='continue'][@type='button'] (7) - Input with attribute named ‘name’ and the value ‘continue’ and attribute named ‘type’ and the value ‘button’
8.//form[@id='loginForm']/input[4] (7) - Fourth input child element of the form element with attribute named ‘id’ and value ‘loginForm’

Locating Hyperlinks by Link Text
This is a simple method of locating a hyperlink in your web page by using the text of the link. If two links with the same text are present, then the first match will be used.

Are you sure you want to do this?


1.link=Continue (4)
2.link=Cancel (5)

Locating by DOM

The Document Object Model represents an HTML document and can be accessed using JavaScript. This location strategy takes JavaScript that evaluates to an element on the page, which can be simply the element’s location using the hierarchical dotted notation. Since only dom locators start with “document”, it is not necessary to include the dom= label when specifying a DOM locator.
1.dom=document.getElementById('loginForm') (3)
2.dom=document.forms['loginForm'] (3)
3.dom=document.forms[0] (3)
4.document.forms[0].username (4)
5.document.forms[0].elements['username'] (4)
6.document.forms[0].elements[0] (4)
7.document.forms[0].elements[3] (7)

Locating by CSS

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents. CSS uses Selectors for binding style properties to elements in the document. These Selectors can be used by Selenium as another locating strategy.

1.css=form#loginForm (3)
2.css=input[name="username"] (4)
3.css=input.required[type="text"] (4)
4.css=input.passfield (5)
5.css=#loginForm input[type="button"] (4)
6.css=#loginForm input:nth-child(2) (5)

Note :
Most experienced Selenium users recommend CSS as their locating strategy of choice as it’s considerably faster than XPath and can find the most complicated objects in an intrinsic HTML document.

Matching Text Patterns
Like locators, patterns are a type of parameter frequently required by Selenese commands. Examples of commands which require patterns are verifyTextPresent, verifyTitle, verifyAlert, assertConfirmation, verifyText, and verifyPrompt. And as has been mentioned above, link locators can utilize a pattern. Patterns allow you to describe, via the use of special characters, what text is expected rather than having to specify that text exactly.
There are three types of patterns: globbing, regular expressions, and exact.

Globbing Patterns

Most people are familiar with globbing as it is utilized in filename expansion at a DOS or Unix/Linux command line such as ls *.c. In this case, globbing is used to display all the files ending with a .c extension that exist in the current directory. Globbing is fairly limited. Only two special characters are supported in the Selenium implementation:
1.which translates to “match anything,” i.e., nothing, a single character, or many characters.
[ ] (character class) which translates to “match any single character found inside the square brackets.” A dash (hyphen) can be used as a shorthand to specify a range of characters (which are contiguous in the ASCII character set). A few examples will make the functionality of a character class clear:
[aeiou] matches any lowercase vowel
[0-9] matches any digit
[a-zA-Z0-9] matches any alphanumeric character

To specify a globbing pattern parameter for a Selenese command, you can prefix the pattern with a glob: label. However, because globbing patterns are the default, you can also omit the label and specify just the pattern itself.

Below is an example of two commands that use globbing patterns. The actual link text on the page being tested was “Film/Television Department”; by using a pattern rather than the exact text, the click command will work even if the link text is changed to “Film & Television Department” or “Film and Television Department”. The glob pattern’s asterisk will match “anything or nothing” between the word “Film” and the word “Television”.
Command Target Value
click link=glob:Film*Television Department
verifyTitle glob:*Film*Television*

The actual title of the page reached by clicking on the link was “De Anza Film And Television Department - Menu”. By using a pattern rather than the exact text, the verifyTitle will pass as long as the two words “Film” and “Television” appear (in that order) anywhere in the page’s title. For example, if the page’s owner should shorten the title to just “Film & Television Department,” the test would still pass. Using a pattern for both a link and a simple test that the link worked (such as the verifyTitle above does) can greatly reduce the maintenance for such test cases.

Regular Expression Patterns
Regular expression patterns are the most powerful of the three types of patterns that Selenese supports. Regular expressions are also supported by most high-level programming languages, many text editors, and a host of tools, including the Linux/Unix command-line utilities grep, sed, and awk. In Selenese, regular expression patterns allow a user to perform many tasks that would be very difficult otherwise. For example, suppose your test needed to ensure that a particular table cell contained nothing but a number. regexp: [0-9]+ is a simple pattern that will match a decimal number of any length.

Whereas Selenese globbing patterns support only the * and [ ] (character class) features, Selenese regular expression patterns offer the same wide array of special characters that exist in JavaScript. Below are a subset of those special characters:
PATTERN MATCH
. any single character
[ ] character class: any single character that appears inside the brackets
* quantifier: 0 or more of the preceding character (or group)
+ quantifier: 1 or more of the preceding character (or group)
? quantifier: 0 or 1 of the preceding character (or group)
{1,5} quantifier: 1 through 5 of the preceding character (or group)
| alternation: the character/group on the left or the character/group on the right
( ) grouping: often used with alternation and/or quantifier

Regular expression patterns in Selenese need to be prefixed with either regexp: or regexpi:. The former is case-sensitive; the latter is case-insensitive.

A few examples will help clarify how regular expression patterns can be used with Selenese commands. The first one uses what is probably the most commonly used regular expression pattern–.* (“dot star”). This two-character sequence can be translated as “0 or more occurrences of any character” or more simply, “anything or nothing.” It is the equivalent of the one-character globbing pattern * (a single asterisk).
Command Target Value
click link=regexp:Film.*Television Department
verifyTitle regexp:.*Film.*Television.*

Let’s examine the regular expression above one part at a time:
Sunrise: * The string Sunrise: followed by 0 or more spaces
[0-9]{1,2} 1 or 2 digits (for the hour of the day)
: The character : (no special characters involved)
[0-9]{2} 2 digits (for the minutes) followed by a space
[ap]m “a” or “p” followed by “m” (am or pm)

Exact Patterns
The exact type of Selenium pattern is of marginal usefulness. It uses no special characters at all. So, if you needed to look for an actual asterisk character (which is special for both globbing and regular expression patterns), the exact pattern would be one way to do that. For example, if you wanted to select an item labeled “Real *” from a dropdown, the following code might work or it might not. The asterisk in the glob:Real * pattern will match anything or nothing. So, if there was an earlier select option labeled “Real Numbers,” it would be the option selected rather than the “Real *” option.
select //select glob:Real *

In order to ensure that the “Real *” item would be selected, the exact: prefix could be used to create an exact pattern as shown below:
select //select exact:Real *

But the same effect could be achieved via escaping the asterisk in a regular expression pattern:
select //select regexp:Real \*
It’s rather unlikely that most testers will ever need to look for an asterisk or a set of square brackets with characters inside them (the character class for globbing patterns). Thus, globbing patterns and regular expression patterns are sufficient for the vast majority of us.

AndWait :
The difference between a command and its AndWait alternative is that the regular command (e.g. click) will do the action and continue with the following command as fast as it can, while the AndWait alternative (e.g. clickAndWait) tells Selenium to wait for the page to load after the action has been done. The AndWait alternative is always used when the action causes the browser to navigate to another page or reload the present one. Be aware, if you use an AndWait command for an action that does not trigger a navigation/refresh, your test will fail. This happens because Selenium will reach the AndWait‘s timeout without seeing any navigation or refresh being made, causing Selenium to raise a timeout exception.

Sequence of Evaluation and Flow Control :

When a script runs, it simply runs in sequence, one command after another. Selenese, by itself, does not support condition statements (if-else, etc.) or iteration (for, while, etc.). Many useful tests can be conducted without flow control. However, for a functional test of dynamic content, possibly involving multiple pages, programming logic is often needed.

When flow control is needed, there are three options:
1. Run the script using Selenium-RC and a client library such as Java or PHP to utilize the programming language’s flow control features.
2. Run a small JavaScript snippet from within the script using the storeEval command.
3. Install the goto_sel_ide.js extension.
Most testers will export the test script into a programming language file that uses the Selenium-RC API (see the Selenium-IDE chapter). However, some organizations prefer to run their scripts from Selenium-IDE whenever possible (for instance, when they have many junior-level people running tests for them, or when programming skills are lacking). If this is your case, consider a JavaScript snippet or the goto_sel_ide.js extension.

Store Commands and Selenium Variables :
You can use Selenium variables to store constants at the beginning of a script. Also, when combined with a data-driven test design (discussed in a later section), Selenium variables can be used to store values passed to your test program from the command-line, from another program, or from a file. The plain store command is the most basic of the many store commands and can be used to simply store a constant value in a selenium variable. It takes two parameters, the text value to be stored and a selenium variable. Use the standard variable naming conventions of only alphanumeric characters when choosing a name for your variable.
Command Target Value
store paul@mysite.org userName

Later in your script, you’ll want to use the stored value of your variable. To access the value of a variable, enclose the variable in curly brackets ({}) and precede it with a dollar sign like this.
Command Target Value
verifyText //div/p ${userName}

A common use of variables is for storing input for an input field.
Command Target Value
type id=login ${userName}

Selenium variables can be used in either the first or second parameter and are interpreted by Selenium prior to any other operations performed by the command. A Selenium variable may also be used within a locator expression. An equivalent store command exists for each verify and assert command. Here are a couple more commonly used store commands.

storeElementPresent :
This corresponds to verifyElementPresent. It simply stores a boolean value–”true” or “false”–depending on whether the UI element is found.

storeText :
StoreText corresponds to verifyText. It uses a locater to identify specific page text. The text, if found, is stored in the variable. StoreText can be used to extract text from the page being tested.

storeEval :

This command takes a script as its first parameter. Embedding JavaScript within Selenese is covered in the next section. StoreEval allows the test to store the result of running the script in a variable.

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

Alerts, Popups, and Multiple Windows :

Suppose that you are testing a page that looks like this.





The user must respond to alert/confirm boxes, as well as moving focus to newly opened popup windows. Fortunately, Selenium can cover JavaScript pop-ups.

But before we begin covering alerts/confirms/prompts in individual detail, it is helpful to understand the commonality between them. Alerts, confirmation boxes and prompts all have variations of the following
Command Description
assertFoo(pattern) throws error if pattern doesn’t match the text of the pop-up
assertFooPresent throws error if pop-up is not available
assertFooNotPresent throws error if any pop-up is present
storeFoo(variable) stores the text of the pop-up in a variable
storeFooPresent(variable) stores the text of the pop-up in a variable and returns true or false

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

Alerts :
Let’s start with asserts because they are the simplest pop-up to handle. To begin, open the HTML sample above in a browser and click on the “Show alert” button. You’ll notice that after you close the alert the text “Alert is gone.” is displayed on the page. Now run through the same steps with Selenium IDE recording, and verify the text is added after you close the alert. Your test will look something like this:
Command Target Value
open /
click btnAlert
assertAlert I’m blocking
verifyTextPresent Alert is gone.

Adding Verifications and Asserts With the Context Menu :
Your test cases will also need to check the properties of a web-page. This requires assert and verify commands. We won’t describe the specifics of these commands here; that is in the chapter on “Selenese” Selenium Commands. Here we’ll simply describe how to add them to your test case. With Selenium-IDE recording, go to the browser displaying your test application and right click anywhere on the page. You will see a context menu showing verify and/or assert commands. The first time you use Selenium, there may only be one Selenium command listed. As you use the IDE however, you will find additional commands will quickly be added to this menu. Selenium-IDE will attempt to predict what command, along with the parameters, you will need for a selected UI element on the current web-page. Let’s see how this works. Open a web-page of your choosing and select a block of text on the page. A paragraph or a heading will work fine. Now, right-click the selected text. The context menu should give you a verifyTextPresent command and the suggested parameter should be the text itself. Also, notice the Show All Available Commands menu option. This shows many, many more commands, again, along with suggested parameters, for testing your currently selected UI element. Try a few more UI elements. Try right-clicking an image, or a user control like a button or a checkbox. You may need to use Show All Available Commands to see options other than verifyTextPresent. Once you select these other options, the more commonly used ones will show up on the primary context menu. For example, selecting verifyElementPresent for an image should later cause that command to be available on the primary context menu the next time you select an image and right-click.Again,

Editing,Insert Command,Table View :
Select the point in your test case where you want to insert the command. To do this, in the Test Case Pane, left-click on the line where you want to insert a new command. Right-click and select Insert Command; the IDE will add a blank line just ahead of the line you selected. Now use the command editing text fields to enter your new command and its parameters.

Source View :
Select the point in your test case where you want to insert the command. To do this, in the Test Case Pane, left-click between the commands where you want to insert a new command, and enter the HTML tags needed to create a 3-column row containing the Command, first parameter (if one is required by the Command), and second parameter (again, if one is required). Be sure to save your test before switching back to Table view.

Insert Comment :
Comments may be added to make your test case more readable. These comments are ignored when the test case is run. Comments may also be used to add vertical white space (one or more blank lines) in your tests; just create empty comments. An empty command will cause an error during execution; an empty comment won’t.

Table View :
Select the line in your test case where you want to insert the comment. Right-click and select Insert Comment. Now use the Command field to enter the comment. Your comment will appear in purple font.

Source View :
Select the point in your test case where you want to insert the comment. Add an HTML-style comment, i.e., . Since Source view provides the equivalent of a WYSIWYG editor, simply modify which line you wish–command, parameter, or comment.

Opening and Saving a Test Case :
Like most programs, there are Save and Open commands under the File menu. However, Selenium distinguishes between test cases and test suites. To save your Selenium-IDE tests for later use you can either save the individual test cases, or save the test suite. If the test cases of your test suite have not been saved, you’ll be prompted to save them before saving the test suite. When you open an existing test case or suite, Selenium-IDE displays its Selenium commands in the Test Case Pane.

Running Test Cases :
The IDE allows many options for running your test case. You can run a test case all at once, stop and start it, run it one line at a time, run a single command you are currently developing, and you can do a batch run of an entire test suite. Execution of test cases is very flexible in the IDE.

Run a Test Case
Click the Run button to run the currently displayed test case.
Run a Test Suite
Click the Run All button to run all the test cases in the currently loaded test suite.
Stop and Start
The Pause button can be used to stop the test case while it is running. The icon of this button then changes to indicate the Resume button. To continue click Resume.
Stop in the Middle
You can set a breakpoint in the test case to cause it to stop on a particular command. This is useful for debugging your test case. To set a breakpoint, select a command, right-click, and from the context menu select Toggle Breakpoint.
Start from the Middle
You can tell the IDE to begin running from a specific command in the middle of the test case. This also is used for debugging. To set a startpoint, select a command, right-click, and from the context menu select Set/Clear Start Point.
Run Any Single Command
Double-click any single command to run it by itself. This is useful when writing a single command. It lets you immediately test a command you are constructing, when you are not sure if it is correct. You can double-click it to see if it runs correctly. This is also available from the context menu.

Debugging :
Debugging means finding and fixing errors in your test case. This is a normal part of test case development. We won’t teach debugging here as most new users to Selenium will already have some basic experience with debugging. If this is new to you, we recommend you ask one of the developers in your organization.

Breakpoints and Startpoints :
The Sel-IDE supports the setting of breakpoints and the ability to start and stop the running of a test case, from any point within the test case. That is, one can run up to a specific command in the middle of the test case and inspect how the test case behaves at that point. To do this, set a breakpoint on the command just before the one to be examined. To set a breakpoint, select a command, right-click, and from the context menu select Toggle Breakpoint. Then click the Run button to run your test case from the beginning up to the breakpoint. 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. For example, suppose your test case first logs into the website and then performs a series of tests and you are trying to debug one of those tests. However, you only need to login once, but you need to keep rerunning your tests as you are developing them. You can login once, then run your test case from a startpoint placed after the login portion of your test case. That will prevent you from having to manually logout each time you rerun your test case. To set a startpoint, select a command, right-click, and from the context menu select Set/Clear Start Point. Then click the Run button to execute the test case beginning at that startpoint.

Stepping Through a Testcase :
To execute a test case one command at a time (“step through” it), follow these steps:
1. Start the test case running with the Run button from the toolbar.
2. Immediately pause the executing test case with the Pause button.
3. Repeatedly select the Step button.

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. This is useful when building a locator for a command’s first parameter (see the section on locators in the Selenium Commands chapter). It can be used with any command that identifies a UI element on a webpage, i.e. click, clickAndWait, type, and certain assert and verify commands, among others. From Table view, select any command that has a locator parameter. Click the Find button. Now look on the webpage: There should be a bright green rectangle enclosing the element specified by the locator parameter.

Page Source for Debugging :
Often, when debugging a test case, you simply must look at the page source (the HTML for the webpage you’re trying to test) to determine a problem. Firefox makes this easy. Simply right-click the webpage and select ‘View->Page Source. The HTML opens in a separate window. Use its Search feature (Edit=>Find) to search for a keyword to find the HTML for the UI element you’re trying to test. Alternatively, select just that portion of the webpage for which you want to see the source. Then right-click the webpage and select View Selection Source. In this case, the separate HTML window will contain just a small amount of source, with highlighting on the portion representing your selection.

Writing a Test Suite :
A test suite is a collection of test cases which is displayed in the leftmost pane in the IDE. 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). 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. In the latter case, the new test case will appear immediately below the previous test case. Selenium-IDE does not yet support loading pre-existing test cases into a test suite. Users who want to create or modify a test suite by adding pre-existing test cases must manually edit a test suite file. A test suite file is an HTML file containing a one-column table. Each cell of each row in the section contains a link to a test case. The example below is of a test suite containing four test cases:
Test Cases for De Anza A-Z Directory Links
A Links
B Links
C Links
D Links

Note :
Test case files should not have to be co-located with the test suite file that invokes them. And on Mac OS and Linux systems, that is indeed the case. However, at the time of this writing, a bug prevents Windows users from being able to place the test cases elsewhere than with the test suite that invokes them.

User Extensions :
User extensions are JavaScript files that allow one to create his or her own customizations and features to add additional functionality. Often this is in the form of customized commands although this extensibility is not limited to additional commands. There are a number of useful extensions created by users. Perhaps the most popular of all Selenium-IDE extensions is one which provides flow control in the form of while loops and primitive conditionals.

Format :
Format, under the Options menu, allows you to select a language for saving and displaying the test case. The default is HTML. If you will be using Selenium-RC to run your test cases, this feature is used to translate your test case into a programming language. Select the language, i.e. Java, PHP, you will be using with Selenium-RC for developing your test programs. Then simply save the test case using File=>Save. Your test case will be translated into a series of functions in the language you choose. Essentially, program code supporting your test is generated for you by Selenium-IDE. Also, note that if the generated code does not suit your needs, you can alter it by editing a configuration file which defines the generation process. Each supported language has configuration settings which are editable. This is under the Options=>Options=>Format tab.

Note :
At the time of this writing, this feature is not yet supported by the Selenium developers. However the author has altered the C# format in a limited manner and it has worked well.

Executing Selenium-IDE Tests on Different Browsers :
While Selenium-IDE can only run tests against Firefox, tests developed with Selenium-IDE can be run against other browsers, using a simple command-line interface that invokes the Selenium-RC server.

Fuzzy Matching :
Here's a real-world example of where fuzzy matching is important:
BrahmsViola Quintet
SaegusaCello 88
Imagine I'm recording in the IDE. Let's say I click on "Cello 88". The IDE would create locator for this action like //table/tr[2]/td[2]. Does that mean that my getLocator() method should return the same XPath? Clearly not. Clicking on either of the table cells for the second row has the same result. I would like my UI element generated XPath to be //table/tr[2] . However, when recording, the page element that was identified as being acted upon was the table cell, which doesn't match my UI element XPath, so the ui locator strategy will fail to auto-populate. What to do? Fuzzy matching to the rescue! Fuzzy matching is realized as a fuzzy matcher function that returns true if a target DOM element is considered to be equivalent to a reference DOM element. The reference DOM element would be the element specified by the UI element's generated XPath. Currently, the fuzzy matcher considers it a match if:
1.the elements are the same element,
2.the reference element is an anchor element, and the target element is a descendant of it; or
3.the reference element has an onclick attribute, and the target element is a descendant of it.
This logic may or may not be sufficient for you. The good news is, it's very easy to modify. Look for the definition of PageBot.prototype.locateElementByUIElement.is_fuzzy_match in ui-element.js .

It's inevitable that certain sequences of Selenium commands will appear in testcases over and over again. When this happens, you might wish to group several fine-grained commands into a single coarser, more semantically meaningful action. In doing so, you would abstract out the execution details for the action, such that if they were to change at some point, you would have a single point of update. In UI-Element, such actions are given their own command, called rollup. In a sense, rollups are a natural extension of the ui locator.
UI-Element is designed with the belief that the IDE can be a useful tool for writing testcases, and need not be shunned for lack of functionality. A corollary belief is that you should be able to drive your RC test in the language of your choice. The execution of the rollup command by the Selenium testrunner produces the component commands, which are executed in a new context, like a function call. The logic of the rollup "expansion" is written in javascript. Corresponding logic for inferring a rollup from a list of commands is also written in javascript. Thus, the logic can be incorporated into any of the family of Selenium products as a user extension. Most notably, the IDE is made viable as a testcase creation tool that understands both how rollups expand to commands, and also how rollup rules can be "applied" to commands to reduce them to rollups.

Rollup rule definitions appear in this general format:
var manager = new RollupManager();

manager.addRollupRule({ ... });
manager.addRollupRule({ ... });
...
In a relatively simple form, a rollup rule looks like this:
manager.addRollupRule({
name: 'do_search'
, description: 'performs a search'
, args: [
name: 'term'
, description: 'the search term'
]
, commandMatchers: [
{
command: 'type'
, target: 'ui=searchPages::search_box\\(.+'
, updateArgs: function(command, args) {
var uiSpecifier = new UISpecifier(command.target);
args.term = uiSpecifier.args.term;
return args;
}
}
, {
command: 'click.+'
, target: 'ui=searchPages::search_go\\(.+'
}
]
, getExpandedCommands: function(args) {
var commands = [];
var uiSpecifier = new UISpecifier(
'searchPages'
, 'search_box'
, { term: args.term });
commands.push({
command: 'type'
, target: 'ui=' + uiSpecifier.toString()
});
commands.push({
command: 'clickAndWait'
, target: 'ui=searchPages::search_go()'
});
return commands;
}
});
In the above example, a rollup rule is defined for performing a search. The rule can be "applied" to two consecutive commands that match the commandMatchers. The rollup takes one argument, term, and expands back to the original two commands. One thing to note is that the second command matcher will match all commands starting with click. The rollup will expand that command to a clickAndWait.


Conclusion :
From this who read these lines and simple commands are femiliar to Selenium IDE and the description which was i given my experiences on selenium and my research(Selenium Documentation and Articles on Selenium) and let me know if i wrong anywhere.

No comments:

Post a Comment