Selenium

From Genecats
Jump to navigationJump to search


The Basics

Setting up Selenium IDE

Selenium IDE is a Firefox (only) plugin to help assist in creating basic Selenium test via a GUI.

1. Download/install Selenium IDE for Firefox

2. Open Selenium IDE from Firefox under the Tools pulldown menu

3. Once IDE is open, go to: Options > Options... > Locator Builders and reorder them to (from top down): id, name, link, css, ui, ...then everything else...

Ordering them like this makes for faster running tests, as finding unique elements (id, name, link) is faster (and easier to read) than hunting for them using another method. The fallback is using css selectors, as css selectors have proven to be faster than xPath.

There are some ok introduction to Selenium IDE videos on YouTube.

Setting up Selenium Server and running tests from the command line

This section assumes that you are writing your tests in python. For additional information, see Redmine issue #6326.

Getting python ready

To write a test in python, first you have to download the python Selenium WebDriver/Client Driver package. This is a python module that will allow you to access methods to control the browser from python (e.g. commands like "find_element_by_tag_name('title')" that you may be familiar with from Selenium IDE).

Step by step instructions:

  1. Install pip, which allows you to easily install python packages.
  2. Download Selenium WebDriver/Client Driver package for python here
  3. Install the python package using:
pip install selenium

You may also need to update selenium occasionally. You can do so by using:

pip install --upgrade selenium

Or pip3 install --upgrade selenium if you have a later python.

pip3 install --upgrade selenium

Note at the top of each test you will need the line:

from selenium import webdriver

at a minimum. You may also want to import other parts of the selenium webdriver module for different tests. Other modules that are useful to import are unitest and time. Both of these come standard in the 2.7 python install.

For more information see:

Setting up the Server

Note that you technically don't need to set up a server (skip this step for gbib.selenium.py) if you are only running one browser and are going to run the test on the same machine that you are on. All you need is the python bindings above. This can be useful for testing that a script runs before deploying cross-browser, cross-platform testing.

First, download the Selenium Server .jar file on the main "controller" machine and all the remote test machines, the "nodes". Note that the controller/hub/server machine and the node machine can be the same machine. To run the server and the node on the same machine, just run the server and the nodes in separate windows.

  1. Start up the server on the main machine using that machines ip address. In this example we have used port 4448:
java -jar selenium-server-standalone-2.16.1.jar -role hub -hub http://<static ip address> -port 4448

You will need to get your ip address from the command line. Use "ifconfig" and look for the ip address starting "192".

  1. Start up each of the "nodes" by logging into each machine (can be remotely). In this example we assume that you started the hub on port 4448. We have used port 4444:
java -jar selenium-server-standalone-2.16.1.jar -role node -hub http://<static ip address>:4448/grid/register -port 4444

Note, the version of Selenium Server may be different.

Both of the server and node will be running in open command windows. To close them, kill them like any other unix command

Running the tests

Now that you have your server and nodes running, it is time to run your tests. Open another command line window and run your python test. It should open the browser that was specified in the test and run the test.

Example test

Here is a quick example test to see if you have set up your python instance and selenium server/node correctly. It tests that google.com loads and that the title is "Google":

import unittest

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class TestTitle(unittest.TestCase):

    def setUp(self):
        # Toggle comments to test with a different browser
        #self.driver = webdriver.Chrome()
        self.driver = webdriver.Firefox()
        #self.driver = webdriver.Ie()
        # self.driver = webdriver.Remote(command_executor="http://128.114.57.250:4448/grid/hub", desired_capabilities={"browser_name":'internet explorer'})
    def tearDown(self):
        self.driver.close()

    def test_title_tag(self):
        self.driver.get('http://google.com')
        title_tag = self.driver.find_element_by_tag_name('title')
        self.assertEqual(title_tag.text, 'Google')


if __name__ == '__main__':
    unittest.main()

Element Locators

Your main locator will be an element's id (they do have id's, right?). There are many others described in the Selenium Docs.

One common way to find elements on a page using Selenium is xPath, however, we should use CSS selectors when possible, as the tests run faster - especially in IE. See: Why CSS Locators are the way to go vs XPath

The best way to find elements is by using their unique ids, in the form of an 'id' or 'name' html attribute, or a specific link. When an element does not have any unique id attached to it, the best fallback is using css selectors. See: Selenium Tips: CSS Selectors in Selenium Demystified.

A really nice tool for creating more complex CSS Selectors (when needed) is Selector Gadget.

Testing dynamic applications (AJAX)

The main things you'll need to test AJAX calls and other dynamic functions are the waitFor... commands. Here are a few of the most useful ones:

waitForCondition(script, timeout)

