Rc067 010d Selenium 1
Rc067 010d Selenium 1
CONTENTS INCLUDE:
n
About Selenium Getting Started with
Selenium
n
Architecture in a Nutshell
n
Installing Selenium
n
Recording/Playback using Selenium IDE
n
Selenese Table Format
n
Selenium Command Reference and more...
By Frank Cohen
source project. It uses Selenium RC to provide Selenium Grid-
About Selenium like capability with the added advantage of providing data-
driven Selenium tests, results analysis charts and graphs, and
Selenium is a portable software testing framework for Web better stability of the test operations.
applications. Selenium works well for QA testers needing
record/playback authoring of tests and for software developers The PushToTest open-source project provides Selenium data-
needing to author tests in Java, Ruby, Python, PHP, and driven testing, load testing, service monitoring, and reporting.
several other languages using the Selenium API. The Selenium TestMaker runs load and performance tests (Type 3) in a
architecture runs tests directly in most modern Web browsers, PushToTest TestNode using the PushToTest SeleniumHTMLUnit
including MS IE, Firefox, Opera, Safari, and Chrome. Selenium library and HTMLUnit Web browser (and Rhino JavaScript
deploys on Windows, Linux, and Macintosh platforms. engine.)
Architecture in a Nutshell
Installing selenium
Selenium Browserbot is a JavaScript class that runs within a
hidden frame within a browser window. The Browserbot runs
www.dzone.com
n Authoritative content
Functional testing (Type 1) uses the Selenium IDE add-on n Designed for developers
to Firefox to record and playback Selenium tests in Firefox. n Written by top experts
Functional testing (Type 2) uses Selenium Grid to run tests in n Latest tools & technologies
a farm of browsers and operating environments. For example,
n Hot tips & examples
run install Selenium Grid on 3 operation environments (for
n Bonus content online
example, Windows Vista, Windows XP, and Ubutu) and on each
Selenium
addLocationStrategy strategyName
With Selenium IDE
addLocationStrategyAndWait
open, the menu bar
context changes to allowNativeXpath boolean
runScript javascript
Selenium IDE provides
an extensibility runScriptAndWait
openWindow url
to be backwardly compatible from one version to the next.
openWindowAndWait
Selenium Context Menu provides quick commands to insert goBack goBackAndWait
new Selenium commands, evaluate XPath expressions within
refresh refreshAndWait
the live Web page, and to show all available Selenium
close
commands. Right click on commands in Selenium IDE, and
deleteCookie name
right-click on elements in the browser page to view the
deleteCookieAndWait
Selenium Context Menu commands.
setCursorPositionAndWait submitAndWait
Keyboard Operations
Windows/Element Selection
keyDown locator
select locator
keyDownAndWait
selectAndWait
keyPress locator
selectFrame locator
keyPressAndWait
shiftKeyDown shiftKeyDownAndWait
click locator Selenium commands identify elements within a Web page using:
clickAndWait
identifier=id Select the element with the specified @id attribute. If no match is
clickAt locator found, select the first element whose @name attribute is id.
clickAtAndWait name=name Select the first element with the specified @name attribute.
The name may optionally be followed by one or more element-
doubleClick locator filters, separated from the name by whitespace. If the filterType
is not specified, value is assumed. For example, name=style
doubleClickAndWait value=carol
doubleClickAt locator dom=javascriptExpression Find an element using JavaScript traversal of the HTML
dom=javascriptExpression Document Object Model. DOM locators must begin with Use the Selenium IDE File menu, Export, Python Selenium RC
(continued) “document.” For example: command to export the test to a jUnit-style TestCase written in
dom=document.forms[‘form1’].myList
dom=document.images[1] Python. The following shows the Java source code:
xpath=xpathExpression Locate an element using an XPath expression. Here are a few
examples: package com.example.tests;
xpath=//img[@alt=’The image alt text’]
xpath=//table[@id=’table1’]//tr[4]/td[2] from selenium import selenium
/html/body/table/tr/td/a import unittest, time, re
//div[@id=’manage_messages_iterator’]
//tr[@class=’SelectedRow’]/td[2] class franktest(unittest.TestCase):
//td[child::text()=’[email protected]’] def setUp(self):
//td[contains(child::text(),’@’)] self.verificationErrors = []
self.selenium = selenium(“localhost”, 4444, “*chrome”, \
link=textPattern Select the link (anchor) element which contains text matching the “http://change-this-to-the-site-you-are-testing/”)
specified pattern. self.selenium.start()
def test_franktest(self):
css=cssSelectorSyntax Select the element using css selectors. For example: sel = self.selenium
sel.open(“/”)
css=a[href=”#id1”]
sel.type(“q”, “sock puppet”)
css=span#firstChild + span
sel.click(“sa”)
Selenium 1.0 css selector locator supports all css1, css2 and css3 sel.wait_for_page_to_load(“30000”)
selectors except namespace in css3, some pseudo classes(:nth- sel.click(“//div[@id=’res’]/div[1]/ol/li[1]/div/h2/a/em”)
of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, sel.click(“//div[@id=’res’]/div[1]/ol/li[1]/div/h2/a/em”)
:visited, :hover, :active, :focus, :indeterminate) and pseudo sel.wait_for_page_to_load(“30000”)
elements(::first-line, ::first-letter, ::selection, ::before, ::after).
Without an explicit locator prefix, Selenium uses the following def tearDown(self):
default strategies: self.selenium.stop()
dom, for locators starting with “document.” self.assertEqual([], self.verificationErrors)
xpath, for locators starting with “//”
identifier, otherwise if __name__ == “__main__”:
unittest.main()
Your choice of element locator type has an impact on the An exported test like the one above has access to all of
test playback performance. The following table compares Python’s functions, including conditionals, looping and
performance of Selenium element locators using Firefox 3 and branching, reusable object libraries, inheritance, collections,
Internet Explorer 7. and dynamically typed data formats.
Locator used Type Firefox 3 Internet
Explorer 7 Selenium provides a Selenium RC client package for Java,
q Locator 47 ms 798 ms Python, C#, Ruby, Groovy, PHP, and Perl. The client object
//input[@name=’q’] XPath 32 ms 563 ms
identifies the Selenium RC service in its constructor:
//html[1]/body[1]//form[1]//input[2] XPath 47 ms 859 ms self.selenium = selenium(“localhost”, 4444, “*iexplore”, \
“http://change-this-to-the-site-you-are-testing/”)
//input[2] XPath 31 ms 564 ms
self.selenium.start()
document.forms[0].elements[1] DOM Index 31 ms 125 ms
The above code identifies the Selenium RC service running on
Additional details on Selenium performance can be found at: the localhost machine at port 4444. This client will run the test
http://www.pushtotest.com/docs/thecohenblog/symposium in Microsoft Internet Explorer. The third parameter identifies
the base URL from which the recorded test will operate.
Script-Driven Testing
to load the Web page because Ajax functions that manipulate Run the above JavaScript function from within a Selenium test
the current Web page in response to a click event do not using the AssertEval command.
reload the page. We recommend using Selenium commands AssertEval javascript:this.browserbot.getCurrentWindow().tinyMCE.
that poll the DOM until the Ajax methods complete their tasks. execCommand
(‘mceInsertContent’,false,’<b>Hello world!!</b>’);
For example, waitUntilElementPresent polls the DOM until
the JavaScript function adds the desired element to the page
before continuing with the rest of the Selenium script. Data Production
Consider the following checklist when using Selenium with Ajax
applications: Selenium offers no operational test data production capability
itself. For example, a Selenium test of a sign-in page usually
Your Selenium tests may require a large number of extra commands to ensure the test
stays in synchronization with the Ajax application. Consider an Ajax application that needs sign-in name and sign-in password operational test data
requires a log-in, then displays a selection list of items, then presents an order form.
Ajax enabled applications often deliver multiple steps of function on a single page to operate. Two options are available: 1) Use the data access
and show-and-hide elements as you work with the application. Some even disable features in Java, Ruby, or one of other supported languages,
form submit buttons and other user interface elements until you enter enough valid
information. For an application like this you will need a combination of Selenium 2) Use PushToTest TestMaker’s Selenium Script Runner to
commands. Consider the following Selenium test:
inject data from comma separated value (CSV) files, relational
waitForElementPresent pauses the test until the Ajax application adds the requisite databases, objects, and Web services.
element to the page. waitForCondition pauses the test until the JavaScript function
evaluates to true. See http://tinyurl.com/btxvn4 for details.
Many Ajax applications use dynamic element id tags. The Ajax application that named
the Log-out button app_6 may later rename the button to app_182. We recommend
using DOM element locator techniques, or XPath techniques if needed, to dynamically
find elements on a positional or other attribute means.
The first row of the data file contains column names. These
will be used to map values into the Selenium test. Change the
Selenium test to refer to mapping name. PushToTest maps
the data from the named column in the CSV data file to the
Selenium test data using the first row definitions.
Working with tinymce and ajax objects
Connect the Data Production Library (DPL) to the Selenium test
in a TestMaker TestScenario. Begin by definition a HashDPL.
Ajax is about moving functions off the server and into the
This DPL reads from CSV data files and provides the data to the
browser. Selenium architecture supports innovative new
test.
browser-based functions because Selenium’s Browserbot is a
JavaScript class itself. The Browserbot even lets Selenium tests <DataSources>
<dpl name=”mydpl” type=”HashDPL”>
operate JavaScript functions as part of the test. For example, <argument name=”file” dpl=”rsc” value=”getDataByIndex” index=”0”/>
TinyMCE (http://tinymce.moxiecode.com) is a graphical text </dpl>
</DataSources>
editor component for embedding in Web pages. TinyMCE
supports styled text and what-you-see-is-what-you-get editing. Next, tell the TestScenario to send the data.csv and Selenium
Testing a TinyMCE can be challenging. Selenium offers click test files to the TestNodes that will operate the test.
and type functions that interact with TinyMCE but no direct
<resources>
commands for TinyMCE’s more advanced functions. For <data path=”data.csv”/>
example, imagine testing TinyMCE’s ability to stylize text. <selenese path=”CalendarTest.selenium”/>
</resources>
The test needs to insert test, move the insertion point, select
a sentence, bold the text, and drag the sentence to another Then tell the Selenium ScriptRunner to use the DPL provided
paragraph. This is beyond Selenium’s DSL. Instead, the data when running the Selenium test.
Selenium test may include JavaScript commands that interact
<run name=”CalendarTest” testclass=”CalendarTest.selenium”
with TinyMCE’s published API method=”runSeleneseFile” langtype=”selenium”>
(http://tinymce.moxiecode.com/documentation.php). <argument dpl=”mydpl” name=”DPL_Properties”
value=”getNextData”/>
Here is an example of using the TinyMCE API from a Selenium </run>
test context: The getNextData operation gets the next row of data from the
this.browserbot.getCurrentWindow().tinyMCE.execCommand CSV file. The Selenium ScriptRunner injexts the data into the
(‘mceInsertContent’,false,’<b>Hello world!!</b>’);
Selenium test.
Selenium RC launches the browser with itself as the proxy In Selenium IDE, the File menu enables tests to be saved as
server to inject the Javascript of the Browserbot and your test cases or test suites. Record a test, use File -> Save Test
test. This architecture makes it possible to run the same test Case. Create a second Test Case by choosing File -> New Test
on multiple browsers. However, some browsers will warn the Case. Record the second test use case. Save the TestSuite for
user of possible security threats when the proxy starts and these two test use cases by choosing File -> Save TestSuite.
when the test requests functions or pages outside of the Click the “Run entire test suite” icon from the Selenium IDE
originating domain. The browser takes control and stops the tool bar.
Browserbot operations to display the warning message. When
TestMaker defines test use cases using a simple XML notation:
this happens, the test stops until a user dismisses the warning.
There are no reliable cross-browser workarounds. <usecases>
<usecase name=”MailerCheck_usecase”>
<test>
Some Web applications redirect from http to https URLs. The
<run name=”LogIn” testclass=”Login.selenium”
browser will often issue a warning that stops the Selenium test. instance=”myinst”
Selnium does not support a test moving across domains. For method=”runSeleneseFile” langtype=”selenium”>
example, a test that started with a baseurl of www.mydomain. </run>
com may not open a page on www.secondomain.com.
<run name=”OrderProduct” testclass=”OrderProduct.
selenium rc browser profiles selenium” instance=”myinst”
method=”runSeleneseFile” langtype=”selenium”>
Selenium Remote Control (RC) enables test operation on
</run>
multiple real browsers. A browser profile attribute may be
any of the following installed browsers: chrome, konqueror, </test>
piiexplore, iehta, mock, opera, pifirefox, safari, iexplore and </usecase>
</usecases>
custom. Append the path to the real browser after browser
profile if your system path does not state the path to the
browser. For example: Reporting options
*firefox /Applications/Firefox.app/Contents/MacOS/firefox
Selenium offers no results reporting capability of its own.
Component approach example Two options are available: 1) Write your tests as a set of JUnit
tests and use JUnit Report (http://ant.apache.org/manual/
Many organizations pursue a “Test and Trash” methodology to OptionalTasks/junitreport.html) to plot success/failure charts, 2)
achieve agile software development lifecycles. For example, an Use PushToTest TestMaker Results Analysis Engine to produce
organization in pursuit of agile techniques may change up to more than 300 charts from the transaction and step time
30% of an application with an application lifecycle of 8 weeks. tracking of Selenium tests.
Without giving the change much thought, up to 30% of their
recorded tests break! For example, TestMaker tracks Selenium command duration
in a test suite or test case. Consider the following chart. This
We recommend a component approach to building tests. shows the “Step” time it takes to process each Selenium
Test components perform specific test operations. We write command in a test use case over 10 equal periods of time that
or record tests as individuals components of test function. the test took to operate.
For example, a component operates the sign-in function
of a private Web
application. When the
sign-in portion of the
application changes,
we only need to
change the sign-in test
and the rest of test
continues to perform
normally.
A B O U T t h e A ut h or R E C O M M E N D E D B oo k
Frank Cohen is, Founder of PushToTest, Author of As a Java developer, you want a guide that shows you
FastSOA. Through his speaking, writing and consulting, Frank how to add Ajax functionality to your web applications
Cohen, is the expert that information technology professionals with a minimum of effort. Well look no further than Pro
and enterprises go to when they need to understand and solve Ajax and Java Frameworks. In this book, recognized
problems in complex interoperating information systems,
especially Service Oriented Architecture (SOA), Ajax, and Java experts and authors of the best-selling Apress
Web services. PushToTest is the open-source test automation title, Foundations of Ajax, will show you how.
solutions business, and maintainer of the popular TestMaker
open-source project
Website: www.pushtotest.com
BUY NOW
The Cohen Blog: www.pushtotest.com/docs/thecohenblog books.dzone.com/books/pro-ajax-java
Bro
ugh
t to
you
by...
Professional Cheat Sheets You Can Trust
tt erns “Exactly what busy developers need:
n Pa
ld
ona
sig son
McD
simple, short, and to the point.”
De
Ja
By
#8
ired
Insp e
by th
GoF ller con
tinu
ed
ndle
r doe
sn’t
have
to
in tab
Cha d ultip ecific o should cep pat
this if the m up the
man
n M
an ac
z.co
n
sp s ents
be a ject ime. d is see passed
Download Now
Com reter of ob at runt handle plem ks to de to
...
n
uest som tion proces e no m
Itera tor ore req
n A g in metho
d
cep
dm ndlin
e e ar
tho e to ptio th
Exce ion is sm to ha up th tered or
e ca
n
Ob
se Me S renc ral
Refcardz.com
plate RN refe listed in mp
le ce pt ni
echa n pa ssed co un avio
Beh
TTE
n
ex
is en
ick
BIRT Windows Powershell
am
Tem Exa he .
A s has ack. W tion uest to ject
NP a qu s, a ct- cep Ob
it
n
st q
IG e s e rn b je call e ex e re
vid patt able O le th nd th
DES
! V is
pro s, hand s to ha
UT ard ign us ram .
des diag
JSF 2.0 Dependency Injection with EJB 3
ct
ABO refc oF) f Re le obje
erns ts o lass exa
mp oke
r
Patt ur (G lemen es c Inv
arz
n F o d rl d h
Des
ig go
f s: E inclu al w
o suc
Th is G a n
l 23 sign Pa
tt e rn e rn
patt , and a
re je ts
t ob mentin
c g AN
D
Adobe AIR Netbeans IDE JavaEditor
c
a h c M M
ef
in c u
orig kD
e
re.
Ea tion ons
tr ple CO ma
nd
boo Softwa rma to c their im om
BPM&BPMN Getting Started with Eclipse
re R
( low
e x p o n la rg cute is al ch
ati an b rm ts. +exe . Th
bject nship
s su
Cre y c fo je c an o
t th
e
ed
to ob ms, d as ed rela
tio
Get
nsh
ips
that
can psu
Enca quest
the
re
late
sa
and
e ha
to b llbacks
ca
.
nalit
y.
riant
times
or in
varia
ling
the
invo
catio
ing
n.
DZone, Inc.
ra o pose uing nctio led at va hand
io n ti ct cess be
av ,a la P ur
as q
ue
ack
fu je pro
Beh nships t re
1251 NW Maynard
e nd ob to
c b callb e ha eded. the nous nality
ob je a n b m ro ed
at c
ed to fro y ne
tio You ne s need
ne
sts is couple
d ynch nctio
rela with s th st que
n
e th
e as the fu
itho
ut an is
eals
it
ship Reque y of re de ar
ld be litat pattern ssing w tation articul
e: D e. tion Use or faci
n
A hist shou d ce en p
ed to mman for pro implem ents its ting.
cop runtim rela type
ker
Cary, NC 27513
n
S s Whe invo y us
n
s co al m pec
jec t at cla Pro
to Th e
w id el th e ue ue
ac tu
d im
p le ex
are utilizing a job q of the ue is
Ob ged with
n
C ues ueue e que
han eals me.
y dge enq
que s. B en to th
e c : D P roxy Job orithm be giv knowle that is terface
b e ti
cop
g n ct
pile r S in
rato er mp
le of al ed ca to have d obje of the
ss S at com serv
888.678.0399
Exa ut
Deco nes
an
.com
919.678.0300
one
Abst tory
C C
Fac
B
State
t
pte
r eigh teg
y
Ada Flyw Stra od
z
Meth
more than 3.3 million software developers, architects and decision
S S r B
w. d
ge rp rete plate
Brid
Refcardz Feedback Welcome
B
Inte Tem
S B
er tor or
ww
C B r B
NSIB
ILIT
S
Com
po si te
P O succ
ess
or Sponsorship Opportunities
RES
“DZone is a developer’s dream,” says PC Magazine.
F
CH
AIN
O
ace
>> [email protected]
terf r
<<in andle
H st ( )
re
ndle
+ha
ern
1 ki ng
ler by lin .c o
m
and uest one
teH req z
cre () le a w.d
Con uest hand | ww