This is the AJAX command - well almost; also see waitForElementPresent below.

Arguments:

  • script - the JavaScript snippet to run
  • timeout - a timeout in milliseconds, after which this command will return with an error

Runs the specified JavaScript snippet repeatedly until it evaluates to "true". The snippet may have multiple lines, but only the result of the last line will be considered.

Note that, by default, the snippet will be run in the runner's test window, not in the window of your application. To get the window of your application, you can use the JavaScript snippet selenium.browserbot.getCurrentWindow(), and then run your JavaScript in there.

Examples.

waitForElementPresent(locator)

The other AJAX biggie. Similar to waitForCondition. This waits for a certain element to appear (i.e., often an element being loaded via an ajax call).

Generated from isElementPresent(locator)

Arguments:

  • locator - an element locator

Returns: true if the element is present, false otherwise

Verifies that the specified element is somewhere on the page.


waitForVisible(locator)

Also note it's evil twin, waitForNotVisible(locator). These are good when an element is on a page but hidden (i.e., a popup) and your test requires you to wait for it to become visible before clicking on some element inside it.

Arguments:

  • locator - an element locator

Returns: true if the specified element is visible, false otherwise

Determines if the specified element is 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. This method will fail if the element is not present.

Example:

waitForVisible(id=hgTrackUiDialog)

Wait for the UiDialog (which has an id=hgTrackUiDialog) to appear so the test can continue and click on elements in this dialog.

Selenium Resources

General Automated Testing Resources

A Quick Example Script to Build a new Selenium IDE for FF from URLs

Place some URLs in a file called "URLs" in your current directory.

http://encodeproject.org/ENCODE/dataMatrix/encodeChipMatrixHuman.html
http://encodeproject.org/ENCODE/dataMatrix/encodeDataSummaryHuman.html
http://encodeproject.org/ENCODE/dataMatrix/encodeChipMatrixMouse
http://encodeproject.org/ENCODE/dataMatrix/encodeDataSummaryMouse.html

You can then use the following command line, that will first curl the headSelenium to a file called newScript, then for each URL build a middle part around it with parts like open for indentations around each URL, and then lastly curl the tailSelenium onto the bottom of the newScript.


curl --silent BROKEN http://hgwdev.gi.ucsc.edu/~brianlee/ENCODE3/misc/scriptSelenium/headSelenium >> newScript; for i in $(cat URLs); do echo -e "\n open\n $i\n\n\n" >> newScript; done; curl --silent http://hgwdev.gi.ucsc.edu/~brianlee/ENCODE3/misc/scriptSelenium/tailSelenium >> newScript


Now you can open FF and click Tools and select Selenium IDE and then use the File menu to Open... "newScript" from the directory you created it in, and run it.

Note you can change the open section to openWindow to have the script create a new window for each page.


A Quick Example to build a python script

FF discontinued allowing Selenium IDE in 2017. Until the community improves their ability to have a plug-in again, here's a work around to quickly build a script in python using links like /cgi-bin/hgGateway?db=gorGor5 (not full links now since the cool genomeTest.py program inputs a base_url).

curl --silent https://hgwdev.gi.ucsc.edu/~brianlee/misc/code/TOP >> genomeTestTemp.py; \
for i in $(cat TESTS); \
do echo '        driver.get(self.base_url + "'$i\"\) >> genomeTestTemp.py; \
done; \
curl --silent https://hgwdev.gi.ucsc.edu/~brianlee/misc/code/BOTTOM >> genomeTestTemp.py; \

Then one would run a script like: python genomeTestTemp.py http://hgw0.soe.ucsc.edu

In this case the script in TESTS has entries like /cgi-bin/hgGateway?db=taeGut1 And builds lines like:

        driver.get(self.base_url + "/cgi-bin/hgGateway?db=taeGut1")

Into the middle of genomeTestTemp.py.

You can make this script more interesting by having it do more than just go to the URL in TESTS. You can add a second "echo" line that might click into an item or do something specific, like check for some displayed text.

...
do echo '        driver.get(self.base_url + "'$i\"\) >> genomeTestTemp.py; \
echo '        new python line to do something after navigating to this URL >> genomeTestTemp.py; \
...

An example python Selenium script testing GBiB

Here is an example script pointed to the GBiB URL http://127.0.0.1:1234/ that can be run when GBiB is up: python selenium GBiB Script

With a script open in FireFox, one can export the script as python.

  1. With functional FF running script, select File and then "Export Test Case As" and select "Python 2.. webdriver"
  2. Open your terminal and find your saved file. (Or cut and paste the above gbib.selenium.py into a file).
  3. With your python set up you should be able to run the script. For example:
    python gbib.selenium.py
    .