Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
Selenium-IDE
Introduction
The Selenium - I DE ( I nt egr at ed Developm ent Env ir onm ent ) is t he t ool you use t o develop your Selenium t est cases. I t s an easy- t o- use Fir efox plug- in and is gener ally t he m ost efficient way t o develop t est cases. I t also cont ains a cont ex t m enu t hat allows you t o fir st select a UI elem ent fr om t he br owser s cur r ent ly displayed page and t hen select fr om a list of Selenium com m ands wit h param et er s pr e- defined accor ding t o t he cont ex t of t he select ed UI elem ent. This is not only a t im e- saver, but also an excellent way of lear ning Selenium scr ipt syntax. This chapt er is all about t he Selenium I DE and how t o use it effect ively.
Select I nst all Now. The Fir efox Add- ons window pops up, fir st showing a pr ogr ess bar, and when t he download is com plet e, display s t he following.
1 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
Select I nst all Now. The Fir efox Add- ons window pops up, fir st showing a pr ogr ess bar, and when t he download is com plet e, display s t he following.
Rest ar t Fir efox . Aft er Fir efox r eboot s you will find t he Selenium - I DE list ed under t he Fir efox Tools m enu.
2 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
IDE Features
Menu Bar
The File m enu has opt ions for Test Case and Test Suit e ( suit e of Test Cases) . Using t hese you can add a new Test Case, open a Test Case, save a Test Case, ex por t Test Case in a language of your choice. You can also open t he r ecent Test Case.All t hese opt ions ar e also available for Test Suit e. The Edit m enu allows copy, past e, delet e, undo, and select all operat ions for edit ing the com m ands in your t est case. The Opt ions m enu allows t he changing of set t ings. You can set t he t im eout value for cer t ain com m ands, add user - defined user ex t ensions t o t he base set of Selenium com m ands, and specify t he for m at ( language) used when sav ing your t est cases. The Help m enu is t he st andar d Fir efox Help m enu; only one it em on t his m enu UI Elem ent Docum ent at ion per t ains t o Selenium - I DE.
Toolbar
The t oolbar cont ains but t ons for cont r olling t he execut ion of your t est cases, including a st ep feat ur e for debugging your t est cases. The r ight - m ost but t on, t he one wit h t he r ed-dot, is t he r ecor d but t on.
Speed Cont r ol: cont r ols how fast your t est case r uns.
Run All: Runs t he ent ir e t est suit e when a t est suit e wit h m ult iple t est cases is loaded.
Run: Runs t he cur r ent ly select ed t est . When only a single t est is loaded t his but t on and t he Run All but t on have t he sam e effect .
St ep: Allows you t o st ep t hr ough a t est case by r unning it one com m and at a t im e. Use for debugging t est cases.
Test Runner Mode: Allows you t o r un t he t est case in a br owser loaded wit h t he Selenium - Cor e Test Runner. The Test Runner is not com m only used now and is likely t o be depr ecat ed. This but t on is for evaluat ing t est cases for back war ds com pat ibilit y wit h the Test Runner. Most user s will pr obably not need t his but t on.
Apply Rollup Rules: This advanced feat ur e allows r epet it ive sequences of Selenium com m ands t o be gr ouped int o a single act ion. Det ailed docum ent at ion on r ollup r ules can be found in t he UI - Elem ent Docum ent at ion on t he Help m enu.
3 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
The ot her t ab - Sour ce display s t he t est case in t he nat ive for m at in which t he file will be st or ed. By default , t his is HTML alt hough it can be changed t o a pr ogr am m ing language such as Java or C# , or a scr ipt ing language like Py t hon. See t he Opt ions m enu for det ails. The Sour ce v iew also allows one t o edit t he t est case in it s r aw for m , including copy, cut and past e oper at ions. The Com m and, Tar get , and Value ent r y fields display t he cur r ent ly select ed com m and along wit h it s par am et er s. These ar e ent r y fields wher e you can m odify t he cur r ent ly select ed com m and. The fir st par am et er specified for a com m and in t he Refer ence t ab of t he bot t om pane alway s goes in t he Tar get field. I f a second par am et er is specified by t he Refer ence t ab, it alway s goes in t he Value field.
I f you st ar t t y ping in t he Com m and field, a dr op- down list will be populat ed based on the fir st char act er s you t y pe; you can t hen select your desir ed com m and fr om t he dr op- down.
Log/Reference/UI-Element/Rollup Pane
The bot t om pane is used for four differ ent funct ions Log, Refer ence, UI - Elem ent , and Rollup depending on which t ab is select ed. Log When you r un your t est case, er r or m essages and infor m at ion m essages showing t he pr ogr ess ar e displayed in t his pane aut om at ically, even if you do not fir st select t he Log t ab. These m essages ar e oft en useful for t est case debugging. Not ice t he Clear but t on for clear ing t he Log. Also not ice t he I nfo but t on is a dr op- down allowing select ion of differ ent levels of infor m at ion t o log.
Reference The Refer ence t ab is t he default select ion whenever you ar e ent er ing or m odify ing Selenese com m ands and par am et er s in Table m ode. I n Table m ode, t he Refer ence pane will display docum ent at ion on t he cur r ent com m and. When ent er ing or m odify ing com m ands, whet her fr om Table or Sour ce m ode, it is cr it ically im por t ant t o ensur e t hat t he par am et er s specified in t he Tar get and Value fields m at ch t hose specified in t he par am et er list in t he Refer ence pane. The num ber of par am et er s pr ov ided m ust m at ch t he num ber specified, t he or der of par am et er s pr ov ided m ust m at ch t he or der specified, and t he t y pe of par am et er s pr ov ided m ust m at ch t he t y pe specified. I f t her e is a m ism at ch in any of t hese t hr ee ar eas, t he com m and will not r un cor r ect ly.
While t he Refer ence t ab is invaluable as a quick r efer ence, it is st ill oft en necessary to consult t he Selenium Reference document. UI-Element and Rollup Det ailed infor m at ion on t hese t wo panes ( which cover advanced feat ur es) can be found in t he UI - Elem ent Docum ent at ion on t he Help m enu of Selenium - I DE.
Recording
Many fir st - t im e user s begin by r ecor ding a t est case fr om t heir int eract ions wit h a websit e. When Selenium - I DE is fir st opened, t he r ecor d but t on is ON by default . I f you do not want Selenium - I DE t o begin r ecor ding aut om at ically you can t ur n t his off by going under Opt ions > Opt ions... and deselect ing St ar t r ecor ding im m ediat ely on open.
4 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
When Selenium - I DE is fir st opened, t he r ecor d but t on is ON by default . I f you do not want Selenium - I DE t o begin r ecor ding aut om at ically you can t ur n t his off by going under Opt ions > Opt ions... and deselect ing St ar t r ecor ding im m ediat ely on open. Dur ing r ecor ding, Selenium - I DE will aut om at ically inser t com m ands int o your t est case based on your act ions. Typically, t his will include: click ing a link - click or clickAndWait commands ent er ing values - type command select ing opt ions fr om a dr op- down list box - select command click ing check boxes or r adio but t ons - click command Her e ar e som e got chas t o be awar e of: The type com m and m ay r equir e click ing on som e ot her ar ea of t he web page for it t o record. Following a link usually r ecor ds a click com m and. You will oft en need t o change t his t o clickAndWait t o ensur e your t est case pauses unt il t he new page is com plet ely loaded. Ot her wise, your t est case will cont inue r unning com m ands befor e t he page has loaded all it s UI elem ent s. This will cause unexpect ed t est case failur es.
Editing
Insert Command
Table View
Select t he point in your t est case wher e you want t o inser t t he com m and. To do t his, in t he Test Case Pane, left - click on t he line wher e you want t o inser t a new com m and. Right - click and select I nser t Com m and; t he I DE will add a blank line j ust ahead of t he line you select ed. Now use t he com m and edit ing t ex t fields t o ent er your new com m and and it s par am et er s.
Source View
Select t he point in your t est case wher e you want t o inser t t he com m and. To do t his, in t he Test Case Pane, left - click bet ween t he com m ands wher e you want t o inser t a new com m and, and ent er t he HTML t ags needed t o cr eat e a 3- colum n r ow cont aining t he Com m and, fir st par am et er ( if one is r equir ed by t he Com m and) , and second par am et er ( again, if one is r equir ed t o locat e an elem ent ) and t hir d param et er ( again, if one is r equir ed t o have a value) . Ex am ple:
<tr> <td>Command</td> <td>target (locator)</td> <td>Value</td> </tr>
Insert Comment Com m ent s m ay be added t o m ake your t est case m or e r eadable. These com m ent s ar e ignor ed when t he t est case is r un. Com m ent s m ay also be used t o add ver t ical whit e space ( one or m or e blank lines) in your t est s; j ust cr eat e em pt y com m ent s. An em pt y com m and will cause an er r or dur ing execut ion; an em pt y com m ent won t .
5 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
Com m ent s m ay also be used t o add ver t ical whit e space ( one or m or e blank lines) in your t est s; j ust cr eat e em pt y com m ent s. An em pt y com m and will cause an er r or dur ing execut ion; an em pt y com m ent won t .
Table View
Select t he line in your t est case wher e you want t o inser t t he com m ent . Right - click and select I nser t Com m ent . Now use t he Com m and field t o ent er t he com m ent . Your com m ent will appear in pur ple t ex t .
Source View
Select t he point in your t est case wher e you want t o inser t t he com m ent . Add an HTML- st y le com m ent , i.e., <!-- your comment here -->. Edit a Command or Comment
Table View
Sim ply select t he line t o be changed and edit it using t he Com m and, Tar get , and Value fields.
Source View
Since Sour ce v iew pr ov ides t he equivalent of a WYSI WYG ( What You See is What You Get ) edit or, sim ply m odify which line you wish com m and, par am et er, or com m ent .
6 de 21
This sam e t est case wit h a m odified Base URL set t ing would be r un against ht t p: / / bet a.news.por t al.com / about .ht m l:
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
This sam e t est case wit h a m odified Base URL set t ing would be r un against ht t p: / / bet a.news.por t al.com / about .ht m l:
Selenium Commands
Selenese
Selenium com m ands, oft en called selenese, are the set of commands that run your tests. A sequence of t hese com m ands is a test script. Her e we ex plain t hose com m ands in det ail, and we pr esent t he m any choices you have in t est ing your web applicat ion when using Selenium . Selenium pr ov ides a r ich set of com m ands for fully t est ing your web- app in v ir t ually any way you can im agine. The com m and set is oft en called selenese. These com m ands essent ially cr eat e a t est ing language. I n selenese, one can t est t he ex ist ence of UI elem ent s based on t heir HTML t ags, t est for specific cont ent , t est for br oken link s, input fields, select ion list opt ions, subm it t ing for m s, and t able dat a am ong ot her t hings. I n addit ion Selenium com m ands suppor t t est ing of window size, m ouse posit ion, aler t s, Aj ax funct ionalit y, pop up windows, event handling, and many ot her web- applicat ion feat ur es. The Command Reference list s all t he available com m ands. A command t ells Selenium what t o do. Selenium com m ands com e in t hr ee flavor s : Actions, Accessors, and Assertions. Actions ar e com m ands t hat gener ally m anipulat e t he st at e of t he applicat ion. They do t hings like click t his link and select t hat opt ion . I f an Act ion fails, or has an error, the execut ion of t he cur r ent t est is st opped. Many Act ions can be called wit h t he AndWait suffix , e.g. click AndWait . This suffix t ells Selenium t hat t he act ion will cause t he br owser t o m ake a call t o t he ser ver, and t hat Selenium should wait for a new page t o load. Accessors ex am ine t he st at e of t he applicat ion and st or e t he r esult s in var iables, e.g. st or eTit le . They ar e also used t o aut om at ically gener at e Asser t ions. Assertions ar e like Accessor s, but t hey ver ify t hat t he st at e of t he applicat ion confor m s t o what is ex pect ed. Ex am ples include m ake sur e t he page t it le is X and ver ify t hat t his check box is checked . All Selenium Asser t ions can be used in 3 m odes: asser t , ver ify , and wait For . For ex am ple, you can asser t Text , ver ify Tex t and wait For Tex t . When an asser t fails, t he t est is abor t ed. When a ver ify fails, t he t est will cont inue execut ion, logging the failur e. This allows a single asser t t o ensur e t hat t he applicat ion is on t he cor r ect page, followed by a bunch of ver ify asser t ions t o t est for m field values, labels, et c. wait For com m ands wait for som e condit ion t o becom e t r ue ( which can be useful for t est ing Aj ax applicat ions) . They will succeed im m ediat ely if t he condit ion is alr eady true. However, t hey will fail and halt t he t est if t he condit ion does not becom e t r ue wit hin the cur r ent t im eout set t ing ( see t he set Tim eout act ion below) .
Script Syntax
Selenium com m ands ar e sim ple, t hey consist of t he com m and and t wo par am et er s. For ex am ple: ver ify Tex t / / div/ / a[ 2] Login
The par am et er s ar e not alway s r equir ed; it depends on t he com m and. I n som e cases bot h are r equir ed, in ot her s one param et er is r equir ed, and in st ill ot her s t he com m and m ay t ake no par am et er s at all. Her e ar e a couple m or e ex am ples: goBack AndWait ver ify Tex t Pr esent type type id= phone id= addr ess1 Welcom e t o My Hom e Page (555) 666-7066
The com m and r efer ence descr ibes t he par am et er r equir em ent s for each com m and. Par am et er s var y, however t hey ar e t y pically : a locator for ident ify ing a UI elem ent wit hin a page. a text pattern for ver ify ing or asser t ing ex pect ed page cont ent a text pattern or a selenium var iable for ent er ing t ex t in an input field or for select ing an opt ion fr om an opt ion list . Locat or s, t ex t pat t er ns, selenium var iables, and t he com m ands t hem selves ar e descr ibed in consider able det ail in t he sect ion on Selenium Com m ands.
7 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
Locat or s, t ex t pat t er ns, selenium var iables, and t he com m ands t hem selves ar e descr ibed in consider able det ail in t he sect ion on Selenium Com m ands. Selenium scr ipt s t hat will be r un fr om Selenium - I DE will be be st or ed in an HTML t ex t file for m at . This consist s of an HTML t able wit h t hr ee colum ns. The fir st colum n ident ifies the Selenium com m and, t he second is a t ar get , and t he final colum n cont ains a value. The second and t hir d colum ns m ay not r equir e values depending on t he chosen Selenium com m and, but t hey should be pr esent . Each t able r ow r epr esent s a new Selenium com m and. Her e is an ex am ple of a t est t hat opens a page, asser t s t he page t it le and t hen ver ifies som e content on the page:
<table> <tr><td>open</td><td>/download/</td><td></td></tr> <tr><td>assertTitle</td><td></td><td>Downloads</td></tr> <tr><td>verifyText</td><td>//h2</td><td>Downloads</td></tr> </table>
Render ed as a t able in a br owser t his would look like t he following: open asser t Tit le ver ify Tex t //h2 / download/ Downloads Downloads
The Selenese HTML sy nt ax can be used t o wr it e and r un t est s wit hout r equir ing k nowledge of a pr ogr am m ing language. Wit h a basic k nowledge of selenese and Selenium - I DE you can quick ly pr oduce and r un t est cases.
Test Suites
A t est suit e is a collect ion of t est s. Oft en one will r un all t he t est s in a t est suite as one cont inuous bat ch- j ob. When using Selenium - I DE, t est suit es also can be defined using a sim ple HTML file. The syntax again is sim ple. An HTML t able defines a list of t est s wher e each r ow defines t he filesystem pat h t o each t est . An ex am ple t ells it all.
<html> <head> <title>Test Suite Function Tests - Priority 1</title> </head> <body> <table> <tr><td><b>Suite Of Tests</b></td></tr> <tr><td><a href="./Login.html">Login</a></td></tr> <tr><td><a href="./SearchValues.html">Test Searching for Values</a></td></tr> <tr><td><a href="./SaveValues.html">Test Save</a></td></tr> </table> </body> </html>
A file sim ilar t o t his would allow r unning t he t est s all at once, one aft er anot her, from the Selenium - I DE. Test suit es can also be m aint ained when using Selenium - RC. This is done v ia pr ogr am m ing and can be done a num ber of way s. Com m only Junit is used t o m aint ain a t est suit e if one is using Selenium - RC wit h Java. Addit ionally, if C# is t he chosen language, Nunit could be em ployed. I f using an int er pr et ed language like Py t hon wit h Selenium - RC t hen som e sim ple pr ogr am m ing would be involved in set t ing up a t est suit e. Since t he whole r eason for using Selenium - RC is t o m ake use of pr ogr am m ing logic for your t est ing t his usually isn t a pr oblem .
8 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
is used.
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
waitForElementPresent pauses execut ion unt il an ex pect ed UI elem ent , as defined by it s HTML t ag, is pr esent on the page.
Assertion or Verification?
Choosing bet ween asser t and ver ify com es down t o convenience and m anagem ent of failur es. Ther e s ver y lit t le point check ing t hat t he fir st par agr aph on t he page is the correct one if your t est has alr eady failed when check ing t hat t he br owser is display ing t he expected page. I f you r e not on t he cor r ect page, you ll pr obably want t o abor t your t est case so that you can invest igat e t he cause and fix t he issue( s) pr om pt ly. On t he ot her hand, you m ay want t o check m any at t r ibut es of a page wit hout abor t ing t he t est case on t he fir st failur e as t his will allow you t o r ev iew all failur es on t he page and t ake t he appr opr iat e act ion. Effect ively an asser t will fail t he t est and abor t t he cur r ent t est case, wher eas a ver ify will fail t he t est and cont inue t o r un t he t est case. The best use of t his feat ur e is t o logically gr oup your t est com m ands, and st ar t each group wit h an asser t followed by one or m or e ver ify t est com m ands. An ex am ple follows: Command open asser t Tit le ver ify Tex t asser t Table ver ify Table ver ify Table Target / download/ Downloads //h2 1.2.1 1.2.2 1.2.3 Downloads Selenium I DE June 3, 2008 1.0 beta 2 Value
The above ex am ple fir st opens a page and t hen asser t s t hat t he cor r ect page is loaded by com par ing t he t it le wit h t he ex pect ed value. Only if t his passes will t he following command run and ver ify t hat t he t ex t is pr esent in t he expect ed locat ion. The t est case t hen asser t s t he fir st colum n in t he second r ow of t he fir st t able cont ains t he ex pect ed value, and only if t his passed will t he r em aining cells in t hat r ow be ver ified .
verifyTextPresent
The command verifyTextPresent is used t o ver ify specific text exists somewhere on the page. I t t akes a single ar gum ent t he t ex t pat t er n t o be ver ified. For ex am ple: Command Target Value
ver ifyTex t Pr esent Mar ket ing Analy sis This would cause Selenium t o sear ch for, and ver ify, t hat t he t ex t st r ing Mar ket ing Analy sis appear s som ewher e on t he page cur r ent ly being t est ed. Use verifyTextPresent when you ar e int er est ed in only t he t ex t it self being pr esent on t he page. Do not use t his when you also need t o t est wher e t he t ex t occur s on t he page.
verifyElementPresent
Use t his com m and when you m ust t est for t he pr esence of a specific UI elem ent , r at her t han it s cont ent . This ver ificat ion does not check t he t ex t , only t he HTML t ag. One common use is t o check for t he pr esence of an im age. Command Target Value
ver ifyElem ent Pr esent / / div / p/ im g This com m and ver ifies t hat an im age, specified by t he ex ist ence of an < im g> HTML t ag, is pr esent on t he page, and t hat it follows a < div > t ag and a < p> t ag. The fir st ( and only ) par am et er is a locator for t elling t he Selenese com m and how t o find t he elem ent . Locat or s ar e ex plained in t he nex t sect ion.
verifyElementPresent can be used t o check t he ex ist ence of any HTML t ag wit hin t he page.
You can check t he ex ist ence of link s, par agr aphs, div isions < div > , et c. Her e ar e a few more ex am ples. Command Target Value
ver ifyElem ent Pr esent / / div / p ver ifyElem ent Pr esent / / div / a ver ifyElem ent Pr esent id= Login
9 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
ver ifyElem ent Pr esent / / div / p ver ifyElem ent Pr esent / / div / a ver ifyElem ent Pr esent id= Login ver ifyElem ent Pr esent link = Go t o Mar ket ing Resear ch ver ifyElem ent Pr esent //a[2] ver ifyElem ent Pr esent / / head/ t it le These exam ples illust r at e t he var iet y of way s a UI elem ent m ay be t est ed. Again, locators ar e ex plained in t he nex t sect ion.
verifyText
Use verifyText when bot h t he t ex t and it s UI elem ent m ust be t est ed. verifyText must use a locat or. I f you choose an XPath or DOM locat or, you can ver ify t hat specific t ex t appear s at a specific locat ion on t he page r elat ive t o ot her UI com ponent s on t he page. Command Target ver ifyTex t / / t able/ t r / t d / div / p Value This is m y t ex t and it occur s r ight aft er t he div inside t he t able.
Locating Elements
For m any Selenium com m ands, a t ar get is r equir ed. This t ar get ident ifies an elem ent in the cont ent of t he web applicat ion, and consist s of t he locat ion st r at egy followed by t he locat ion in the format locatorType=location. The locat or t y pe can be om it t ed in m any cases. The var ious locat or t ypes ar e ex plained below wit h ex am ples for each.
Locating by Identifier
This is pr obably t he m ost com m on m et hod of locat ing elem ent s and is t he cat ch- all default when no r ecognized locat or t y pe is used. Wit h t his st r at egy, t he fir st elem ent wit h t he id at t r ibut e value m at ching t he locat ion will be used. I f no elem ent has a m at ching id at t r ibut e, t hen t he fir st elem ent wit h a nam e at t r ibut e m at ching t he locat ion will be used. For inst ance, your page sour ce could have id and nam e at t r ibut es as follows:
1 <html> 2 <body> 3 <form id="loginForm"> 4 <input name="username" type="text" /> 5 <input name="password" type="password" /> 6 <input name="continue" type="submit" value="Login" /> 7 </form> 8 </body> 9 <html>
The following locat or st r at egies would r et ur n t he elem ent s fr om t he HTML snippet above indicat ed by line num ber :
identifier=loginForm (3) identifier=password (5) identifier=continue (6) continue (6)
Since t he identifier t y pe of locat or is t he default , t he identifier= in t he fir st t hr ee ex am ples above is not necessar y. Locating by Id This t y pe of locat or is m or e lim it ed t han t he ident ifier locat or t y pe, but also m or e ex plicit . Use t his when you k now an elem ent s id at t r ibut e.
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id="loginForm"> <input name="username" <input name="password" <input name="continue" <input name="continue" </form> </body> <html>
type="text" /> type="password" /> type="submit" value="Login" /> type="button" value="Clear" />
id=loginForm (3)
Locating by Name The nam e locat or t y pe will locat e t he fir st elem ent wit h a m at ching nam e at t r ibut e. I f m ult iple elem ent s have t he sam e value for a nam e at t r ibut e, t hen you can use filt er s to fur t her r efine your locat ion st r at egy. The default filt er t y pe is value ( m at ching t he value at t r ibut e) .
10 de 21
1 2 3 4 5 6
<html> <body> <form id="loginForm"> <input name="username" type="text" /> <input name="password" type="password" /> <input name="continue" type="submit" value="Login" />
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
2 3 4 5 6 7 8 9 10
<body> <form id="loginForm"> <input name="username" <input name="password" <input name="continue" <input name="continue" </form> </body> <html>
type="text" /> type="password" /> type="submit" value="Login" /> type="button" value="Clear" />
name=username (4) name=continue value=Clear (7) name=continue Clear (7) name=continue type=button (7)
Note Unlike som e t ypes of XPat h and DOM locat or s, t he t hr ee t ypes of locat or s above allow Selenium t o t est a UI elem ent independent of it s locat ion on t he page. So if t he page st r uct ur e and or ganizat ion is alt er ed, t he t est will st ill pass. You m ay or m ay not want to also t est whet her t he page st r uct ur e changes. I n t he case wher e web designer s fr equent ly alt er t he page, but it s funct ionalit y m ust be r egr ession t est ed, t est ing via id and nam e at t r ibut es, or r eally v ia any HTML pr oper t y, becom es ver y im por t ant . Locating by XPath XPat h is t he language used for locat ing nodes in an XML docum ent . As HTML can be an im plem ent at ion of XML ( XHTML) , Selenium user s can lever age t his power ful language t o t ar get elem ent s in t heir web applicat ions. XPat h ex t ends beyond ( as well as suppor t ing) t he sim ple m et hods of locat ing by id or nam e at t r ibut es, and opens up all sor t s of new possibilit ies such as locat ing t he t hir d check box on t he page. One of t he m ain r easons for using XPat h is when you don t have a suit able id or nam e at t r ibut e for t he elem ent you wish t o locat e. You can use XPat h t o eit her locat e t he elem ent in absolut e t er m s ( not adv ised) , or r elat ive t o an elem ent t hat does have an id or nam e at t r ibut e. XPat h locat or s can also be used t o specify elem ent s v ia at t r ibut es ot her t han id and nam e. Absolut e XPat hs cont ain t he locat ion of all elem ent s fr om t he r oot ( ht m l) and as a r esult ar e likely t o fail wit h only t he slight est adj ust m ent t o t he applicat ion. By finding a near by elem ent wit h an id or nam e at t r ibut e ( ideally a par ent elem ent ) you can locat e your t ar get elem ent based on t he r elat ionship. This is m uch less likely t o change and can make your tests more robust. Since only xpath locat or s st ar t wit h / / , it is not necessar y t o include t he xpath= label when specify ing an XPat h locat or.
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id="loginForm"> <input name="username" <input name="password" <input name="continue" <input name="continue" </form> </body> <html>
type="text" /> type="password" /> type="submit" value="Login" /> type="button" value="Clear" />
changed only slightly) //form[1] (3) - First form element in the HTML
xpath=//form[@id='loginForm'] (3) - The for m elem ent wit h at t r ibut e nam ed id
elem ent wit h at t r ibut e nam ed nam e and t he v alue user nam e //input[@name='username'] (4) - Fir st input elem ent wit h at t r ibut e nam ed nam e and t he value user nam e //form[@id='loginForm']/input[1] (4) - First input child element of the form elem ent wit h at t r ibut e nam ed id and t he v alue loginFor m //input[@name='continue'][@type='button'] (7) - Input with attribute named nam e and t he value cont inue and at t r ibut e nam ed t y pe and t he v alue but t on //form[@id='loginForm']/input[4] (7) - Fourth input child element of the form elem ent wit h at t r ibut e nam ed id and v alue loginFor m These ex am ples cover som e basics, but in or der t o lear n m or e, t he following r efer ences are recommended: W3Schools XPat h Tut or ial W3C XPat h Recom m endat ion Ther e ar e also a couple of ver y useful Fir efox Add- ons t hat can assist in discover ing the XPat h of an elem ent : XPath Checker - suggest s XPat h and can be used t o t est XPat h r esult s. Fir ebug - XPat h suggest ions ar e j ust one of t he m any power ful feat ur es of t his ver y useful add- on.
11 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
XPath Checker - suggest s XPat h and can be used t o t est XPat h r esult s. Fir ebug - XPat h suggest ions ar e j ust one of t he m any power ful feat ur es of t his ver y useful add- on. Locating Hyperlinks by Link Text This is a sim ple m et hod of locat ing a hyper link in your web page by using t he t ex t of the link . I f t wo links wit h t he sam e t ex t ar e pr esent , t hen t he fir st m at ch will be used.
1 <html> 2 <body> 3 <p>Are you sure you want to do this?</p> 4 <a href="continue.html">Continue</a> 5 <a href="cancel.html">Cancel</a> 6 </body> 7 <html>
Locating by DOM The Docum ent Obj ect Model r epr esent s an HTML docum ent and can be accessed using JavaScr ipt . This locat ion st r at egy t akes JavaScr ipt t hat evaluat es t o an elem ent on t he page, which can be sim ply t he elem ent s locat ion using t he hier ar chical dot t ed not at ion. Since only dom locat or s st ar t wit h docum ent , it is not necessar y t o include t he dom= label when specify ing a DOM locat or.
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id="loginForm"> <input name="username" <input name="password" <input name="continue" <input name="continue" </form> </body> <html>
type="text" /> type="password" /> type="submit" value="Login" /> type="button" value="Clear" />
dom=document.getElementById('loginForm') (3) dom=document.forms['loginForm'] (3) dom=document.forms[0] (3) document.forms[0].username (4) document.forms[0].elements['username'] (4) document.forms[0].elements[0] (4) document.forms[0].elements[3] (7)
You can use Selenium it self as well as ot her sit es and ex t ensions t o ex plor e t he DOM of your web applicat ion. A good r efer ence ex ist s on W3Schools. Locating by CSS CSS ( Cascading St y le Sheet s) is a language for descr ibing t he r ender ing of HTML and XML docum ent s. CSS uses Select or s for binding st yle pr oper t ies t o elem ent s in t he docum ent . These Select or s can be used by Selenium as anot her locat ing st r at egy.
1 2 3 4 5 6 7 8 9 10
<html> <body> <form id="loginForm"> <input class="required" name="username" type="text" /> <input class="required passfield" name="password" type="password" /> <input name="continue" type="submit" value="Login" /> <input name="continue" type="button" value="Clear" /> </form> </body> <html>
css=form#loginForm (3) css=input[name="username"] (4) css=input.required[type="text"] (4) css=input.passfield (5) css=#loginForm input[type="button"] (7) css=#loginForm input:nth-child(2) (5)
For m or e infor m at ion about CSS Select or s, t he best place t o go is t he W3C publicat ion. You ll find addit ional r efer ences t her e. Note Most ex per ienced Selenium user s r ecom m end CSS as t heir locat ing st r at egy of choice as it s consider ably fast er t han XPat h and can find t he m ost com plicat ed obj ect s in an int r insic HTML docum ent .
12 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
Most ex per ienced Selenium user s r ecom m end CSS as t heir locat ing st r at egy of choice as it s consider ably fast er t han XPat h and can find t he m ost com plicat ed obj ect s in an int r insic HTML docum ent . Implicit Locators You can choose t o om it t he locat or t y pe in t he following sit uat ions: Locat or s wit hout an ex plicit ly defined locat or st r at egy will default t o using t he ident ifier locat or st r at egy. See Locat ing by I dent ifier. Locat or s st ar t ing wit h / / will use t he XPat h locat or st r at egy. See Locat ing by XPat h. Locat or s st ar t ing wit h docum ent will use t he DOM locat or st r at egy. See Locat ing by DOM
Globbing Patterns
Most people ar e fam iliar wit h globbing as it is ut ilized in filenam e ex pansion at a DOS or Unix/ Linux com m and line such as ls *.c. I n t his case, globbing is used t o display all t he files ending wit h a .c ext ension t hat ex ist in t he cur r ent dir ect or y. Globbing is fair ly lim it ed. Only t wo special char act er s ar e suppor t ed in t he Selenium im plem ent at ion: * which t ranslat es t o m at ch any t hing, i.e., not hing, a single char act er, or many characters. [ ] (character class) which t r anslat es t o m at ch any single char act er found inside t he squar e br acket s. A dash ( hy phen) can be used as a shor t hand t o specify a r ange of charact er s ( which ar e cont iguous in t he ASCI I char act er set ) . A few ex am ples will m ake t he funct ionalit y of a char act er class clear :
[aeiou] m at ches any lower case vowel [0-9] m at ches any digit [a-zA-Z0-9] m at ches any alphanum er ic char act er
I n m ost ot her cont ex t s, globbing includes a t hir d special char act er, t he ?. However, Selenium globbing pat t er ns only suppor t t he ast er isk and char act er class. To specify a globbing pat t er n par am et er for a Selenese com m and, you can pr efix t he pat t er n wit h a glob: label. However, because globbing pat t er ns ar e t he default , you can also om it t he label and specify j ust t he pat t er n it self. Below is an ex am ple of t wo com m ands t hat use globbing pat t er ns. The act ual link t ex t on t he page being t est ed was Film / Telev ision Depar t m ent ; by using a pat t er n r at her t han the exact text, the click com m and will wor k even if t he link t ex t is changed t o Film & Telev ision Depar t m ent or Film and Telev ision Depar t m ent . The glob pat t er n s ast er isk will m at ch any t hing or not hing bet ween t he wor d Film and t he wor d Telev ision . Command Target click ver ifyTit le link = glob: Film * Telev ision Depar t m ent glob: * Film * Telev ision* Value
The act ual t it le of t he page r eached by click ing on t he link was De Anza Film And Telev ision Depar t m ent - Menu . By using a pat t er n rat her t han t he ex act t ex t , t he verifyTitle will pass as long as t he t wo wor ds Film and Telev ision appear ( in t hat or der ) anywher e in t he page s t it le. For ex am ple, if t he page s owner should shor t en the t it le t o j ust Film & Telev ision Depar t m ent , t he t est would st ill pass. Using a pat t ern for bot h a link and a sim ple t est t hat t he link wor ked ( such as t he verifyTitle above does) can gr eat ly r educe t he m aint enance for such t est cases. Regular Expression Patterns Regular expression pat t er ns ar e t he m ost power ful of t he t hr ee t y pes of pat t er ns t hat Selenese suppor t s. Regular ex pr essions ar e also suppor t ed by m ost high- level pr ogr am m ing languages, m any t ex t edit or s, and a host of t ools, including t he Linux / Unix com m and- line ut ilit ies grep, sed, and awk. I n Selenese, r egular ex pr ession pat t er ns allow a user t o per for m m any t ask s t hat would be ver y difficult ot her wise. For ex am ple, suppose your t est needed t o ensur e t hat a par t icular t able cell cont ained not hing but a number. regexp: [0-9]+ is a sim ple pat t er n t hat will m at ch a decim al num ber of any lengt h. Wher eas Selenese globbing pat t er ns suppor t only t he * and [ ] ( char act er class) feat ur es, Selenese r egular expr ession pat t er ns offer t he sam e wide ar r ay of special char act er s t hat ex ist in JavaScr ipt . Below ar e a subset of t hose special char act er s: PATTERN . [ ] * + MATCH any single char act er char act er class: any single char act er t hat appear s inside t he br acket s quant ifier : 0 or m or e of t he pr eceding char act er ( or gr oup) quant ifier : 1 or m or e of t he pr eceding char act er ( or gr oup)
13 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
. [ ] * + ? {1,5} | () any single char act er
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
char act er class: any single char act er t hat appear s inside t he br acket s quant ifier : 0 or m or e of t he pr eceding char act er ( or gr oup) quant ifier : 1 or m or e of t he pr eceding char act er ( or gr oup) quant ifier : 0 or 1 of t he pr eceding char act er ( or gr oup) quant ifier : 1 t hr ough 5 of t he pr eceding char act er ( or gr oup) alt er nat ion: t he char act er / gr oup on t he left or t he char act er / gr oup on t he r ight gr ouping: oft en used wit h alt er nat ion and/ or quant ifier
Regular ex pr ession pat t er ns in Selenese need t o be pr efixed wit h eit her regexp: or regexpi:. The for m er is case- sensit ive; t he lat t er is case- insensit ive. A few ex am ples will help clar ify how r egular ex pr ession pat t er ns can be used wit h Selenese com m ands. The fir st one uses what is pr obably t he m ost com m only used r egular ex pr ession pat t er n .* ( dot st ar ) . This t wo- char act er sequence can be t r anslat ed as 0 or m or e occur r ences of any char act er or m or e sim ply, any t hing or not hing. I t is t he equivalent of t he one- char act er globbing pat t er n * ( a single ast er isk ) . Command Target click ver ify Tit le link = r egex p: Film .* Television Depar t m ent r egex p: .* Film .* Telev ision.* Value
The ex am ple above is funct ionally equivalent t o t he ear lier ex am ple t hat used globbing pat t er ns for t his sam e t est . The only differ ences ar e t he pr efix ( regexp: inst ead of glob:) and t he any t hing or not hing pat t er n ( .* inst ead of j ust * ). The m or e com plex ex am ple below t est s t hat t he Yahoo! Weat her page for Anchor age, Alask a cont ains info on t he sunr ise t im e: Command open ver ify Tex t Pr esent Target http://weather.yahoo.com/forecast/USAK0012.html r egex p: Sunr ise: * [ 0- 9] { 1,2} : [ 0- 9] { 2} [ ap] m Value
The st r ing Sunrise: followed by 0 or m or e spaces 1 or 2 digit s ( for t he hour of t he day ) The character : ( no special char act er s involved) 2 digit s ( for t he m inut es) followed by a space a or p followed by m ( am or pm )
Exact Patterns The exact t ype of Selenium pat t er n is of m ar ginal usefulness. I t uses no special char act er s at all. So, if you needed t o look for an act ual ast er isk char act er ( which is special for bot h globbing and r egular ex pr ession pat t er ns) , t he exact pat t er n would be one way t o do t hat . For ex am ple, if you want ed t o select an it em labeled Real * fr om a dr opdown, t he following code m ight wor k or it m ight not . The ast er isk in t he glob:Real * pat t er n will m at ch any t hing or not hing. So, if t her e was an ear lier select opt ion labeled Real Num ber s, it would be t he opt ion select ed r at her t han t he Real * opt ion. select / / select glob: Real *
I n or der t o ensur e t hat t he Real * it em would be select ed, t he exact: pr efix could be used to create an exact pat t er n as shown below: select / / select ex act : Real *
But t he sam e effect could be achieved via escaping t he ast er isk in a r egular ex pr ession pattern: select / / select r egexp: Real \ *
I t s r at her unlikely t hat m ost t est er s will ever need t o look for an ast er isk or a set of squar e br acket s wit h char act er s inside t hem ( t he char act er class for globbing pat t er ns). Thus, globbing pat t er ns and r egular ex pr ession pat t er ns ar e sufficient for t he vast m aj or it y of us.
14 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
I n AJAX dr iven web applicat ions, dat a is r et r ieved fr om ser ver wit hout r efr eshing t he page. Using andWait com m ands will not wor k as t he page is not act ually r efr eshed. Pausing t he t est execut ion for a cer t ain per iod of t im e is also not a good appr oach as web elem ent m ight appear lat er or ear lier t han t he st ipulat ed per iod depending on t he sy st em s r esponsiveness, load or ot her uncont r olled fact or s of t he m om ent , leading t o t est failur es. The best approach would be t o wait for t he needed elem ent in a dynam ic per iod and t hen cont inue t he execut ion as soon as t he elem ent is found. This is done using waitFor commands, as waitForElementPresent or waitForVisible, which wait dy nam ically, check ing for t he desir ed condit ion ever y second and cont inuing t o t he next com m and in t he scr ipt as soon as t he condit ion is m et .
Lat er in your scr ipt , you ll want t o use t he st or ed value of your var iable. To access t he value of a var iable, enclose t he var iable in cur ly br acket s ( { } ) and pr ecede it wit h a dollar sign like t his. Command Target ver ify Tex t / / div / p Value
A com m on use of var iables is for st or ing input for an input field. Command Target type id= login Value
Selenium var iables can be used in eit her t he fir st or second par am et er and ar e int er preted by Selenium pr ior t o any ot her operat ions per for m ed by t he com m and. A Selenium var iable may also be used wit hin a locat or ex pr ession. An equivalent st or e com m and ex ist s for each ver ify and asser t com m and. Her e ar e a couple m or e com m only used st or e com m ands.
storeElementPresent
This cor r esponds t o ver ify Elem ent Pr esent . I t sim ply st or es a boolean value false depending on whet her t he UI elem ent is found. t r ue or
storeText
St or eTex t cor r esponds t o ver ify Tex t . I t uses a locat er t o ident ify specific page t ex t . The text, if found, is st or ed in t he var iable. St or eTex t can be used t o ex t r act t ex t fr om t he page being tested.
storeEval
This com m and t akes a scr ipt as it s fir st par am et er. Em bedding JavaScr ipt wit hin Selenese is cover ed in t he nex t sect ion. St or eEval allows t he t est t o st or e t he r esult of r unning the scr ipt in a var iable.
15 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
ar e st or ed in a JavaScr ipt associative array. An associat ive ar r ay has st r ing indexes r at her t han sequent ial num er ic indexes. The associat ive ar r ay cont aining your t est case s var iables is named storedVars. Whenever you wish t o access or m anipulat e a var iable wit hin a JavaScr ipt snippet , you m ust r efer t o it as st or edVar s[ your Var iableN am e ] .
This nex t ex am ple illust r at es how a JavaScr ipt snippet can include calls t o m et hods, in t his case t he JavaScr ipt St r ing obj ect s toUpperCase method and toLowerCase method. Command Target store storeEval storeEval Edit h Whar t on Value name
JavaScript Usage with Non-Script Parameters JavaScr ipt can also be used t o help gener at e values for param et er s, even when t he par am et er is not specified t o be of t y pe script. However, in t his case, special sy nt ax is r equir ed t he JavaScr ipt snippet m ust be enclosed inside cur ly br aces and pr eceded by t he label javascript, as in javascript {*yourCodeHere*}. Below is an ex am ple in which the type com m and s second par am et er value is gener at ed v ia JavaScr ipt code using t his special sy nt ax : Command Target store type league of nat ions q Value sear chSt r ing j avascr ipt { st or edVar s[ sear chSt r ing ] .t oUpper Case( ) }
16 de 21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> function output(resultText){ document.getElementById('output').childNodes[0].nodeValue=resultText; } function show_confirm(){ var confirmation=confirm("Chose an option."); if (confirmation==true){ output("Confirmed."); } else{ output("Rejected!"); } } function show_alert(){ alert("I'm blocking!"); output("Alert is gone."); } function show_prompt(){ var response = prompt("What's the best web QA tool?","Selenium"); output(response); } function open_window(windowName){ window.open("newWindow.html",windowName); } </script> </head>
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
function open_window(windowName){ window.open("newWindow.html",windowName); } </script> </head> <body> <input type="button" id="btnConfirm" onclick="show_confirm()" value="Show confirm box" /> <input type="button" id="btnAlert" onclick="show_alert()" value="Show alert" /> <input type="button" id="btnPrompt" onclick="show_prompt()" value="Show prompt" /> <a href="newWindow.html" id="lnkNewWindow" target="_blank">New Window Link</a> <input type="button" id="btnNewNamelessWindow" onclick="open_window()" value="Open Nameless Window" <input type="button" id="btnNewNamedWindow" onclick="open_window('Mike')" value="Open Named Window" <br /> <span id="output"> </span> </body> </html>
The user m ust r espond t o aler t / confir m boxes, as well as m ov ing focus t o newly opened popup windows. For t unat ely, Selenium can cover JavaScr ipt pop- ups. But befor e we begin cover ing aler t s/ confir m s/ pr om pt s in indiv idual det ail, it is helpful t o under st and t he com m onalit y bet ween t hem . Aler t s, confir m at ion boxes and pr om pt s all have var iat ions of t he following Command assertFoo(pattern) assertFooPresent assertFooNotPresent storeFoo(variable) Description t hr ows er r or if pattern doesn t m at ch t he t ex t of t he pop- up t hr ows er r or if pop- up is not available t hr ows er r or if any pop- up is pr esent st or es t he t ex t of t he pop- up in a var iable
storeFooPresent(variable) st or es t he t ex t of t he pop- up in a var iable and r et ur ns t r ue or false When r unning under Selenium , JavaScr ipt pop- ups will not appear. This is because t he funct ion calls ar e act ually being over r idden at r unt im e by Selenium s own JavaScr ipt . However, j ust because you cannot see t he pop- up doesn t m ean you don t have t o deal wit h it . To handle a pop- up, you m ust call it s assertFoo(pattern) funct ion. I f you fail t o asser t t he pr esence of a pop- up your nex t com m and will be blocked and you will get an er r or sim ilar t o t he following
[error] Error: There was an unexpected Confirmation! [Chose an option.]
Alerts
Let s st ar t wit h aler t s because t hey ar e t he sim plest pop- up t o handle. To begin, open the HTML sam ple above in a br owser and click on t he Show aler t but t on. You ll not ice t hat aft er you close t he aler t t he t ex t Aler t is gone. is displayed on t he page. Now r un through t he sam e st eps wit h Selenium I DE r ecor ding, and ver ify t he t ex t is added aft er you close t he aler t . Your t est will look som et hing like t his: Command open click asser t Aler t Target / bt nAler t I m block ing! Value
ver ifyTex t Pr esent Aler t is gone. You m ay be t hink ing That s odd, I never t r ied t o asser t t hat aler t . But t his is Selenium - I DE handling and closing t he aler t for you. I f you r em ove t hat st ep and r eplay t he t est you will get t he following er r or [error] Error: There was an unexpected Alert! [I'm blocking!]. You m ust include an asser t ion of t he aler t t o ack nowledge it s pr esence. I f you j ust want t o asser t t hat an aler t is pr esent but eit her don t k now or don t care what t ex t it cont ains, you can use assertAlertPresent. This will r et ur n t r ue or false, wit h false halt ing t he t est . Confirmations Confir m at ions behave in m uch t he sam e way as aler t s, wit h assertConfirmation and assertConfirmationPresent offer ing t he sam e char act er ist ics as t heir aler t count er par t s. However, by default Selenium will select OK when a confir m at ion pops up. Tr y r ecor ding click ing on t he Show confir m box but t on in t he sam ple page, but click on t he Cancel but t on in t he popup, t hen asser t t he out put t ex t . Your t est m ay look som et hing like t his: Command open click chooseCancelOnNex t Confir m at ion asser t Confir m at ion ver ify Tex t Pr esent Choose an opt ion. Rejected Target / bt nConfir m Value
The chooseCancelOnNextConfirmation funct ion t ells Selenium t hat all following confir m at ion should r et ur n false. I t can be r eset by calling chooseOk OnNex t Confir m at ion. You m ay not ice t hat you cannot r eplay t his t est , because Selenium com plains t hat t her e is an unhandled confir m at ion. This is because t he or der of event s Selenium - I DE r ecor ds causes t he click and chooseCancelOnNext Confir m at ion t o be put in t he wr ong or der ( it m akes sense if you t hink about it , Selenium can t k now t hat you r e cancelling befor e you open a confir m at ion) Sim ply swit ch t hese t wo com m ands and your t est will r un fine.
17 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
is an unhandled confir m at ion. This is because t he or der of event s Selenium - I DE r ecor ds causes t he click and chooseCancelOnNext Confir m at ion t o be put in t he wr ong or der ( it m akes sense if you t hink about it , Selenium can t k now t hat you r e cancelling befor e you open a confir m at ion) Sim ply swit ch t hese t wo com m ands and your t est will r un fine.
Debugging
Debugging m eans finding and fix ing er r or s in your t est case. This is a nor m al par t of test case developm ent . We won t t each debugging her e as m ost new user s t o Selenium will alr eady have som e basic ex per ience wit h debugging. I f t his is new t o you, we r ecom m end you ask one of t he developer s in your or ganizat ion.
2. I m m ediat ely pause t he execut ing t est case wit h t he Pause but t on.
Find Button
The Find but t on is used t o see which UI elem ent on t he cur r ent ly displayed webpage ( in the br owser ) is used in t he cur r ent ly select ed Selenium com m and. This is useful when building a locat or for a com m and s fir st par am et er ( see t he sect ion on locators in t he Selenium Com m ands chapt er ) . I t can be used wit h any com m and t hat ident ifies a UI elem ent on a webpage, i.e. click, clickAndWait, type, and cer t ain assert and verify commands, among others. Fr om Table v iew, select any com m and t hat has a locat or par am et er. Click t he Find but t on. Now look on t he webpage: Ther e should be a br ight gr een r ect angle enclosing t he elem ent specified by t he locat or par am et er.
Locator Assistance
Whenever Selenium - I DE r ecor ds a locat or - t y pe ar gum ent , it st or es addit ional infor m at ion which allows t he user t o v iew ot her possible locat or - t y pe ar gum ent s t hat could be used inst ead. This feat ur e can be ver y useful for lear ning m or e about locat or s, and is oft en needed t o help one build a differ ent t y pe of locat or t han t he t y pe t hat was r ecor ded. This locat or assist ance is pr esent ed on t he Selenium - I DE window as a dr op- down list accessible at t he r ight end of t he Tar get field ( only when t he Tar get field cont ains a r ecor ded locat or - t ype ar gum ent ) . Below is a snapshot showing t he cont ent s of t his dr op- down for one com m and. Not e t hat t he fir st colum n of t he dr op- down pr ov ides alt er nat ive locat or s, wher eas t he second colum n indicat es t he t y pe of each alt er nat ive.
18 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
dr op- down for one com m and. Not e t hat t he fir st colum n of t he dr op- down pr ov ides alt er nat ive locat or s, wher eas t he second colum n indicat es t he t y pe of each alt er nat ive.
Note Test case files should not have t o be co- locat ed wit h t he t est suit e file t hat invokes them. And on Mac OS and Linux sy st em s, t hat is indeed t he case. However, at t he t im e of t his wr it ing, a bug pr event s Windows user s fr om being able t o place t he t est cases elsewher e t han wit h the t est suit e t hat invokes t hem .
User Extensions
User ex t ensions ar e JavaScr ipt files t hat allow one t o cr eat e his or her own cust om izat ions and feat ur es t o add addit ional funct ionalit y. Oft en t his is in t he for m of cust om ized com mands alt hough t his ex t ensibilit y is not lim it ed t o addit ional com m ands. Ther e ar e a num ber of useful ex t ensions created by users. I MPORTANT: THI S SECTI ON I S OUT OF DATE WE WI LL BE REVI SI NG THI S SOON.
19 de 21
Per haps t he m ost popular of all Selenium - I DE ex t ensions is one which pr ov ides flow cont r ol in
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
Ther e ar e a num ber of useful ex t ensions created by users. I MPORTANT: THI S SECTI ON I S OUT OF DATE WE WI LL BE REVI SI NG THI S SOON. Per haps t he m ost popular of all Selenium - I DE ex t ensions is one which pr ov ides flow cont r ol in t he for m of while loops and pr im it ive condit ionals. This ex t ension is t he got o_sel_ide.j s. For an ex am ple of how t o use t he funct ionalit y pr ovided by t his ex t ension, look at t he page created by it s aut hor. To inst all t his ex t ension, put t he pat hnam e t o it s locat ion on your com put er in t he Selenium Core extensions field of Selenium - I DE s Opt ions= > Opt ions= > Gener al t ab.
Aft er select ing t he OK but t on, you m ust close and r eopen Selenium - I DE in or der for t he ex t ensions file t o be r ead. Any change you m ake t o an ex t ension will also r equir e you t o close and r eopen Selenium - I DE. I nfor m at ion on wr it ing your own ex t ensions can be found near t he bot t om of t he Selenium Reference document.
Format
For m at , under t he Opt ions m enu, allows you t o select a language for sav ing and display ing t he t est case. The default is HTML. I f you will be using Selenium - RC t o r un your t est cases, t his feat ur e is used t o t r anslat e your t est case int o a pr ogr am m ing language. Select t he language, e.g. Java, PHP , you will be using wit h Selenium - RC for developing your t est pr ogr am s. Then sim ply save t he t est case using File= > Ex por t Test Case As. Your t est case will be t r anslat ed int o a ser ies of funct ions in t he language you choose. Essent ially, pr ogr am code suppor t ing your t est is gener at ed for you by Selenium - I DE. Also, not e t hat if t he gener at ed code does not suit your needs, you can alt er it by edit ing a configur at ion file which defines t he gener at ion pr ocess. Each suppor t ed language has configur at ion set t ings which ar e edit able. This is under t he Opt ions= > Opt ions= > For m at s tab. Note At t he t im e of t his wr it ing, t his feat ur e is not yet suppor t ed by t he Selenium developers. However t he aut hor has alt er ed t he C# for m at in a lim it ed m anner and it has wor ked well.
Troubleshooting
Below is a list of im age/ ex planat ion pair s which descr ibe fr equent sour ces of pr oblem s wit h Selenium - I DE: Table view is not available with this format. This m essage can be occasionally displayed in t he Table t ab when Selenium I DE is launched. The wor k ar ound is t o close and r eopen Selenium I DE. See issue 1008. for m or e infor m at ion. I f you ar e able t o r epr oduce t his r eliably t hen please pr ov ide det ails so t hat we can work on a fix .
error loading test case: no command found You ve used File=>Open t o t r y t o open a t est suit e file. Use File=>Open Test Suite inst ead. An enhancem ent r equest has been r aised t o im pr ove t his er r or m essage. See issue 1010.
20 de 21
28/05/2013 7:23
Selenium-IDE
Selenium Documentation
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp
This t y pe of error m ay indicat e a t im ing pr oblem , i.e., t he elem ent specified by a locat or in your com m and wasn t fully loaded when t he com m and was execut ed. Tr y put t ing a pause 5000 befor e t he com m and t o det er m ine whet her t he pr oblem is indeed r elat ed t o t im ing. I f so, invest igat e using an appr opr iat e waitFor* or *AndWait com m and befor e t he failing command.
Whenever your at t em pt t o use var iable subst it ut ion fails as is t he case for t he open command above, it indicat es t hat you haven t act ually cr eat ed t he var iable whose value you r e t r y ing t o access. This is som et im es due t o put t ing t he var iable in t he Value field when it should be in the Target field or v ice ver sa. I n t he ex am ple above, t he t wo par am et er s for t he store com m and have been er r oneously placed in t he r ever se or der of what is r equir ed. For any Selenese com m and, t he fir st r equir ed par am et er m ust go in t he Target field, and t he second r equir ed par am et er ( if one ex ist s) m ust go in t he Value field.
er r or loading t est case: [ Ex cept ion... Com ponent r et ur ned failur e code: 0x80520012 ( NS_ERROR_FI LE_NOT_FOUND) [ nsI FileI nput St r eam .init ] nr esult : 0x 80520012 ( NS_ERROR_FI LE_NOT_FOUND) locat ion: JS fr am e : : chr om e: / / selenium - ide/ cont ent / fileut ils.j s : : anonym ous : : line 48 dat a: no] One of t he t est cases in your t est suit e cannot be found. Make sur e t hat t he t est case is indeed locat ed wher e t he t est suit e indicat es it is locat ed. Also, m ake sur e t hat your act ual t est case files have t he .ht m l ex t ension bot h in t heir filenam es, and in t he t est suit e file where they are referenced. An enhancem ent r equest has been r aised t o im pr ove t his er r or m essage. See issue 1011.
Your ext ension file s cont ent s have not been r ead by Selenium - I DE. Be sur e you have specified t he pr oper pat hnam e t o t he ex t ensions file v ia Options=>Options=>General in t he Selenium Core extensions field. Also, Selenium - I DE m ust be r est ar t ed aft er any change t o eit her an ex t ensions file or to the contents of the Selenium Core extensions field.
21 de 21
28/05/2013 7:23
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
NOTE: We r e cur r ent ly wor king on docum ent ing t hese sect ions. We believe the information here is accurate, however be aware we are also still working on this chapter. Additional information will be provided as we go which should make this chapter more solid.
Introducing WebDriver
The pr im ar y new feat ur e in Selenium 2.0 is t he int egrat ion of t he WebDr iver API . WebDr iver is designed t o pr ovide a sim pler, m or e concise pr ogram m ing int er face in addit ion t o addr essing som e lim it at ions in t he Selenium - RC API . Selenium -WebDr iver was developed t o bet t er suppor t dynam ic web pages wher e elem ent s of a page m ay change wit hout t he page it self being r eloaded. WebDr iver s goal is t o supply a well- designed obj ect- or ient ed API t hat pr ovides im pr oved suppor t for m oder n advanced web- app t est ing pr oblem s.
Java
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
pr ogram m ing language and your developm ent envir onm ent .
Java
The easiest way t o set up a Selenium 2.0 Java pr oj ect is t o use Maven. Maven will download t he j ava bindings ( t he Selenium 2.0 j ava client librar y) and all it s dependencies, and will cr eat e t he pr oj ect for you, using a m aven pom .xm l ( pr oj ect configurat ion) file. Once you ve done t his, you can im por t t he m aven pr oj ect int o your pr efer r ed I DE, I nt elliJ I DEA or Eclipse. Fir st , cr eat e a folder t o cont ain your Selenium pr oj ect files. Then, t o use Maven, you need a pom .xm l file. This can be cr eat ed wit h a t ext edit or. We won t t each t he det ails of pom .xm l files or for using Maven since t her e ar e alr eady excellent r efer ences on t his. Your pom .xm l file will look som et hing like t his. Cr eat e t his file in t he folder you cr eat ed for your pr oj ect .
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 h <modelVersion>4.0.0</modelVersion> <groupId>MySel20Proj</groupId> <artifactId>MySel20Proj</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.33.0</version> </dependency> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> <version>1.3</version> <exclusions> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-remote-driver</artifact </exclusion> </exclusions> </dependency> </dependencies> </dependencyManagement> </project>
Be sur e you specify t he m ost cur r ent ver sion. At t he t im e of wr it ing, t he ver sion list ed above was t he m ost cur r ent , however t her e wer e fr equent r eleases im m ediat ely aft er t he r elease of Selenium 2.0. Check the Maven download page for t he cur r ent r elease and edit t he above dependency accor dingly. Now, fr om a com m and- line, CD int o t he pr oj ect dir ect or y and r un m aven as follows. 2 de 18 28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp Now, fr om a com m and- line, CD int o t he pr oj ect dir ect or y and r un m aven as follows.
mvn clean install
This will download Selenium and all it s dependencies and will add them to the project. Finally, im por t t he pr oj ect int o your pr efer r ed developm ent envir onm ent . For t hose not fam iliar wit h t his, we ve pr ovided an appendix which shows t his. Importing a maven project into IntelliJ IDEA. Importing a maven project into Eclipse.
C#
As of Selenium 2.2.0, t he C# bindings ar e dist r ibut ed as a set of signed dlls along wit h ot her dependency dlls. Pr ior t o 2.2.0, all Selenium dll s wer e unsigned. To include Selenium in your pr oj ect , sim ply download t he lat est selenium - dot net zip file fr om ht t ps: / / code.google.com / p/ selenium / downloads/ list . I f you ar e using Windows Vist a or above, you should unblock t he zip file befor e unzipping it : Right click on t he zip file, click Pr oper t ies , click Unblock and click OK . Unzip t he cont ent s of t he zip file, and add a r efer ence t o each of t he unzipped dlls t o your pr oj ect in Visual St udio ( or your I DE of choice) . Official NuGet Packages: RC WebDr iver WebDr iver BackedSelenium Support
Python
I f you ar e using Pyt hon for t est aut om at ion t hen you pr obably ar e alr eady fam iliar wit h developing in Pyt hon. To add Selenium t o your Pyt hon envir onm ent r un t he following com m and fr om a com m and- line.
pip install selenium
Pip r equir es pip t o be inst alled, pip also has a dependency on set upt ools. Teaching Pyt hon developm ent it self is beyond t he scope of t his docum ent , however t her e ar e m any r esour ces on Pyt hon and likely developer s in your or ganizat ion can help you get up t o speed.
Ruby
I f you ar e using Ruby for t est aut om at ion t hen you pr obably ar e alr eady fam iliar wit h developing in Ruby. To add Selenium t o your Ruby envir onm ent r un t he following com m and fr om a com m and- line.
gem install selenium-webdriver
Teaching Ruby developm ent it self is beyond t he scope of t his docum ent , however t her e ar e m any r esour ces on Ruby and likely developer s in your or ganizat ion can help you get up t o speed. 3 de 18
Perl
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
Perl
Per l bindings ar e pr ovided by a t hir d par t y, please r efer t o any of t heir docum ent at ion on how t o inst all / get st ar t ed. Ther e is one known Per l binding as of t his wr it ing.
PHP
PHP bindings ar e pr ovided by a t hir d par t y, please r efer t o any of t heir docum ent at ion on how t o inst all / get st ar t ed. Ther e ar e t hr ee known bindings at t his t im e: By Chibim agic By Lukasz Kolczynski and By the Facebook
selenium import webdriver selenium.common.exceptions import TimeoutException selenium.webdriver.support.ui import WebDriverWait # available since selenium.webdriver.support import expected_conditions as EC
# Create a new instance of the Firefox driver driver = webdriver.Firefox() # go to the google home page driver.get("http://www.google.com")
4 de 18
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
# go to the google home page driver.get("http://www.google.com") # find the element that's name attribute is q (the google search box) inputElement = driver.find_element_by_name("q") # type in the search inputElement.send_keys("Cheese!")
# submit the form (although google automatically searches now without subm inputElement.submit() # the page is ajaxy so the title is originally this: print driver.title try:
# we have to wait for the page to refresh, the last thing that seems t WebDriverWait(driver, 10).until(EC.title_contains("cheese!")) # You should see "cheese! - Google Search" print driver.title finally: driver.quit()
I n upcom ing sect ions, you will lear n m or e about how t o use WebDr iver for t hings such as navigat ing for war d and backwar d in your br owser s hist or y, and how t o t est web sit es t hat use fram es and windows. We also pr ovide a m or e t hor ough discussions and exam ples.
driver.get("http://www.google.com")
Dependent on several fact or s, including t he OS/ Br owser com binat ion, WebDr iver m ay or m ay not wait for t he page t o load. I n som e cir cum st ances, WebDr iver m ay r et ur n cont r ol befor e t he page has finished, or even st ar t ed, loading. To ensur e r obust ness, you need t o wait for t he elem ent ( s) t o exist in t he page using Explicit and Implicit Waits.
5 de 18
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
The Find m et hods t ake a locat or or quer y obj ect called By . By st rat egies ar e list ed below. By ID This is t he m ost efficient and pr efer r ed way t o locat e an elem ent . Com m on pit falls t hat UI developer s m ake is having non- unique id s on a page or aut o- generat ing t he id, bot h should be avoided. A class on an ht m l elem ent is m or e appr opr iat e t han an aut o- generat ed id. Exam ple of how t o find an elem ent t hat looks like t his:
<div id="coolestWidgetEvah">...</div>
By Class Name Class in t his case r efer s t o t he at t r ibut e on t he DOM elem ent . Oft en in pract ical use t her e ar e m any DOM elem ent s wit h t he sam e class nam e, t hus finding m ult iple elem ent s becom es t he m or e pract ical opt ion over finding t he fir st elem ent . Exam ple of how t o find an elem ent t hat looks like t his:
<div class="cheese"><span>Cheddar</span></div><div class="cheese"
By Tag Name The DOM Tag Nam e of t he elem ent . Exam ple of how t o find an elem ent t hat looks like t his:
<iframe src="..."></iframe>
6 de 18
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
By Name Find t he input elem ent wit h m at ching nam e at t r ibut e. Exam ple of how t o find an elem ent t hat looks like t his:
<input name="cheese" type="text"/>
By Link Text Find t he link elem ent wit h m at ching visible t ext . Exam ple of how t o find an elem ent t hat looks like t his:
<a href="http://www.google.com/search?q=cheese">cheese</a>>
By Partial Link Text Find t he link elem ent wit h par t ial m at ching visible t ext . Exam ple of how t o find an elem ent t hat looks like t his:
<a href="http://www.google.com/search?q=cheese">search for cheese
By CSS Like t he nam e im plies it is a locat or st rat egy by css. Nat ive br owser suppor t is used by default , so please r efer t o w3c css selectors <http://www.w3.org/TR/CSS/#selectors> for a list of generally available css select or s. I f a br owser does not have nat ive suppor t for css quer ies, t hen Sizzle is used. I E 6,7 and FF3.0 cur r ent ly use Sizzle as t he css quer y engine. 28/05/2013 7:37
7 de 18
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp generally available css select or s. I f a br owser does not have nat ive suppor t for css quer ies, t hen Sizzle is used. I E 6,7 and FF3.0 cur r ent ly use Sizzle as t he css quer y engine. Bewar e t hat not all br owser s wer e cr eat ed equal, som e css t hat m ight wor k in one ver sion m ay not wor k in anot her. Exam ple of t o find t he cheese below:
<div id="food"><span class="dairy">milk</span><span class="dairy aged"
cheese = driver.find_element_by_css_selector("#food span.dairy.aged" or from selenium.webdriver.common.by import By cheese = driver.find_element(By.CSS_SELECTOR, "#food span.dairy.aged"
By XPATH At a high level, WebDr iver uses a br owser s nat ive XPat h capabilit ies wher ever possible. On t hose br owser s t hat don t have nat ive XPat h suppor t , we have pr ovided our own im plem ent at ion. This can lead t o som e unexpect ed behaviour unless you ar e awar e of t he differ ences in t he var ious xpat h engines. Tag and Attribute Name Lower-cased Native XPath Support Yes No Yes
Attribute Values As they appear in t he HTML As they appear in t he HTML As they appear in t he HTML
I nt er net Explor er Lower-cased Dr iver Fir efox Dr iver Case insensit ive
The following num ber of m at ches will be found XPath HtmlUnit expression Driver / / input //INPUT 8 de 18 1 ( exam ple ) 0 Firefox Driver 2 2 Internet Explorer Driver 2 0
Som et im es HTML elem ent s do not need at t r ibut es t o be explicit ly 28/05/2013 7:37
Selenium WebDriver
http://docs.seleniumhq.org/docs/03_webdriver.jsp 2 0
Som et im es HTML elem ent s do not need at t r ibut es t o be explicit ly declar ed because t hey will default t o known values. For exam ple, t he input t ag does not r equir e t he t ype at t r ibut e because it default s t o t ext . The r ule of t hum b when using xpat h in WebDr iver is t hat you should not expect t o be able t o m at ch against t hese im plicit at t r ibut es. Using JavaScript You can execut e ar bit rar y j avascr ipt t o find an elem ent and as long as you r et ur n a DOM Elem ent , it will be aut om at ically conver t ed t o a WebElem ent obj ect . Sim ple exam ple on a page t hat has j Quer y loaded:
labels = driver.find_elements_by_tag_name("label") inputs = driver.execute_script( "var labels = arguments[0], inputs = []; for (var i=0; i < labels.l "inputs.push(document.getElementById(labels[i].getAttribute('for'))
select = driver.find_element_by_tag_name("select") allOptions = select.find_elements_by_tag_name("option") for option in allOptions: print "Value is: " + option.get_attribute("value") option.click()
This will find t he fir st SELECT elem ent on t he page, and cycle t hr ough each of it s OPTI ONs in t ur n, pr int ing out t heir values, and select ing each in t ur n. As you will not ice, t his isn t t he m ost efficient way of dealing wit h SELECT elem ent s. WebDr iver s suppor t classes include one called Select , which pr ovides useful m et hods for int eract ing wit h t hese.
# available since 2.12 from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_tag_name("select")) select.deselect_all() select.select_by_visible_text("Edam")
9 de 18
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
select.deselect_all() select.select_by_visible_text("Edam")
This will deselect all OPTI ONs fr om t he fir st SELECT on t he page, and t hen select t he OPTI ON wit h t he displayed t ext of Edam . Once you ve finished filling out t he for m , you pr obably want t o subm it it . One way t o do t his would be t o find t he subm it but t on and click it :
driver.find_element_by_id("submit").click()
Alt er nat ively, WebDr iver has t he convenience m et hod subm it on ever y elem ent . I f you call t his on an elem ent wit hin a for m , WebDr iver will walk up t he DOM unt il it finds t he enclosing for m and t hen calls subm it on t hat . I f t he elem ent isn t in a for m , t hen t he NoSuchElementException will be t hr own:
element.submit()
driver.switch_to_window("windowName")
All calls t o driver will now be int er pr et ed as being dir ect ed t o t he par t icular window. But how do you know t he window s nam e? Take a look at t he j avascr ipt or link t hat opened it :
Alt er nat ively, you can pass a window handle t o t he swit chTo( ) .window( ) m et hod. Knowing t his, it s possible t o it er at e over ever y open window like so:
driver.switch_to_frame("frameName")
10 de 18
I t s possible t o access subfram es by separat ing t he pat h wit h a dot , and you can specify t he fram e by it s index t oo. That is: 28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
I t s possible t o access subfram es by separat ing t he pat h wit h a dot , and you can specify t he fram e by it s index t oo. That is:
driver.switch_to_frame("frameName.0.child")
would go t o t he fram e nam ed child of t he fir st subfram e of t he fram e called fram eNam e . All frames are evaluated as if from *top*.
Popup Dialogs
St ar t ing wit h Selenium 2.0 bet a 1, t her e is built in suppor t for handling popup dialog boxes. Aft er you ve t r igger ed an act ion t hat opens a popup, you can access t he aler t wit h t he following:
This will r et ur n t he cur r ent ly open aler t obj ect . Wit h t his obj ect you can now accept , dism iss, r ead it s cont ent s or even t ype int o a pr om pt . This int er face wor ks equally well on aler t s, confir m s, and prompts. Refer to the JavaDocs or RubyDocs for m or e infor m at ion.
driver.get("http://www.example.com")
To r eit erat e: navigate().to() and get() do exact ly t he sam e t hing. One s j ust a lot easier t o t ype t han t he ot her ! The navigat e int er face also exposes t he abilit y t o m ove backwar ds and for war ds in your br owser s hist or y:
driver.forward() driver.back()
Please be awar e t hat t his funct ionalit y depends ent ir ely on t he under lying br owser. I t s j ust possible t hat som et hing unexpect ed m ay happen when you call t hese m et hods if you r e used t o t he behaviour of one br owser over anot her.
Cookies
11 de 18 Befor e we leave t hese next st eps, you m ay be int er est ed in 7:37 under st anding how t o use cookies. Fir st of all, you need t o be on t28/05/2013 he
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
Cookies
Befor e we leave t hese next st eps, you m ay be int er est ed in under st anding how t o use cookies. Fir st of all, you need t o be on t he dom ain t hat t he cookie will be valid for. I f you ar e t r ying t o pr eset cookies befor e you st ar t int eract ing wit h a sit e and your hom epage is lar ge / t akes a while t o load an alt er nat ive is t o find a sm aller page on t he sit e, t ypically t he 404 page is sm all ( ht t p: / / exam ple.com / som e404page)
# Go to the correct domain driver.get("http://www.example.com") # Now set the cookie. Here's one for the entire domain # the cookie name here is 'key' and it's value is 'value' driver.add_cookie({'name':'key', 'value':'value', 'path':'/'}) # additional keys that can be passed in are: # 'domain' -> String, # 'secure' -> Boolean, # 'expiry' -> Milliseconds since the Epoch it should expire. # And now output all the available cookies for the current URL for cookie in driver.get_cookies(): print "%s -> %s" % (cookie['name'], cookie['value']) # You can delete cookies in 2 ways # By name driver.delete_cookie("CookieName") # Or all of them driver.delete_all_cookies()
from selenium.webdriver.common.action_chains import ActionChains element = driver.find_element_by_name("source") target = driver.find_element_by_name("target") ActionChains(driver).drag_and_drop(element, target).perform()
HtmlUnit Driver
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp WebDr iver is t he nam e of t he key int er face against which t est s should be wr it t en, but t her e ar e several im plem ent at ions. These include:
HtmlUnit Driver
This is cur r ent ly t he fast est and m ost light weight im plem ent at ion of WebDr iver. As t he nam e suggest s, t his is based on Ht m lUnit . Ht m lUnit is a j ava based im plem ent at ion of a WebBr owser wit hout a GUI . For any language binding ( ot her t han j ava) t he Selenium Ser ver is r equir ed t o use t his dr iver. Usage
Pros Fast est im plem ent at ion of WebDr iver A pur e Java solut ion and so it is plat for m independent . Suppor t s JavaScr ipt Cons Em ulat es ot her br owser s JavaScr ipt behaviour ( see below) JavaScript in the HtmlUnit Driver None of t he popular br owser s uses t he JavaScr ipt engine used by Ht m lUnit ( Rhino) . I f you t est JavaScr ipt using Ht m lUnit t he r esult s m ay differ significant ly fr om t hose br owser s. When we say JavaScr ipt we act ually m ean JavaScr ipt and t he DOM . Alt hough t he DOM is defined by t he W3C each br owser has it s own quir ks and differ ences in t heir im plem ent at ion of t he DOM and in how JavaScr ipt int eract s wit h it . Ht m lUnit has an im pr essively com plet e im plem ent at ion of t he DOM and has good suppor t for using JavaScr ipt , but it is no differ ent fr om any ot her br owser : it has it s own quir ks and differ ences fr om bot h t he W3C st andar d and t he DOM im plem ent at ions of t he m aj or br owser s, despit e it s abilit y t o m im ic ot her br owser s. Wit h WebDr iver, we had t o m ake a choice; do we enable Ht m lUnit s JavaScr ipt capabilit ies and r un t he r isk of t eam s r unning int o pr oblem s t hat only m anifest t hem selves t her e, or do we leave JavaScr ipt disabled, knowing t hat t her e ar e m or e and m or e sit es t hat r ely on JavaScr ipt ? We t ook t he conser vat ive appr oach, and by default have disabled suppor t when we use Ht m lUnit . Wit h each r elease of bot h WebDr iver and Ht m lUnit , we r eassess t his decision: we hope t o enable JavaScr ipt by default on t he Ht m lUnit at som e point . Enabling JavaScript I f you can t wait , enabling JavaScr ipt suppor t is ver y easy:
13 de 18
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
This will cause t he Ht m lUnit Dr iver t o em ulat e Fir efox 3.6 s JavaScr ipt handling by default .
Firefox Driver
Cont r ols t he Fir efox br owser using a Fir efox plugin. The Fir efox Pr ofile t hat is used is st r ipped down fr om what is inst alled on t he m achine t o only include t he Selenium WebDr iver.xpi ( plugin) . A few set t ings ar e also changed by default ( see t he sour ce t o see which ones) Fir efox Dr iver is capable of being r un and is t est ed on Windows, Mac, Linux. Cur r ent ly on ver sions 3.6, 10, lat est - 1, lat est Usage
driver = webdriver.Firefox()
Pros Runs in a r eal br owser and suppor t s JavaScr ipt Faster than the I nt er net Explor er Dr iver Cons Slower t han t he Ht m lUnit Dr iver Modifying the Firefox Profile Suppose t hat you want ed t o m odify t he user agent st r ing ( as above) , but you ve got a t r icked out Fir efox pr ofile t hat cont ains dozens of useful ext ensions. Ther e ar e t wo ways t o obt ain t his pr ofile. Assum ing t hat t he pr ofile has been cr eat ed using Fir efox s pr ofile m anager ( firefox -ProfileManager):
Alt er nat ively, if t he pr ofile isn t alr eady r egist er ed wit h Fir efox:
As we develop feat ur es in t he Fir efox Dr iver, we expose t he abilit y t o use t hem . For exam ple, unt il we feel nat ive event s ar e st able on Fir efox for Linux, t hey ar e disabled by default . To enable t hem :
Info See the Fir efox sect ion in t he wiki page for the most up to date info. 14 de 18 28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
See the Fir efox sect ion in t he wiki page for the most up to date info.
driver = webdriver.Ie()
Pros Runs in a r eal br owser and suppor t s JavaScr ipt wit h all t he quir ks your end user s see. Cons Obviously t he I nt er net Explor er Dr iver will only wor k on Windows! Com parat ively slow ( t hough st ill pr et t y snappy : ) XPat h is not nat ively suppor t ed in m ost ver sions. Sizzle is inj ect ed aut om at ically which is significant ly slower t han ot her br owser s and slower when com par ing t o CSS select or s in t he sam e br owser. CSS is not nat ively suppor t ed in ver sions 6 and 7. Sizzle is inj ect ed inst ead. CSS select or s in I E 8 and 9 ar e nat ive, but t hose br owser s don t fully suppor t CSS3 Info See the I nt er net Explor er sect ion of t he wiki page for the most up t o dat e info. Please t ake special not e of t he Requir ed Configurat ion sect ion.
Chrome Driver
Chr om e Dr iver is m aint ained / suppor t ed by t he Chr om ium project it eslf. WebDr iver wor ks wit h Chr om e t hr ough t he chr om edr iver binar y ( found on t he chr om ium pr oj ect s download page) . You need t o have bot h chr om edr iver and a ver sion of chr om e br owser inst alled. chr om edr iver needs t o be placed som ewher e on your syst em s pat h in or der for WebDr iver t o aut om at ically discover it . The Chr om e br owser it self is discover ed by chr om edr iver in t he default inst allat ion pat h. These bot h can be over r idden by envir onm ent var iables. Please r efer t o t he wiki for more infor m at ion. Usage
driver = webdriver.Chrome()
15 de 18
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
driver = webdriver.Chrome()
http://docs.seleniumhq.org/docs/03_webdriver.jsp
Pros Runs in a r eal br owser and suppor t s JavaScr ipt Because Chr om e is a Webkit - based br owser, t he Chrome Dr iver m ay allow you t o ver ify t hat your sit e wor ks in Safar i. Not e t hat since Chr om e uses it s own V8 JavaScr ipt engine rat her t han Safar i s Nit r o engine, JavaScr ipt execut ion m ay differ. Cons Slower t han t he Ht m lUnit Dr iver Info See our wiki for t he m ost up t o dat e info. Mor e info can also be found on the downloads page Getting running with Chrome Driver Download t he Chr om e Dr iver execut able and follow t he ot her inst r uct ions on t he wiki page
Opera Driver
See the Opera Dr iver wiki ar t icle in t he Selenium Wiki for infor m at ion on using t he Opera Dr iver.
iPhone Driver
See the iPhone Dr iver wiki ar t icle in t he Selenium Wiki for infor m at ion on using t he Mac iOS Dr iver.
Android Driver
See the Andr oid Dr iver wiki ar t icle in t he Selenium Wiki for infor m at ion on using t he Andr oid Dr iver.
Pros Allows for t he WebDr iver and Selenium API s t o live side- by- side
16 de 18
28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp
Allows for t he WebDr iver and Selenium API s t o live side- by- side Pr ovides a sim ple m echanism for a m anaged m igrat ion fr om t he Selenium RC API t o WebDr iver s Does not r equir e t he st andalone Selenium RC ser ver t o be run Cons Does not im plem ent ever y m et hod Mor e advanced Selenium usage ( using br owser bot or ot her built- in JavaScr ipt m et hods fr om Selenium Cor e) m ay not work Som e m et hods m ay be slower due t o under lying im plem ent at ion differ ences
Ther e ar e cur r ent ly som e m aj or lim it at ions wit h t his appr oach, not ably t hat findElem ent s doesn t wor k as expect ed. Also, because we r e using Selenium Cor e for t he heavy lift ing of dr iving t he br owser, you ar e lim it ed by t he JavaScr ipt sandbox.
I f you want t o use nat ive event s funct ionalit y, indicat e t his on t he com m and line wit h t he opt ion
-Dwebdriver.enable.native.events=1
17 de 18
I n or der t o funct ion pr oper ly, t he following por t s should be allowed incom ing TCP connect ions: 4444, 7054- 5 ( or t wice as m any por t s as t he num ber of concur r ent inst ances you plan t o r un) . Under Windows, 28/05/2013 7:37
Selenium WebDriver
Selenium Documentation
http://docs.seleniumhq.org/docs/03_webdriver.jsp I n or der t o funct ion pr oper ly, t he following por t s should be allowed incom ing TCP connect ions: 4444, 7054- 5 ( or t wice as m any por t s as t he num ber of concur r ent inst ances you plan t o r un) . Under Windows, you m ay need t o unblock t he applicat ions as well.
Additional Resources
You can find fur t her r esour ces for WebDr iver in WebDr iver s wiki Of cour se, don t hesit at e t o do an int er net sear ch on any Selenium t opic, including Selenium -WebDr iver s dr iver s. Ther e ar e quit e a few blogs on Selenium along wit h num er ous post s on var ious user for um s. Addit ionally t he Selenium User s Gr oup is a gr eat r esour ce. ht t p: / / gr oups.google.com / gr oup/ selenium - user s
Next Steps
This chapt er has sim ply been a high level walkt hr ough of WebDr iver and som e of it s key capabilit ies. Once get t ing fam iliar wit h t he Selenium -WebDr iver API you will t hen want t o lear n how t o build t est suit es for m aint ainabilit y, ext ensibilit y, and r educed fr agilit y when feat ur es of t he AUT fr equent ly change. The appr oach m ost Selenium exper t s ar e now r ecom m ending is t o design your t est code using t he Page Obj ect Design Pat t er n along wit h possibly a Page Fact or y. Selenium -WebDr iver pr ovides suppor t for t his by supplying a PageFact or y class in Java and C# . This is pr esent ed,along wit h ot her advanced t opics, in t he next chapter. Also, for high- level descr ipt ion of t his t echnique, you m ay want t o look at t he Test Design Considerations chapter. Bot h of t hese chapt er s pr esent t echniques for wr it ing m or e m aint ainable t est s by m aking your t est code m or e m odular.
18 de 18
28/05/2013 7:37
Selenium Documentation
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
Explicit Waits
An ex plicit wait s is code you defin e t o wait for a cer t ain condit ion t o occu r befor e pr oceeding fur t her in t he code. The wor st case of t his is Thr ead.sleep( ) , which set s t he condit ion t o an ex act t im e per iod t o wait . Ther e ar e som e convenience m et hods pr ov ided t h at help you wr it e code t hat will wait only as long as r equir ed. WebDr iver Wait in com binat ion wit h Ex pect edCondit ion is on e way t his can be accom plished.
selenium import webdriver selenium.webdriver.common.by import By selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 selenium.webdriver.support import expected_conditions as EC # available since 2.2
This wait s up t o 10 seconds befor e t hr owin g a Tim eout Except ion or if it finds t he elem ent will r et ur n it in 0 - 10 secon ds. WebDr iver Wait by default calls t he Ex pect edCondit ion ever y 5 00 m illiseconds unt il it r et ur ns su ccessfully. A successful r et ur n is for Ex pect edCon dit ion t y pe is Boolean r et ur n t r ue or not null r et ur n value for all ot her Ex pect edCondit ion t y pes. This ex am ple is also funct ionally equ ivalent t o t he fir st I m plicit Wait s ex am ple. Expected Conditions Ther e ar e som e com m on condit ions t hat ar e fr equent ly com e acr oss when aut om at ing web br owser s. List ed below ar e I m plem ent at ions of each. Java happens t o have conv ienence m et hods so you don t have t o code an Ex pect edCondit ion class your self or cr eat e your own ut ilit y pack age for t hem . Elem ent is Click able - it is Displayed and En abled.
The Ex pect edCondit ions pack age ( Java) (Python) (.NET) cont ains a set of pr edefin ed condit ions t o u se wit h WebDr iver Wait .
Implicit Waits
An im plicit wait is t o t ell WebDr iver t o poll t he DOM for a cer t ain am ount of t im e wh en t r y ing t o find an elem ent or elem ent s if t hey ar e not im m ediat ely available. The default set t ing is 0. Once set , t h e im plicit wait is set for t he life of t he WebDr iver obj ect inst ance.
1 de 4
ff = webdriver.Firefox()
28/05/2013 7:37
Selenium Documentation
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
from selenium import webdriver ff = webdriver.Firefox() ff.implicitly_wait(10) # seconds ff.get("http://somedomain/url_that_delays_loading") myDynamicElement = ff.find_element_by_id("myDynamicElement")
RemoteWebDriver
Taking a Screenshot
Using a FirefoxProfile
from selenium import webdriver fp = webdriver.FirefoxProfile() # set something on the profile... driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities
Using ChromeOptions
from selenium import webdriver options = webdriver.ChromeOptions() # set some options driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
AdvancedUserInteractions
The Act ions class( es) allow you t o build a Chain of Act ions and per for m t hem . Th er e ar e t oo m any possible com binat ions t o count . Below ar e a few of t he com m on int er act ions t hat you m ay want t o use. For a full list of act ions please r efer t o t he API docs Java C# Ruby Python The Advanced User I n t eract ions r equir e nat ive event s t o be enabled. Her e s a t able of t he cur r ent suppor t Mat r ix for nat ive event s: Chrome Chrome Chrome platform IE6 IE7 IE8 IE9 FF3.6 FF10+ stable beta dev Opera Android Windows Y XP Y Y n/a Y Y Y Y Y Y Y Y Y n/a Y Y Y Y n/a Y Y Y Y n/a ? ? ? ? ? Y [1] Y [1] Y [1] Y [1] Y
Linux n/a n/a n/a n/a Y [2] Y [2] (Ubuntu) Mac OSX n/a n/a n/a n/a N Mobile Dev ice n/a n/a n/a n/a n/a N ?
[1] ( 1, 2, 3, 4) Using t he em ulat or [2] ( 1, 2) Wit h ex plicit ly enablin g nat ive even t s
28/05/2013 7:37
Selenium Documentation
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
Using a Proxy
Internet Explorer The easiest and r ecom m ended way is t o m anually set t he pr ox y on t he m achine t hat will be r unning t he t est . I f t hat is not possible or you want your t est t o r u n wit h a differ ent configur at ion or pr ox y, t hen you can use t he following t echniqu e t hat uses a Capababilit ies obj ect . This t em por ar ily chan ges t he sy st em s pr ox y set t ings and ch anges t hem back t o t he or iginal st at e when done.
from selenium import webdriver PROXY = "localhost:8080" webdriver.DesiredCapabilities.INTERNETEXPLORER['proxy'] = { "httpProxy":PROXY, "ftpProxy":PROXY, "sslProxy":PROXY, "noProxy":None, "proxyType":"MANUAL", "class":"org.openqa.selenium.Proxy", "autodetect":False }
# you have to use remote, otherwise you'll have to code it yourself in python to # dynamically changing the system proxy preferences driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilit
Chrome I s basically t he sam e as int er net ex plor er. I t uses t he sam e configur at ion on t he m achine as I E does ( on windows) . On Mac it uses t he Sy st em Pr efer ence - > Net wor k set t ings. On Linu x it uses ( on Ubunt u) Sy st em > Pr efer ences > Net wor k Pr ox y Pr efer ences ( Alt er nat ively in / et c/ env ir onm en t set ht t p_pr ox y ) . As of t his wr it ing it is unk nown how t o set t he pr ox y pr ogr am m at ically. Firefox Fir efox m aint ains it s pr ox y configurat ion in a pr ofile. You can pr eset t he pr ox y in a pr ofile and use t hat Fir efox Pr ofile or you can set it on pr ofile t hat is cr eat ed on t he fly as is sh own in t he following ex am ple.
from selenium import webdriver from selenium.webdriver.common.proxy import * myProxy = "host:8080" proxy = Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy': myProxy, 'ftpProxy': myProxy, 'sslProxy': myProxy, 'noProxy': '' # set this value as desired }) driver = webdriver.Firefox(proxy=proxy)
3 de 4
# for remote
28/05/2013 7:37
Selenium Documentation
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
Opera Todo
HTML5
Todo
Navigation
4 de 4
28/05/2013 7:37
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
RC Components
Selenium RC components are: The Selenium Ser ver which launches and kills br owser s, int er pr et s and r uns t he Selenese commands passed from the test program, and acts as an HTTP proxy, int er cept ing and ver ify ing HTTP m essages passed bet ween t he br owser and t he AUT. Client librar ies which pr ov ide t he int er face bet ween each pr ogr am m ing language and the Selenium RC Server. Her e is a sim plified ar chit ect ur e diagram ....
The diagram shows t he client librar ies com m unicat e wit h t he Ser ver passing each Selenium com m and for execut ion. Then t he ser ver passes t he Selenium com m and t o t he br owser using Selenium - Cor e JavaScr ipt com m ands. The br owser, using it s JavaScr ipt int er pr et er, execut es t he Selenium com m and. This r uns t he Selenese act ion or ver ificat ion you specified in your t est scr ipt .
Selenium Server
Selenium Ser ver r eceives Selenium com m ands fr om your t est pr ogram , int er pr et s t hem , and reports back to your program the results of running those tests. The RC ser ver bundles Selenium Cor e and aut om at ically inj ect s it int o t he br owser. This occur s when your t est pr ogram opens t he br owser ( using a client librar y API funct ion) . Selenium - Cor e is a JavaScr ipt pr ogram , act ually a set of JavaScr ipt funct ions which int er pr et s and execut es Selenese com m ands using t he br owser s built - in JavaScr ipt interpreter. The Ser ver r eceives t he Selenese com m ands fr om your t est pr ogram using sim ple HTTP GET/ POST r equest s. This m eans you can use any pr ogram m ing language t hat can send HTTP r equest s t o aut om at e Selenium t est s on t he br owser.
Client Libraries
The client librar ies pr ov ide t he pr ogram m ing suppor t t hat allows you t o r un Selenium com m ands fr om a pr ogram of your own design. Ther e is a differ ent client librar y for each suppor t ed language. A Selenium client librar y pr ov ides a pr ogram m ing int er face ( API ) , i.e., a set of funct ions, which r un Selenium com m ands fr om your own pr ogram . Wit hin each 28/05/2013
1 de 17
7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
The client librar ies pr ov ide t he pr ogram m ing suppor t t hat allows you t o r un Selenium com m ands fr om a pr ogram of your own design. Ther e is a differ ent client librar y for each suppor t ed language. A Selenium client librar y pr ov ides a pr ogram m ing int er face ( API ) , i.e., a set of funct ions, which r un Selenium com m ands fr om your own pr ogram . Wit hin each int er face, t her e is a pr ogram m ing funct ion t hat suppor t s each Selenese com m and. The client librar y t akes a Selenese com m and and passes it t o t he Selenium Ser ver for pr ocessing a specific act ion or t est against t he applicat ion under t est ( AUT) . The client librar y also r eceives t he r esult of t hat com m and and passes it back t o your pr ogram . Your pr ogram can r eceive t he r esult and st or e it int o a pr ogram var iable and r epor t it as a success or failur e, or possibly t ake cor r ect ive act ion if it was an unex pect ed er r or. So t o cr eat e a t est pr ogram , you sim ply wr it e a pr ogram t hat r uns a set of Selenium com m ands using a client librar y API . And, opt ionally, if you alr eady have a Selenese test scr ipt cr eat ed in t he Selenium -I DE, you can generate the Selenium RC code. The Selenium -I DE can t r anslat e ( using it s Ex por t m enu it em ) it s Selenium com m ands int o a client- dr iver s API funct ion calls. See t he Selenium - I DE chapt er for specifics on ex por t ing RC code from Selenium-IDE.
Installation
I nst allat ion is rat her a m isnom er for Selenium . Selenium has set of librar ies available in the pr ogram m ing language of your choice. You could download t hem fr om downloads page Once you ve chosen a language t o wor k wit h, you sim ply need t o: I nst all t he Selenium RC Ser ver. Set up a pr ogram m ing pr oj ect using a language specific client dr iver.
2 de 17
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
For det ails on Py t hon client dr iver configur at ion, see t he appendix Py t hon Client Dr iv er Configuration.
assertTextPresent Result s * for selenium r c Note: This example would work with the Google search page http://www.google.com
from selenium import selenium import unittest, time, re class NewTest(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://www.google.com/") self.selenium.start() def test_new(self): sel = self.selenium sel.open("/") sel.type("q", "selenium rc") sel.click("btnG") sel.wait_for_page_to_load("30000") self.failUnless(sel.is_text_present("Results * for selenium rc")) def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors)
3 de 17
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
I n t he nex t sect ion we ll ex plain how t o build a t est pr ogram using t he generat ed code.
Java
For Java, people use eit her JUnit or Test NG as t he t est engine. Som e developm ent env ir onm ent s like Eclipse have dir ect suppor t for t hese v ia plug- ins. This m akes it even easier. Teaching JUnit or Test NG is beyond t he scope of t his docum ent however m at er ials m ay be found online and t her e ar e publicat ions available. I f you ar e alr eady a j ava- shop chances ar e your developer s will alr eady have som e ex per ience wit h one of t hese t est frameworks. You will pr obably want t o r enam e t he t est class fr om NewTest t o som et hing of your own choosing. Also, you will need t o change t he br owser - open param et er s in t he st at em ent :
selenium = new DefaultSelenium("localhost", 4444, "*iehta", "http://www.google.com/")
The Selenium-I DE generat ed code will look like t his. This example has com ment s added manually for addit ional clar it y.
C#
The .NET Client Dr iver wor k s wit h Micr osoft .NET. I t can be used wit h any .NET t est ing fram ewor k like NUnit or t he Visual St udio 2005 Team Sy st em . Selenium -I DE assum es you will use NUnit as your t est ing fram ewor k. You can see t his in t he generat ed code below. I t includes t he using st at em ent for NUnit along wit h cor r esponding NUnit at t r ibut es ident ify ing t he r ole for each m em ber funct ion of t he t est class. You will pr obably have t o r enam e t he t est class fr om NewTest t o som et hing of your own choosing. Also, you will need t o change t he br owser - open param et er s in t he st at em ent :
selenium = new DefaultSelenium("localhost", 4444, "*iehta", "http://www.google.com/")
You can allow NUnit t o manage t he execut ion of your t est s. Or alt er nat ively, you can wr it e a simple m ain( ) pr ogram t hat inst ant iat es t he t est obj ect and r uns each of t he t hr ee met hods, Set upTest ( ) , TheNewTest ( ) , and Tear downTest ( ) in t ur n.
Python
Pyunit is t he t est framewor k t o use for Pyt hon. To lear n Pyunit r efer t o it s official documentation <ht t p: / / docs.py t hon.or g/ librar y / unit t est .ht m l>_. The basic t est st r uct ur e is:
from selenium import selenium # This is the driver's import. You'll use this class for instantiating a # browser and making it do what you need. import unittest, time, re # This are the basic imports added by Selenium-IDE by default. # You can remove the modules if they are not used in your script.
4 de 17
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
import unittest, time, re # This are the basic imports added by Selenium-IDE by default. # You can remove the modules if they are not used in your script. class NewTest(unittest.TestCase): # We create our unittest test case def setUp(self): self.verificationErrors = [] # This is an empty array where we will store any verification errors # we find in our tests self.selenium = selenium("localhost", 4444, "*firefox", "http://www.google.com/") self.selenium.start() # We instantiate and start the browser def test_new(self): # This is the test code. Here you should put the actions you need # the browser to do during your test. sel = self.selenium # We assign the browser to the variable "sel" (just to save us from # typing "self.selenium" each time we want to call the browser). sel.open("/") sel.type("q", "selenium rc") sel.click("btnG") sel.wait_for_page_to_load("30000") self.failUnless(sel.is_text_present("Results * for selenium rc")) # These are the real test steps def tearDown(self): self.selenium.stop() # we close the browser (I'd recommend you to comment this line while # you are creating and debugging your tests) self.assertEqual([], self.verificationErrors) # And make the test fail if we found that any verification errors # were found
Ruby
Selenium -I DE generat es r easonable Ruby, but r equir es t he old Selenium gem . This is a pr oblem because t he official Ruby dr iver for Selenium is t he Selenium - Client gem , not the old Selenium gem . I n fact , t he Selenium gem is no longer even under act ive developm ent. Ther efor e, it is adv isable t o updat e any Ruby scr ipt s generat ed by t he I DE as follows: 1. On line 1, change require "selenium" to require "selenium/client" 2. On line 11, change Selenium::SeleniumDriver.new to Selenium::Client::Driver.new You pr obably also want t o change t he class nam e t o som et hing m or e infor m at ive t han Unt it led, and change t he t est m et hod s nam e t o som et hing ot her t han t est _unt it led. Her e is a sim ple ex am ple cr eat ed by m odify ing t he Ruby code generat ed by Selenium I DE, as descr ibed above.
Perl, PHP
The m em ber s of t he docum ent at ion t eam have not used Selenium RC wit h Per l or PHP . If you ar e using Selenium RC wit h eit her of t hese t wo languages please cont act t he Docum ent at ion Team ( see t he chapt er on cont r ibut ing) . We would love t o include som e ex am ples fr om you and your ex per iences, t o suppor t Per l and PHP user s.
Each of t hese ex am ples opens t he br owser and r epr esent s t hat br owser by assigning a br owser inst ance t o a pr ogram var iable. This pr ogram var iable is t hen used t o call m et hods fr om t he br owser. These m et hods execut e t he Selenium com m ands, i.e. like open or type or t he verify commands.
5 de 17
28/05/2013 7:25
Selenium Documentation
br owser inst ance t o a pr ogram var iable. This pr ogram var iable is t hen used t o call m et hods fr om t he br owser. These m et hods execut e t he Selenium com m ands, i.e. like open or type or t he verify commands. The parameters required when creating the browser instance are: host Specifies t he I P addr ess of t he com put er wher e t he ser ver is locat ed. Usually, t his is the sam e m achine as wher e t he client is r unning, so in t his case localhost is passed. I n som e client s t his is an opt ional param et er. port Specifies t he TCP/ I P socket wher e t he ser ver is list ening wait ing for t he client t o est ablish a connect ion. This also is opt ional in som e client dr iver s. browser The br owser in which you want t o r un t he t est s. This is a r equir ed param et er. url The base ur l of t he applicat ion under t est . This is r equir ed by all t he client libs and is int egral infor m at ion for st ar t ing up t he br owser - pr ox y-AUT com m unicat ion. Not e t hat som e of t he client librar ies r equir e t he br owser t o be st ar t ed ex plicit ly by calling its start() method.
Running Commands
Once you have t he br owser init ialized and assigned t o a var iable ( generally nam ed selenium ) you can m ake it r un Selenese com m ands by calling t he r espect ive m et hods fr om t he br owser var iable. For ex am ple, t o call t he type method of the selenium object: selenium .t ype( field- id , st r ing t o t y pe ) I n t he back gr ound t he br owser will act ually per for m a type operat ion, essent ially ident ical t o a user t y ping input int o t he br owser, by using t he locat or and t he st r ing you specified dur ing t he m et hod call.
Reporting Results
Selenium RC does not have it s own m echanism for r epor t ing r esult s. Rat her, it allows you to build your r epor t ing cust om ized t o your needs using feat ur es of your chosen pr ogram m ing language. That s gr eat , but what if you sim ply want som et hing quick t hat s alr eady done for you? Oft en an ex ist ing librar y or t est fram ewor k can m eet your needs fast er t han developing your own t est r epor t ing code.
6 de 17
7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
which list det ails of t est s. See Test NG Repor t for more. Repor t NG is a HTML r epor t ing plug- in for t he Test NG fram ewor k . I t is int ended as a r eplacem ent for t he default Test NG HTML r epor t . Repor t NG pr ov ides a sim ple, colour-coded view of the test results. See ReportNG for more. Also, for a ver y nice sum m ar y r epor t t r y using Test NG-x slt . A Test NG-x slt Repor t look s like t his.
See TestNG-xslt for more. Logging the Selenese Commands Logging Selenium can be used t o generat e a r epor t of all t he Selenese com m ands in your t est along wit h t he success or failur e of each. Logging Selenium ex t ends t he Java client dr iver t o add t his Selenese logging abilit y. Please r efer t o Logging Selenium . Test Reports for Python When using Py t hon Client Dr iver t hen HTMLTest Runner can be used t o generat e a Test Report. See HTMLTestRunner. Test Reports for Ruby I f RSpec fr am ewor k is used for wr it ing Selenium Test Cases in Ruby t hen it s HTML report can be used to generate a test report. Refer to RSpec Report for more. Note I f you ar e int er est ed in a language independent log of what s going on, t ake a look at Selenium Ser ver Logging
Iteration
I t erat ion is one of t he m ost com m on t hings people need t o do in t heir t est s. For ex am ple, you m ay want t o t o execut e a sear ch m ult iple t im es. Or, per haps for ver ifying your t est r esult s you need t o pr ocess a r esult set r et ur ned fr om a dat abase. Using the same Google search example we used ear lier, let s check t he Selenium sear ch r esult s. This t est could use t he Selenese: open type click AndWait type click AndWait type / q btnG q btnG q selenium selenium ide selenium rc
7 de 17
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
assertTextPresent Result s * for selenium gr id The code has been r epeat ed t o r un t he sam e st eps 3 t im es. But m ult iple copies of t he same code is not good pr ogr am pract ice because it s m or e wor k t o m aint ain. By using a pr ogram m ing language, we can it erat e over t he sear ch r esult s for a m or e flex ible and m aint ainable solut ion. In C#:
// Collection of String values. String[] arr = {"ide", "rc", "grid"}; // Execute loop for each String in array 'arr'. foreach (String s in arr) { sel.open("/"); sel.type("q", "selenium " +s); sel.click("btnG"); sel.waitForPageToLoad("30000"); assertTrue("Expected text: " +s+ " is missing on page." , sel.isTextPresent("Results * for selenium " + s)); }
Condition Statements
To illust rat e using condit ions in t est s we ll st ar t wit h an ex am ple. A com m on pr oblem encount er ed while r unning Selenium t est s occur s when an ex pect ed elem ent is not available on page. For ex am ple, when r unning t he following line:
This can cause your t est t o abor t . For som e t est s t hat s what you want . But oft en t hat is not desirable as your t est scr ipt has m any ot her subsequent t est s t o per for m . A bet t er appr oach is t o fir st validat e whet her t he elem ent is r eally pr esent and t hen take alt er nat ives when it it is not . Let s look at t his using Java.
The advant age of t his appr oach is t o cont inue wit h t est execut ion even if som e UI elements ar e not available on page.
Rem em ber t o use window obj ect in case of DOM ex pr essions as by default selenium window is referred to, not the test window.
Server Options
When t he ser ver is launched, com m and line opt ions can be used t o change t he default server behaviour. Recall, t he ser ver is st ar t ed by r unning t he following.
$ java -jar selenium-server-standalone-<version-number>.jar
You ll see a list of all t he opt ions you can use wit h t he ser ver and a br ief descr ipt ion of each. The pr ov ided descr ipt ions will not alway s be enough, so we ve pr ov ided ex planat ions for som e of t he m or e im por t ant opt ions.
Proxy Configuration
I f your AUT is behind an HTTP pr ox y which r equir es aut hent icat ion t hen you should configur e ht t p.pr ox y Host , ht t p.pr ox y Por t , ht t p.pr ox yUser and ht t p.pr ox y Passwor d using the following com m and.
8 de 17
28/05/2013 7:25
Selenium Documentation
Proxy Configuration
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
I f your AUT is behind an HTTP pr ox y which r equir es aut hent icat ion t hen you should configur e ht t p.pr ox y Host , ht t p.pr ox y Por t , ht t p.pr ox yUser and ht t p.pr ox y Passwor d using the following com m and.
Multi-Window Mode
I f you ar e using Selenium 1.0 you can pr obably sk ip t his sect ion, since m ult iwindow m ode is t he default behav ior. However, pr ior t o ver sion 1.0, Selenium by default ran t he applicat ion under t est in a sub fr am e as shown her e.
Som e applicat ions didn t r un cor r ect ly in a sub fram e, and needed t o be loaded int o t he top fram e of t he window. The m ult i- window m ode opt ion allowed t he AUT t o r un in a separat e window rat her t han in t he default fram e wher e it could t hen have t he t op fram e it r equir ed.
9 de 17
For older ver sions of Selenium you m ust specify m ult iwindow m ode ex plicit ly wit h t he following opt ion:
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
For older ver sions of Selenium you m ust specify m ult iwindow m ode ex plicit ly wit h t he following opt ion:
-multiwindow
As of Selenium RC 1.0, if you want t o r un your t est wit hin a single fram e ( i.e. using the st andar d for ear lier Selenium ver sions) you can st at e t his t o t he Selenium Ser ver using the option
-singlewindow
Cr eat e t he new pr ofile using t he dialog. Then when you r un Selenium Ser ver, t ell it t o use t his new Fir efox pr ofile wit h t he ser ver com m and- line opt ion - fir efox Pr ofileTem plat e and specify t he pat h t o t he pr ofile using it s filenam e and dir ect or y pat h.
-firefoxProfileTemplate "path to the profile"
Warning Be sur e t o put your pr ofile in a new folder separat e fr om t he default ! ! ! The Fir efox pr ofile m anager t ool will delet e all files in a folder if you delet e a pr ofile, r egar dless of whether t hey ar e pr ofile files or not . Mor e infor m at ion about Fir efox pr ofiles can be found in Mozilla s Knowledge Base
This will aut om at ically launch your HTML suit e, r un all t he t est s and save a nice HTML report with the results. Note When using t his opt ion, t he ser ver will st ar t t he t est s and wait for a specified num ber of seconds for t he t est t o com plet e; if t he t est doesn t com plet e wit hin t hat am ount of time, t he com m and will ex it wit h a non-zer o ex it code and no r esult s file will be generat ed. This com m and line is ver y long so be car eful when you t y pe it . Not e t his r equir es you to pass in an HTML Selenese suit e, not a single t est . Also be awar e t he - ht m lSuit e opt ion is incom pat ible wit h -interactive You cannot r un bot h at t he sam e t im e.
This log file is m or e ver bose t han t he st andar d console logs ( it includes DEBUG level logging m essages) . The log file also includes t he logger nam e, and t he I D num ber of t he t hr ead t hat logged t he m essage. For ex am ple:
20:44:25 DEBUG [12] org.openqa.selenium.server.SeleniumDriverResourceHandler Browser 465828/:top frame1 posted START NEW
10 de 17
Browser-Side Logs
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
TIMESTAMP(HH:mm:ss) LEVEL [THREAD] LOGGER - MESSAGE
This m essage m ay be m ult iline. Browser-Side Logs JavaScr ipt on t he br owser side ( Selenium Cor e) also logs im por t ant m essages; in m any cases, t hese can be m or e useful t o t he end- user t han t he r egular Selenium Ser ver logs. To access br owser - side logs, pass t he -browserSideLog ar gum ent t o t he Selenium Server.
java -jar selenium-server-standalone-<version-number>.jar -browserSideLog
-browserSideLog m ust be com bined wit h t he -log ar gum ent , t o log br owser SideLogs ( as well as all ot her DEBUG level logging m essages) t o a file.
Selenium RC Architecture
Note This t opic t r ies t o ex plain t he t echnical im plem ent at ion behind Selenium RC. I t s not fundam ent al for a Selenium user t o k now t his, but could be useful for under st anding some of t he pr oblem s you m ight find in t he fut ur e. To under st and in det ail how Selenium RC Ser ver wor k s and why it uses pr ox y inj ect ion and height ened pr ivilege m odes you m ust fir st under st and t he sam e or igin policy.
Proxy Injection
The fir st m et hod Selenium used t o avoid t he The Sam e Or igin Policy was Proxy Injection. In Pr ox y I nj ect ion Mode, t he Selenium Ser ver act s as a client - configur ed [1] HTTP proxy [2], t hat sit s bet ween t he br owser and t he Applicat ion Under Test . I t t hen m ask s t he AUT under a fict ional URL ( em bedding Selenium - Cor e and t he set of t est s and deliver ing t hem as if t hey wer e com ing fr om t he sam e or igin) . [1] The pr oxy is a t hir d per son in t he m iddle t hat passes t he ball bet ween t he t wo par t s. It act s as a web ser ver t hat deliver s t he AUT t o t he br owser. Being a pr ox y gives Selenium Ser ver t he capabilit y of ly ing about t he AUT s r eal URL. [2] The br owser is launched wit h a configurat ion pr ofile t hat has set localhost : 4444 as t he HTTP pr ox y, t his is why any HTTP r equest t hat t he br owser does will pass t hr ough Selenium ser ver and t he r esponse will pass t hr ough it and not fr om t he r eal ser ver. Her e is an ar chit ect ural diagram .
11 de 17
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
As a t est suit e st ar t s in your favor it e language, t he following happens: 1. The client / dr iver est ablishes a connect ion wit h t he selenium - RC ser ver. 2. Selenium RC ser ver launches a br owser ( or r euses an old one) wit h a URL t hat inj ect s Selenium - Cor e s JavaScr ipt int o t he br owser - loaded web page. 3. The client - dr iver passes a Selenese com m and t o t he ser ver. 4. The Ser ver int er pr et s t he com m and and t hen t r igger s t he cor r esponding JavaScr ipt execut ion t o execut e t hat com m and wit hin t he br owser. Selenium - Cor e inst r uct s t he br owser t o act on t hat fir st inst r uct ion, t y pically opening a page of t he AUT. 5. The br owser r eceives t he open r equest and ask s for t he websit e s cont ent fr om t he Selenium RC server (set as the HTTP proxy for the browser to use). 6. Selenium RC ser ver com m unicat es wit h t he Web ser ver asking for t he page and once it r eceives it , it sends t he page t o t he br owser m ask ing t he or igin t o look like t he page com es fr om t he sam e ser ver as Selenium - Cor e ( t his allows Selenium - Cor e t o com ply wit h t he Sam e Or igin Policy ) . 7. The br owser r eceives t he web page and r ender s it in t he fram e/ window r eser ved for it .
12 de 17
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
As a t est suit e st ar t s in your favor it e language, t he following happens: 1. The client / dr iver est ablishes a connect ion wit h t he selenium - RC ser ver. 2. Selenium RC ser ver launches a br owser ( or r euses an old one) wit h a URL t hat will load Selenium - Cor e in t he web page. 3. Selenium - Cor e get s t he fir st inst r uct ion fr om t he client / dr iver ( v ia anot her HTTP request made to the Selenium RC Server). 4. Selenium - Cor e act s on t hat fir st inst r uct ion, t y pically opening a page of t he AUT. 5. The browser receives the open request and asks the Web Server for the page. Once t he br owser r eceives t he web page, r ender s it in t he fram e/ window r eser ved for it .
13 de 17
Anot her m et hod used wit h ear lier ver sions of Selenium was t o inst all t he Cy ber v illians
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
inst all it s own secur it y cer t ificat e, t em porar ily, t o your client m achine in a place where the br owser can access it . This t r icks t he br owser int o t hinking it s accessing a sit e different fr om your AUT and effect ively suppr esses t he popups. Anot her m et hod used wit h ear lier ver sions of Selenium was t o inst all t he Cy ber v illians secur it y cer t ificat e pr ov ided wit h your Selenium inst allat ion. Most user s should no longer need t o do t his however ; if you ar e r unning Selenium RC in pr ox y inj ect ion m ode, you may need t o ex plicit ly inst all t his secur it y cer t ificat e.
Not e t hat when launching t he br owser t his way, you m ust m anually configur e t he br owser t o use t he Selenium Ser ver as a pr ox y. Nor m ally t his j ust m eans opening your br owser pr efer ences and specify ing localhost : 4444 as an HTTP pr ox y, but inst r uct ions for t his can differ radically fr om br owser t o br owser. Consult your br owser s docum ent at ion for det ails. Be awar e t hat Mozilla br owser s can var y in how t hey st ar t and st op. One m ay need t o set t he MOZ_NO_REMOTE env ir onm ent var iable t o m ake Mozilla br owser s behave a lit t le m or e pr edict ably. Unix user s should avoid launching t he br owser using a shell scr ipt ; it s generally bet t er t o use t he binar y execut able ( e.g. fir efox- bin) dir ect ly.
I f you see a m essage like t his, be sur e you st ar t ed t he Selenium Ser ver. I f so, t hen there is a pr oblem wit h t he connect iv it y bet ween t he Selenium Client Librar y and t he Selenium Server. When st ar t ing wit h Selenium RC, m ost people begin by r unning t hier t est pr ogram ( wit h a Selenium Client Librar y ) and t he Selenium Ser ver on t he sam e m achine. To do t his use localhost as your connect ion param et er. We r ecom m end beginning t his way since it r educes t he influence of pot ent ial net wor k ing pr oblem s which you r e get t ing st ar t ed. Assum ing your oper at ing sy st em has t y pical net wor k ing and TCP/ I P set t ings you should have lit t le difficult y. I n t r ut h, m any people choose t o r un t he t est s t his way. I f, however, you do want t o r un Selenium Ser ver on a r em ot e m achine, t he connect iv it y should be fine assum ing you have valid TCP/ I P connect iv it y bet ween t he t wo m achines. I f you have difficult y connect ing, you can use com m on net wor k ing t ools like ping, telnet, ifconfig(Unix)/ipconfig ( Windows) , et c t o ensur e you have a valid net wor k connect ion. I f unfam ilar wit h t hese, your syst em adm inist rat or can assist you.
This could be caused by Fir efox ( pr ior t o Selenium 1.0) cannot st ar t because t he br owser is alr eady open and you did not specify a separat e pr ofile. See t he sect ion on Fir efox pr ofiles under Ser ver Options. The r un m ode you r e using doesn t m at ch any br owser on your m achine. Check t he 28/05/2013 param et er s you passed t o Selenium when you pr ogram opens t he br owser.
14 de 17
7:25
Selenium1 (SeleniumRC)
SeleniumDocum entation
you did not specify a separat e pr ofile. See t he sect ion on Fir efox pr ofiles under Ser ver Options. The r un m ode you r e using doesn t m at ch any br owser on your m achine. Check t he param et er s you passed t o Selenium when you pr ogram opens t he br owser. You specified t he pat h t o t he br owser ex plicit ly ( using * cust om see above) but t he pat h is incor r ect . Check t o be sur e t he pat h is cor r ect . Also check t he user gr oup t o be sur e t her e ar e no k nown issues wit h your br owser and t he * cust om param et er s.
To r esolve t his, see t he sect ion on Specify ing a Separat e Fir efox Pr ofile
Versioning Problems
Make sur e your ver sion of Selenium suppor t s t he ver sion of your br owser. For ex am ple, Selenium RC 0.92 does not suppor t Fir efox 3. At t im es you m ay be luck y ( I was) . But don t for get t o check which br owser ver sions ar e suppor t ed by t he ver sion of Selenium you are using. When in doubt , use t he lat est r elease ver sion of Selenium wit h t he m ost widely used version of your browser.
I f you see a lower ver sion num ber, you m ay need t o updat e t he JRE, or you m ay sim ply need t o add it t o your PATH env ir onm ent var iable.
15 de 17
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
on LAN Set t ings . I f you need t o use a pr ox y t o access t he applicat ion you want t o t est , you ll need t o st ar t Selenium Ser ver wit h - Dht t p.pr ox y Host ; see t he Proxy Configuration for m or e det ails. You m ay also t r y configur ing your pr ox y m anually and t hen launching t he br owser wit h * cust om , or wit h * ieht a br owser launcher. *custom: When using *custom you must configure the proxy correctly(manually), ot her wise you ll get a 404 er r or. Double- check t hat you ve configur ed your pr ox y set t ings cor r ect ly. To check whet her you ve configur ed t he pr ox y cor r ect ly is t o at t em pt t o int ent ionally configur e t he br owser incor r ect ly. Tr y configur ing t he br owser t o use t he wr ong pr ox y ser ver host nam e, or t he wr ong por t . I f you had successfully configur ed t he br owser s pr ox y set t ings incor r ect ly, t hen t he br owser will be unable t o connect t o t he I nt er net , which is one way t o m ake sur e t hat one is adj ust ing t he r elevant set t ings. For ot her br owser s ( * fir efox , * opera) we aut om at ically har d- code t he pr ox y for you, and so t her ar e no k nown issues wit h t his funct ionalit y. I f you r e encount er ing 404 er r or s and have followed t his user guide car efully post your r esult s t o user gr oup for som e help fr om t he user com m unit y.
16 de 17
Is it ok to load a custom pop-up as the parent page is loading (i.e., before the parent
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/05_selenium_rc.jsp
Check Fir efox pr ofile folder - > pr efs.j s - > user _pr ef( br owser.st ar t up.page , 0) ; Com ment t his line like t his: / / user _pr ef( br owser.st ar t up.page , 0) ; and t r y again.
Is it ok to load a custom pop-up as the parent page is loading (i.e., before the parent page s javascript window.onload() function runs)?
No. Selenium r elies on int er cept or s t o det er m ine window nam es as t hey ar e being loaded. These int er cept or s wor k best in cat ching new windows if t he windows ar e loaded AFTER the onload( ) funct ion. Selenium m ay not r ecognize windows loaded befor e t he onload funct ion.
Firefox on Linux
On Unix / Linux , ver sions of Selenium befor e 1.0 needed t o invoke fir efox- bin dir ect ly, so if you ar e using a pr ev ious ver sion, m ake sur e t hat t he r eal execut able is on t he pat h. On m ost Linux dist r ibut ions, t he r eal firefox-bin is locat ed on:
/usr/lib/firefox-x.x.x/
Wher e t he x .x .x is t he ver sion num ber you cur r ent ly have. So, t o add t hat pat h t o t he user s pat h. you will have t o add t he following t o your .bashr c file:
export PATH="$PATH:/usr/lib/firefox-x.x.x/"
I f necessar y, you can specify t he pat h t o fir efox- bin dir ect ly in your t est , like t his:
"*firefox /usr/lib/firefox-x.x.x/firefox-bin"
This would wor k per fect ly in Fir efox, Opera or Safar i but not wit h I E. I E int er pr et s the keys in @style as upper case. So, even if t he sour ce code is in lower case, you should use:
//td[@style="BACKGROUND-COLOR:yellow"]
This is a pr oblem if your t est is int ended t o wor k on m ult iple br owser s, but you can easily code your t est t o det ect t he sit uat ion and t r y t he alt er nat ive locat or t hat only wor ks in IE.
Error encountered - Cannot convert object to primitive value with shut down of *googlechrome browser
To avoid t his er r or you have t o st ar t br owser wit h an opt ion t hat disables sam e or igin policy checks:
selenium.start("commandLineFlags=--disable-web-security");
17 de 17
28/05/2013 7:25
Selenium Documentation
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
Types of Tests
What par t s of your applicat ion should you t est ? That depends on aspect s of your pr oj ect : user expect at ions, t im e allowed for t he pr oj ect , pr ior it ies set by t he pr oj ect m anager and so on. Once t he pr oj ect boundar ies ar e defined t hough, you, t he t est er, will cer t ainly m ake m any decisions on what t o t est . We ve cr eat ed a few t er m s her e for t he pur pose of cat egor izing t he t ypes of t est you m ay per for m on your web applicat ion. These t er m s ar e by no m eans st andar d, alt hough t he concept s we pr esent her e ar e t ypical for web- applicat ion t est ing.
Testing Links
A fr equent sour ce of er r or s for web- sit es is br oken links or m issing pages behind links. Test ing involves clicking each link and ver ifying t he expect ed page. I f st at ic links ar e infr equent ly changed t hen m anual t est ing m ay be sufficient . However if your web designer s fr equent ly alt er links, or if files ar e occasionally r elocat ed, link t est s should be aut om at ed.
Function Tests
These would be t est s of a specific funct ion wit hin your applicat ion, r equir ing som e t ype of user input , and r et ur ning som e t ype of r esult s. Oft en a funct ion t est will involve m ult iple pages wit h a for m - based input page cont aining a collect ion of input fields, Subm it 28/05/2013 7:35 and Cancel operat ions, and one or m or e r esponse pages. User input
1 de 10
Selenium Documentation
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
r esult s. Oft en a funct ion t est will involve m ult iple pages wit h a for m - based input page cont aining a collect ion of input fields, Subm it and Cancel operat ions, and one or m or e r esponse pages. User input can be via t ext- input fields, check boxes, dr op- down list s, or any ot her br owser - suppor t ed input . Funct ion t est s ar e oft en t he m ost com plex t est s you ll aut om at e, but ar e usually t he m ost im por t ant . Typical t est s can be for login, r egist rat ion t o t he sit e, user account operat ions, account set t ings changes, com plex dat a r et r ieval operat ions, am ong ot her s. Funct ion t est s t ypically m ir r or t he user - scenar ios used t o specify t he feat ur es and design or your applicat ion.
This shows an HTML t ag for a check box. I t s I D ( addFor m : _I D74: _I D75: 0: _I D79: 0: checkBox) is a dynam ically generat ed value. The next t im e t he sam e page is opened it will likely be a differ ent value.
Ajax Tests
Aj ax is a t echnology which suppor t s dynam ically changing user int er face elem ent s which can dynam ically change wit hout t he br owser having t o r eload t he page, such as anim at ion, RSS feeds, and r eal- t im e dat a updat es am ong ot her s. Ther e s a count less ways Aj ax can be used t o updat e elem ent s on a web page. But , t he easy way t o t hink of t his is t hat in Aj ax- dr iven applicat ions, dat a can r et r ieved fr om t he applicat ion ser ver and t hen displayed on t he page wit hout r eloading t he ent ir e page. Only a por t ion of t he page, or st r ict ly t he elem ent it self is r eloaded.
Validating Results
Assert vs. Verify
When should you use an asser t com m and and when should you use a ver ify com m and? This is up t o you. The differ ence is in what you want t o happen when t he check fails. Do you want your t est t o t er m inat e, or t o cont inue and sim ply r ecor d t hat t he check failed? Her e s t he t rade- off. I f you use an asser t , t he t est will st op at t hat point and not r un any subsequent checks. Som et im es, per haps 28/05/2013 7:35
2 de 10
Selenium Documentation
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
t er m inat e, or t o cont inue and sim ply r ecor d t hat t he check failed? Her e s t he t rade- off. I f you use an asser t , t he t est will st op at t hat point and not r un any subsequent checks. Som et im es, per haps oft en, t hat is what you want . I f t he t est fails you will im m ediat ely know t he t est did not pass. Test engines such as Test NG and JUnit have plugins for com m only used developm ent envir onm ent s ( Chap 5) which convenient ly flag t hese t est s as failed t est s. The advant age: you have an im m ediat e visual of whet her t he checks passed. The disadvant age: when a check does fail, t her e ar e ot her checks which wer e never per for m ed, so you have no infor m at ion on t heir st at us. I n cont rast , ver ify com m ands will not t er m inat e t he t est . I f your t est uses only ver ify com m ands you ar e guarant eed ( assum ing no unexpect ed except ions) t he t est will r un t o com plet ion whet her t he checks find defect s or not . The disadvant age: you have t o do m or e wor k t o exam ine your t est r esult s. That is, you won t get feedback fr om Test NG or JUnit . You will need t o look at t he r esult s of a console pr int out or a log out put . And you will need t o t ake t he t im e t o look t hr ough t his out put ever y t im e you r un your t est . I f you ar e r unning hundr eds of t est s, each wit h it s own log, t his will be t im e- consum ing, and t he im m ediat e feedback of asser t s will be m or e appr opr iat e. Asser t s ar e m or e com m only used t han ver ifys due t o t heir im m ediat e feedback.
Selenium Documentation
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
is. You only car e t hat a specific elem ent , say, an im age, is at a specific locat ion. Get t ing a feel for t hese t ypes of decisions will com e wit h t im e and a lit t le exper ience. They ar e easy concept s, and easy t o change in your test.
Location Strategies
Choosing a Location Strategy
Ther e ar e m ult iple ways of select ing an obj ect on a page. But what ar e t he t rade offs of each of t hese locat or t ypes? Recall we can locat e an obj ect using t he elem ent s I D t he elem ent s nam e at t r ibut e an XPath statement by a links t ext docum ent obj ect m odel ( DOM) Using an elem ent I D or nam e locat or is t he m ost efficient in t er m s of t est per for m ance, and also m akes your t est code m or e r eadable, assum ing t he I D or nam e wit hin t he page sour ce is well- nam ed. XPat h st at em ent s t ake longer t o pr ocess since t he br owser m ust r un it s XPat h pr ocessor. XPat h has been known t o be especially slow in I nt er net Explor er ver sion 7. Locat ing via a link s t ext is oft en convenient and per for m s well. This t echnique is specific t o links t hough. Also, if t he link t ext is likely t o change fr equent ly, locat ing by t he < a> elem ent would be t he bet t er choice. Som et im es t hough, you m ust use an XPat h locat or. I f t he page sour ce does not have an I D or nam e at t r ibut e you m ay have no choice but t o use an XPat h locat or. ( DOM locat or s ar e no longer com m only used since XPat h can do ever yt hing t hey can and m or e. DOM locat or s ar e available sim ply t o suppor t legacy t est s.) Ther e is an advant age t o using XPat h t hat locat ing via I D or nam e at t r ibut es do not have. Wit h XPat h ( and DOM) you can locat e an obj ect wit h r espect t o anot her obj ect on t he page. For exam ple, if t her e is a link t hat m ust occur wit hin t he second paragraph wit hin a < div> sect ion, you can use XPat h t o specify t his. Wit h I D and nam e locat or s, you can only specify t hat t hey occur on t he page t hat is, som ewher e on t he page. I f you m ust t est t hat an im age displaying t he com pany logo appear s at t he t op of t he page wit hin a header sect ion XPat h m ay be t he bet t er locat or.
<a class="button" id="adminHomeForm" onclick="return oamSubmitForm('admi 'adminHomeForm:_ID38');" href="#">View Archived Allocation Events
4 de 10
This HTML anchor t ag defines a but t on wit h an I D at t r ibut e of adm inHom eFor m . I t s a fair ly com plex anchor t ag when com par ed t o m ost HTML t ags, but it is st ill a st at ic t ag. The HTML will be t he sam e each t im e t his page is loaded in t he br owser. I t s I D r em ains const ant wit h all inst ances of t his page. That is, when t his page is displayed, t his UI elem ent will always have t his I dent ifier. So, for 28/05/2013 7:35
Selenium Documentation
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
sam e each t im e t his page is loaded in t he br owser. I t s I D r em ains const ant wit h all inst ances of t his page. That is, when t his page is displayed, t his UI elem ent will always have t his I dent ifier. So, for your t est scr ipt t o click t his but t on you sim ply need t o use t he following selenium com m and.
click adminHomeForm
Your applicat ion, however, m ay generat e HTML dynam ically wher e t he ident ifier var ies on differ ent inst ances of t he webpage. For inst ance, HTML for a dynam ic page elem ent m ight look like t his.
This defines a checkbox. I t s I D and nam e at t r ibut es ( bot h addFor m : _I D74: _I D75: 0: _I D79: 0: checkBox) ar e dynam ically generat ed values. I n t his case, using a st andar d locat or would look som et hing like t he following.
click addForm:_ID74:_ID75:0:_ID79:0:checkBox
Given t he dynam ically generat ed I dent ifier, t his appr oach would not wor k. The next t im e t his page is loaded t he I dent ifier will be a differ ent value fr om t he one used in t he Selenium com m and and t her efor e, will not be found. The click operat ion will fail wit h an elem ent not found er r or. To cor r ect t his, a sim ple solut ion would be t o j ust use an XPat h locat or rat her t han t r ying t o use an I D locat or. So, for t he checkbox you can sim ply use
click //input
Or, if it is not t he fir st input elem ent on t he page ( which it likely is not ) t r y a m or e det ailed XPat h st at em ent .
click //input[3]
Or
click //div/p[2]/input[3]
I f however, you do need t o use t he I D t o locat e t he elem ent , a differ ent solut ion is needed. You can capt ur e t his I D fr om t he websit e befor e you use it in a Selenium com m and. I t can be done like t his.
This appr oach will wor k if t her e is only one check box whose I D cont ains t he t ext addFor m . 5 de 10 28/05/2013 7:35
Selenium Documentation
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
This appr oach will wor k if t her e is only one check box whose I D cont ains t he t ext addFor m .
This cer t ainly isn t t he only solut ion. Aj ax is a com m on t opic in t he user for um and we r ecom m end sear ching pr evious discussions t o see what others have done.
I nst ead of duplicat ing t his code you could wr it e a wrapper m et hod t hat per for m s bot h funct ions.
This exam ple uses t he Selenium 1 API but Selenium 2 also suppor t s t his. 6 de 10 28/05/2013 7:35
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
I n t his second exam ple XXXX is sim ply a placeholder for one of t he m ult iple locat ion m et hods t hat can be called her e. Using safe m et hods is up t o t he t est developer s discr et ion. Hence, if t est execut ion is t o be cont inued, even in t he wake of m issing elem ent s on t he page, t hen safe m et hods could be used, while post ing a m essage t o a log about t he m issing elem ent . This, essent ially, im plem ent s a ver ify wit h a r epor t ing m echanism as opposed t o an abor t ive asser t . But if elem ent m ust be available on page in or der t o be able t o car r y out fur t her operat ions ( i.e. login but t on on hom e page of a por t al) t hen t his safe m et hod t echnique should not be used.
UI Mapping
A UI m ap is a m echanism t hat st or es all t he locat or s for a t est suit e in one place for easy m odificat ion when ident ifier s or pat hs t o UI elem ent s change in t he AUT. The t est scr ipt t hen uses t he UI Map for locat ing t he elem ent s t o be t est ed. Basically, a UI m ap is a r eposit or y of t est scr ipt obj ect s t hat cor r espond t o UI elem ent s of t he applicat ion being t est ed. What m akes a UI m ap helpful? I t s pr im ar y pur pose is m aking t est scr ipt m anagem ent m uch easier. When a locat or needs t o be edit ed, t her e is a cent ral locat ion for easily finding t hat obj ect , rat her t han having t o sear ch t hr ough t est scr ipt code. Also, it allows changing t he I dent ifier in a single place, rat her t han having t o m ake t he change in m ult iple places wit hin a t est scr ipt , or for t hat m at t er, in m ult iple t est scr ipt s. To sum m ar ize, a UI m ap has t wo significant advant ages. Using a cent ralized locat ion for UI obj ect s inst ead of having t hem scat t er ed t hr oughout t he scr ipt . This m akes scr ipt m aint enance m or e efficient . Cr ypt ic HTML I dent ifier s and nam es can be given m or e hum anr eadable nam es im pr oving t he r eadabilit y of t est scr ipt s. Consider t he following, difficult t o under st and, exam ple ( in j ava) .
This scr ipt would be har d t o follow for anyone not fam iliar wit h t he AUT s page sour ce. Even r egular user s of t he applicat ion m ight have difficult y under st anding what t hus scr ipt does. A bet t er scr ipt could be:
Now, using som e com m ent s and whit espace along wit h t he UI Map ident ifier s m akes a ver y r eadable scr ipt .
Ther e ar e var ious ways a UI Map can be im plem ent ed. One could cr eat e a class or st r uct which only st or es public St r ing var iables each st or ing a locat or. Alt er nat ively, a t ext file st or ing key value pair s could be used. I n Java, a pr oper t ies file cont aining key/ value pair s is pr obably best m et hod. 7 de 10 Consider a pr oper t y file prop.properties which assigns as aliases 28/05/2013 7:35
Selenium Documentation
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
be used. I n Java, a pr oper t ies file cont aining key/ value pair s is pr obably best m et hod. Consider a pr oper t y file prop.properties which assigns as aliases r eader - fr iendly ident ifier s for UI elem ent s fr om t he pr evious exam ple.
admin.username = loginForm:tbUsername admin.loginbutton = loginForm:btnLogin admin.events.createnewevent = adminHomeForm:_activitynew admin.events.cancel = addEditEventForm:_IDcancel admin.events.viewoldevents = adminHomeForm:_activityold
The locat or s will st ill r efer t o ht m l obj ect s, but we have int r oduced a layer of abst ract ion bet ween t he t est scr ipt and t he UI elem ent s. Values ar e r ead fr om t he pr oper t ies file and used in t he Test Class t o im plem ent t he UI Map. For m or e on Java pr oper t ies files r efer t o t he following link.
Ther e ar e t wo pr oblem s wit h t his appr oach. 1. Ther e is no separat ion bet ween t he t est m et hod and t he AUTs locat or s ( I Ds in t his exam ple) ; bot h ar e int er t wined in a single m et hod. I f t he AUT s UI changes it s ident ifier s, layout , or how a login is input and pr ocessed, t he t est it self m ust change. 2. The id- locat or s would be spr ead in m ult iple t est s, all t est s t hat had t o use t his login page. 8 de 10 Applying t he page obj ect t echniques t his exam ple could be r ewr it t en28/05/2013 7:35
Selenium Documentation
Applying t he page obj ect t echniques t his exam ple could be r ewr it t en like t his in t he following exam ple of a page obj ect for a Sign- in page.
and page obj ect for a Hom e page could look like t his.
So now, t he login t est would use t hese t wo page obj ect s as follows.
Ther e is a lot of flexibilit y in how t he page obj ect s m ay be designed, but t her e ar e a few basic r ules for get t ing t he desir ed m aint ainabilit y of your t est code. Page obj ect s t hem selves should never be m ake ver ificat ions or asser t ions. This is par t of your t est and should always be wit hin t he t est s code, never in an page obj ect . The page obj ect will cont ain t he r epr esent at ion of t he page, and t he ser vices t he page pr ovides via m et hods but no code r elat ed t o what is being t est ed should be wit hin t he page obj ect . Ther e is one, single, ver ificat ion which can, and should, be wit hin t he page obj ect and t hat is t o ver ify t hat t he page, and possibly cr it ical elem ent s on t he page, wer e loaded cor r ect ly. This ver ificat ion should be done while inst ant iat ing t he page obj ect . I n t he exam ples above, bot h t he SignI nPage and Hom ePage const r uct or s check t hat t he expect ed page is available and r eady for r equest s fr om t he t est . A page obj ect does not necessar ily need t o r epr esent an ent ir e page. The Page Obj ect design pat t er n could be used t o r epr esent com ponent s on a page. I f a page in t he AUT has m ult iple com ponent s, it m ay im pr oved m aint ainabilit y if t her e was a separat e page obj ect for each component. Ther e ar e ot her design pat t er ns t hat also m ay be used in t est ing. Som e use a Page Fact or y for inst ant iat ing t heir page obj ect s. Discussing all of t hese is beyond t he scope of t his user guide. Her e, we m er ely want t o int r oduce t he concept s t o m ake t he r eader awar e of som e of t he t hings t hat can be done. As was m ent ioned ear lier, m any have blogged on t his t opic and we encourage t he r eader t o sear ch for blogs on t hese t opics.
9 de 10
28/05/2013 7:35
Selenium Documentation
http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp
source = open("input_file.txt", "r") values = source.readlines() source.close() # Execute For loop for each String in the values array for search in values: sel.open("/") sel.type("q", search) sel.click("btnG") sel.waitForPageToLoad("30000") self.failUnless(sel.is_text_present("Results * for " + search
The Pyt hon scr ipt above opens a t ext file. This file cont ains a differ ent sear ch st r ing on each line. The code t hen saves t his in an ar ray of st r ings, and it erat es over t he ar ray doing a sear ch and asser t on each st r ing. This is a ver y basic exam ple, but t he idea is t o show t hat r unning a t est wit h var ying dat a can be done easily wit h a pr ogram m ing or scr ipt ing language. For m or e exam ples, r efer t o t he Selenium RC wiki for exam ples of r eading dat a fr om a spr eadsheet or for using t he dat a pr ovider capabilit ies of Test NG. Addit ionally, t his is a well- known t opic am ong t est aut om at ion pr ofessionals including t hose who don t use Selenium so sear ching t he int er net on dat a- dr iven t est ing should r eveal m any blogs on t his t opic.
Database Validation
Anot her com m on t ype of t est ing is t o com par e dat a in t he UI against t he dat a act ually st or ed in t he AUT s dat abase. Since you can also do dat abase quer ies fr om a pr ogram m ing language, assum ing you have dat abase suppor t funct ions, you can use t hem t o r et r ieve dat a and t hen use t he dat a t o ver ify what s displayed by t he AUT is cor r ect . Consider t he exam ple of a r egist er ed em ail addr ess t o be r et r ieved fr om a dat abase and t hen lat er com par ed against t he UI . An exam ple of est ablishing a DB connect ion and r et r ieving dat a fr om t he DB could look like t his. In Java:
This is a sim ple Java exam ple of dat a r et r ieval fr om a dat abase.
10 de 10
28/05/2013 7:35
Selenium-Grid
Selenium Documentation
http://docs.seleniumhq.org/docs/07_selenium_grid.jsp
Note: We are currently working on this chapter. Presently we have introductory info here for people completely new to Selnium-Grid. Over the next few months we hope to provide useful examples and illustrations to thoroughly explain how to use Selenium-Grid.
Quick Start
I f you r e alr eady exper ienced in Selenium t est aut om at ion you m ay sim ply need a quick- st ar t t o get up and r unning. This chapt er has m uch infor m at ion gear ed t o m any skill levels, but m ay be t oo m uch if you r e looking for j ust a quick r efer ence t o quickly t r y t hings out . For a quick- st ar t , r efer t o t he Selenium - Gr id ar t icles in t he Selenium Wiki.
What is Selenium-Grid?
Selenium - Gr id allows you r un your t est s on differ ent m achines against differ ent br owser s in parallel. That is, r unning m ult iple t est s at t he sam e t im e against differ ent m achines r unning differ ent br owser s and operat ing syst em s. Essent ially, Selenium - Gr id suppor t dist r ibut ed t est execut ion. I t allows for r unning your t est s in a distributed test execution envir onm ent .
When to Use It
Generally speaking, t her e s t wo r easons why you m ight want t o use Selenium - Gr id. To r un your t est s against m ult iple br owser s, m ult iple ver sions of br owser, and br owser s r unning on differ ent operat ing syst em s. To r educe t he t im e it t akes for t he t est suit e t o com plet e a t est pass. Selenium - Gr id is used t o speed up t he execut ion of a t est pass by using m ult iple m achines t o r un t est s in parallel. For exam ple, if you have a suit e of 100 t est s, but you set up Selenium - Gr id t o suppor t 4 differ ent m achines ( VMs or separat e physical m achines) t o r un t hose t est s, your t est suit e will com plet e in ( r oughly) one- four t h t he t im e as it would if you ran your t est s sequent ially on a single m achine. For lar ge t est suit es, and long- r unning t est suit e such as t hose per for m ing lar ge am ount s of dat a-validat ion, t his can be a significant t im e- saver. Som e t est suit es can t ake hour s t o r un. Anot her r eason t o boost t he t im e spent r unning t he suit e is t o shor t en t he t ur nar ound t im e for t est r esult s aft er developer s check- in code for t he AUT. I ncr easingly soft war e t eam s pract icing Agile soft war e developm ent want t est feedback as im m ediat ely as possible as opposed t o wait over night for an over night t est pass. Selenium - Gr id is also used t o suppor t r unning t est s against m ult iple r unt im e envir onm ent s, specifically, against differ ent br owser s at t he sam e t im e. For exam ple, a gr id of vir t ual m achines can be set up wit h each suppor t ing a differ ent br owser t hat t he applicat ion t o be t est ed m ust suppor t . So, m achine 1 has I nt er net Explor er 8, m achine 2, I nt er net Explor er 9, m achine 3 t he lat est Chr om e, and m achine 4 t he lat est Fir efox. When t he t est suit e is r un, Selenium - Gr id r eceives each t est- br owser com binat ion and assigs each t est t o r un against it s r equir ed br owser. 1 de 6 I n addit ion, one can have a gr id of all t he sam e br owser, t ype and 28/05/2013 7:26
Selenium-Grid
Selenium Documentation
http://docs.seleniumhq.org/docs/07_selenium_grid.jsp
r equir ed br owser. I n addit ion, one can have a gr id of all t he sam e br owser, t ype and ver sion. For inst ance, one could have a gr id of 4 m achines each r unning 3 inst ances of Fir efox 12, allowing for a ser ver - far m ( in a sense) of available Fir efox inst ances. When t he suit e r uns, each t est is passed t o Selenium - Gr id which assigns t he t est t o t he next available Fir efox inst ance. I n t his m anner one get s t est pass wher e conceivably 12 t est s ar e all r unning at t he sam e t im e in parallel, significant ly r educing t he t im e r equir ed t o com plet e a t est pass. Selenium - Gr id is ver y flexible. These t wo exam ples can be com bined t o allow m ult iple inst ances of each br owser t ype and ver sion. A configurat ion such as t his would pr ovide bot h, parallel execut ion for fast t est pass com plet ion and suppor t for m ult iple br owser t ypes and ver sions sim ult aneously.
Selenium-Grid 2.0
Selenium - Gr id 2.0 is t he lat est r elease as of t he wr it ing of t his docum ent ( 5/ 26/ 2012) . I t is quit e differ ent fr om ver sion 1 of Selenium - Gr id. I n 2.0 Selenium - Gr id was m er ged wit h t he Selenium - RC ser ver. Now, you only need t o download a single .j ar file t o get t he r em ot e Selenium - RC- Ser ver and Selenium - Gr id all in one package.
Selenium-Grid 1.0
Ver sion 1 was t he fir st general r elease of Selenium - Gr id. I f you ar e new t o Selenium - Gr id you should use ver sion 2. I t s been updat ed and has new feat ur es, and suppor t s Selenium -WebDr iver. Legacy t est syst em s m ay st ill be using ver sion 1 however. I nfor m at ion on Selenium - Gr id ver sion 1 m ay be found at t he Selenium - Gr id websit e.
Installation
I nst allat ion is sim ple. Download t he Selenium - Ser ver j ar file fr om t he Selenium Hq websit e s download page. You want t he link under t he sect ion Selenium - Ser ver ( for m er ly Selenium - RC) . 28/05/2013 7:26
2 de 6
Selenium-Grid
Selenium Documentation
http://docs.seleniumhq.org/docs/07_selenium_grid.jsp I nst allat ion is sim ple. Download t he Selenium - Ser ver j ar file fr om t he Selenium Hq websit e s download page. You want t he link under t he sect ion Selenium - Ser ver ( for m er ly Selenium - RC) . I nst all it in a folder of your choice. You ll need t o be sur e t he j ava execut able is on your execut ion pat h so you can r un it fr om t he com m and- line. I f it does not r un cor r ecly, ver ify your syst em s pat h var iable includes t he pat h t o t he j ava.exe.
Starting Selenium-Grid
Generally you would st ar t a hub fir st since nodes depend on a hub. This is not abolut ely necessar y however, since nodes can r ecognize when a hub has been st ar t ed and vice-ver sa. For lear ning pur poses t hough, it would easier t o st ar t t he hub fir st , ot her wise you ll see er r or m essages t hat m ay not want t o st ar t off wit h your fir st t im e using Selenium - Gr id.
Starting a Hub
To st ar t a hub wit h default param et er s, r un t he following com m and fr om a com m and- line shell. This will wor k on all t he suppor t ed plat for m s, Windows Linux, or MacOs.
java -jar selenium-server-standalone-2.21.0.jar -role hub
This st ar t s a hub using default param et er values. We ll explain t hese param et er s in folowing subsect ions. Not e t hat you will likely have t o change t he ver sion num ber in t he j ar filenam e depending on which ver sion of t he selenium - ser ver you r e using.
Starting a Node
To st ar t a node using default param et er s, r un t he following com m and fr om a com m and- line.
java -jar selenium-server-standalone-2.21.0.jar -role node
-hub http://
This assum es t he hub has been st ar t ed above using default param et er s. The default por t t he hub uses t o list en for new r equest s is por t 4444. This is why por t 4444 was used in t he URL for locat ing t he hub. Also t he use of localhost assum es your node is r unning on t he sam e m achine as your hub. For get t ing st ar t ed t his is pr obably easiest . I f r unning t he hub and node on separat e m achines, sim ply r eplace localhost wit h t he host nam e of t he r em ot e m achine r unning t he hub. WARNI NG: Be sur e t o t ur n off t he fir ewalls on t he m achine r unning your hub and nodes. Ot her wise you m ay get connect ion er r or s.
Configuring Selenium-Grid
Default Configuration JSON Configuration File Configuring Via the Command-Line Options
Hub Configuration
3 de 6 To r un t he hub using t he default opt ions sim ply specify - r ole hub t o t he Selenim - Ser ver 28/05/2013 7:26
Selenium-Grid
Selenium Documentation
http://docs.seleniumhq.org/docs/07_selenium_grid.jsp
Hub Configuration
To r un t he hub using t he default opt ions sim ply specify - r ole hub t o t he Selenim - Ser ver
java -jar selenium-server-standalone-2.21.0.jar -hub
Jul 19, 2012 10:46:21 AM org.openqa.grid.selenium.GridLauncher main INFO: Launching a selenium grid server 2012-07-19 10:46:25.082:INFO:osjs.Server:jetty-7.x.y-SNAPSHOT 2012-07-19 10:46:25.151:INFO:osjsh.ContextHandler:started o.s.j.s.ServletC 2012-07-19 10:46:25.185:INFO:osjs.AbstractConnector:Started SocketConnecto
10:56:35.490 WARN - Failed to start: SocketListener0@0.0.0.0:4444 Exception in thread "main" java.net.BindException: Selenium is already r
I f t his occur s you can eit her shut down t he ot her pr ocess t hat is using por t 4444, or you can t ell Selenium - Gr id t o use a differ ent por t for it s hub. Use t he - por t opt ion for changing t he por t used by the hub.
java -jar selenium-server-standalone-2.21.0.jar -role hub -port 4441
This will wor k even if anot her hub is alr eady r unning on t he sam e m achine, t hat is, as long as t hey r e bot h not using por t 4441. You m ay, however, want t o see what pr ocess is using por t 4444 so you can allow t he hub t o use t he default . To see t he por t s used by all r unning pr ogram s on your m achine use t he com m and.
netstat -a
This should wor k on all suppor t ed syst em s, Unix/ Linux, MacOs, and Windows alt hough addit ional opt ions beyond - a m ay be r equir ed. Basically you need t o display t he pr ocess I D along wit h t he por t . I n Unix you m ay gr ep t he out put ( use a pipe) fr om t he por t num ber t o only display t hose r ecor ds you r e concer ned wit h.
Selenium-Grid
http://docs.seleniumhq.org/docs/07_selenium_grid.jsp
The Selenium - Ser ver pr ovides t wo dist inct funct ions, t hat of t he Selenium - RC ser ver and t hat of Selenium - Gr id. These wer e likely wr it t en by differ ent Selenium t eam s, and t her efor e t he com m and- line help for each funct ion has ended up in t wo differ ent places. And, for t he new user, it m ay not be appar ent at fir st which of t hese t wo you ar e viewing. I f you sim ply pass a - h opt ion as you m ight fir st assum e, you get t he Selenium - RC Ser ver opt ions but not t hose for Selenium - Gr id.
java -jar selenium-server-standalone-2.21.0.jar -h
This would give you Selenium - RC s ser ver opt ions. I f you want t he com m and- line help for Selenium - Gr id, you fir st use t he - hub or - node opt ions t o t ell Selenium - Ser ver you r e int er et ed in Selenium - Gr id, and t hen follow wit h a - h.
java -jar selenium-server-standalone-2.21.0.jar -role node -h
Or, for t hat m at t er, j ust pass a gar bage ar gum ent t o t he - r ole node as follows.
java -jar selenium-server-standalone-2.21.0.jar -role node xx
You will fir st see I NFO... and an ERROR but below t hat you ll get t he com m and- line opt ions for Selenium - Gr id. We won t list t he whole out put her e since it s rat her long, but t he fir st few lines look like t his.
Jul 19, 2012 10:10:39 AM org.openqa.grid.selenium.GridLauncher main INFO: Launching a selenium grid node org.openqa.grid.common.exception.GridConfigurationException: You need to s at org.openqa.grid.common.RegistrationRequest.validate(Registratio at org.openqa.grid.internal.utils.SelfRegisteringRemote.startRemot at org.openqa.grid.selenium.GridLauncher.main(GridLauncher.java:72 Error building the config :You need to specify a hub to register to using Usage : -hubConfig: (hub) a JSON file following grid2 format. -nodeTimeout: (node) <XXXX> the timeout in seconds before the hub automatically ends a test that hasn't had aby activity than XX sec.The browser will be released for another test to use.This typically takes care of the client crashes.
Common Errors
Unable to acess the jarfile
Unable to access jarfile selenium-server-standalone-2.21.0.jar
This er r or can occur when st ar t ing up eit her a hub or node. This m eans Java cannot find t he selenium - ser ver j ar file. Eit her r un t he com m and fr om t he dir ect or y wher e t he selenium - ser ver -XXXX.j ar file is st or ed, or specify an explicit pat h t o t he j ar.
Troubleshooting
5 de 6 28/05/2013 7:26
Selenium-Grid
Selenium Documentation
http://docs.seleniumhq.org/docs/07_selenium_grid.jsp
Troubleshooting
6 de 6
28/05/2013 7:26
User-Extensions
Selenium Documentation
http://docs.seleniumhq.org/docs/08_user_extensions.jsp
NOTE: This section is close to completion, but it has not been reviewed and edited.
Introduction
Ext ending Selenium by adding your own act ions, asser t ions and locat or - st rat egies can be quit e sim ple. Add JavaScr ipt m et hods t o t he Selenium obj ect pr ot ot ype and t he PageBot obj ect pr ot ot ype. On st ar t up, Selenium will aut om at ically look t hr ough m et hods on t hese pr ot ot ypes, using nam e pat t er ns t o r ecognize which ones ar e act ions, asser t ions and locat or s. The following exam ples give an indicat ion of how Selenium can be ext ended wit h JavaScr ipt .
Actions
All m et hods on t he Selenium pr ot ot ype beginning wit h do ar e added as act ions. For each act ion foo t her e is also an act ion fooAndWait r egist er ed. An act ion m et hod can t ake up t o t wo param et er s, which will be passed t he second and t hir d colum n values in t he t est . Exam ple: Add a t ypeRepeat ed act ion t o Selenium , which t ypes t he t ext t wice int o a t ext box.
Accessors/Assertions
All getFoo and isFoo m et hods on t he Selenium pr ot ot ype ar e added as accessor s ( st or eFoo) . For each accessor t her e is an asser t Foo, ver ifyFoo and wait For Foo r egist er ed. An asser t m et hod can t ake up t o 2 param et er s, which will be passed t he second and t hir d colum n values in t he t est . You can also define your own asser t ions lit erally as sim ple asser t m et hods, which will also aut o- generat e ver ify and wait For com m ands. Exam ple: Add a valueRepeat ed asser t ion, t hat m akes sur e t hat t he elem ent value consist s of t he supplied t ext r epeat ed. The 2 com m ands t hat would be available in t est s would be asser t ValueRepeat ed and ver ifyValueRepeat ed.
Also not e t hat t he assertValueRepeated m et hod descr ibed above could have been im plem ent ed using isValueRepeated, wit h t he added benefit of also aut om at ically get t ing asser t Not ValueRepeat ed, st or eValueRepeat ed, wait For ValueRepeat ed and wait For Not ValueRepeat ed.
Locator Strategies
1 de 3 28/05/2013 7:27
User-Extensions
Selenium Documentation
http://docs.selenium hq.org/docs/08_user_extensions.jsp
Locator Strategies
All locat eElem ent ByFoo m et hods on t he PageBot pr ot ot ype ar e added as locat or - st rat egies. A locat or st rat egy t akes 2 param et er s, t he fir st being t he locat or st r ing ( m inus t he pr efix) , and t he second being t he docum ent in which t o sear ch. Exam ple: Add a valuer epeat ed= locat or, t hat finds t he fir st elem ent a value at t r ibut e equal t o t he t he supplied value r epeat ed.
Example
C# 1. Place your user ext ension in t he sam e dir ect or y as your Selenium Ser ver. 2. I f you ar e using client code generat ed by t he Selenium -I DE you will need t o m ake a couple of sm all edit s. Fir st , you will need to create an HttpCommandProcessor obj ect wit h class scope ( out side t he Set upTest m et hod, j ust below private StringBuilder verificationErrors;)
HttpCommandProcessor proc;
3. Next , inst ant iat e t hat HttpCommandProcessor object as you would t he DefaultSelenium obj ect . This can be done in t he t est setup.
proc = new HttpCommandProcessor("localhost", 4444, "*iexplore",
4. I nst ant iat e t he Default Selenium obj ect using t he HttpCommandProcessor object you created.
selenium = new DefaultSelenium(proc);
2 de 3
5. Wit hin your t est code, execut e your user - ext ension by calling 28/05/2013 7:27
User-Extensions
Selenium Documentation
http://docs.selenium hq.org/docs/08_user_extensions.jsp
selenium = new DefaultSelenium(proc);
5. Wit hin your t est code, execut e your user - ext ension by calling it wit h t he DoCommand() method of HttpCommandProcessor. This m et hod t akes t wo ar gum ent s: a st r ing t o ident ify t he user - ext ension m et hod you want t o use and st r ing ar ray t o pass ar gum ent s. Not ice t hat t he fir st let t er of your funct ion is lower case, r egar dless of t he capit alizat ion in your user - ext ension. Selenium aut om at ically does t his t o keep com m on JavaScr ipt nam ing convent ions. Because JavaScr ipt is case sensit ive, your t est will fail if you begin t his com m and wit h a capit al. input Param s is t he ar ray of ar gum ent s you want t o pass t o t he JavaScr ipt user - ext ension. I n t his case t her e is only one st r ing in t he ar ray because t her e is only one param et er for our user ext ension, but a longer ar ray will m ap each index t o t he cor r esponding user - ext ension param et er. Rem em ber t hat user ext ensions designed for Selenium - I DE will only t ake t wo ar gum ent s.
string[] inputParams = {"Hello World"}; proc.DoCommand("alertWrapper", inputParams);
6. St ar t t he t est ser ver using t he -userExtensions argument and pass in your user-extensions.js file.
java -jar selenium-server.jar -userExtensions user-extensions.js
3 de 3
28/05/2013 7:27
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_cheat_sheet.jsp
Javascr ipt Execut or Allows t he execut ion of ar bit r ar y JS commands. Rot at able
I ndicat es whet her Java Rot at able.j ava t he dr iver suppor t s r ot at ing t he display ( m ost ly j ust m obile dr iver s) . Pr ovides a Java TakesScreenshot.java m echanism for t aking scr eenshot s.
TakesScreenshot
1 de 1
28/05/2013 7:27
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_android_driver.jsp
This is a placeholder.
Navigation
1 de 1
28/05/2013 7:28
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_dotnet_driver_client.jsp
Select Visual C# > Class Libr ar y > Nam e your pr oj ect > Click on OK but t on.
Under r igh t hand pane of Solut ion Ex plor er r igh t click on Refer en ces > Add Refer ences.
1 de 2
28/05/2013 7:28
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_dotnet_driver_client.jsp
Under r igh t hand pane of Solut ion Ex plor er r igh t click on Refer en ces > Add Refer ences.
Select following dll files - nm ock .dll, nun it .cor e.dll, nunit .fr am ewor k.dll,Thought Wor ks. Selenium .Cor e.dll, Th ou gh t Wor k s.Selenium .I nt egr at ionTest s.dll, Thought Wor k s.Selenium .Unit Test s.dll and click on Ok but t on
Navigation
2 de 2
28/05/2013 7:28
Selenium Document...
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...
Then open eclipse. Choose your wor k space or cr eat e a new one. Once t he Eclipse I DE loads, do t he following: # File - > I m por t ... # Gener al - > Ex ist ing Pr oj ect s int o Wor k space # Click nex t # Next t o Select r oot Dir ect or y : click Br owse but t on # locat e t he pr oj ect folder cont aining y our pom .x m l and click ok . # Your pr oj ect should appear in t he Pr oj ect s box alr eady # click finish I f you haven t alr eady, inst all t he m 2eclipse plugin t hen r ight click on your pr oj ect and select Maven - > Enable Dependency Managem ent .
1 de 8
28/05/2013 7:29
Selenium Document...
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...
Now you will see a dialog allowing you t o set pr oj ect opt ions including t he pr oj ect s r oot dir ect or y.
2 de 8
28/05/2013 7:29
Selenium Document...
http://docs.selenium hq.org/docs/appendix_installing_java_driver_Sel20_...
Now t he set t ings dialog will show t he dir ect or y you j ust select ed.
This nex t dialog shows t he nam e of your m aven pr oj ect as specified in t he pom .x m l file. Select your m aven pr oj ect and cont inue.
3 de 8
28/05/2013 7:29
Selenium Document...
Enter a name for your project.
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...
Once y our pr oj ect has been im por t ed it should look lik e t his in I nt elliJ.
The m aven pr oj ect download m any dependencies ( libr ar ies) when y ou or iginally r an m v n inst all . Now in I nt elliJ you can see all t hese librar ies. These nex t t wo scr een capt ur es shows t he librar ies you should now have in your pr oj ect .
4 de 8
28/05/2013 7:29
Selenium Document...
http://docs.selenium hq.org/docs/appendix_installing_java_driver_Sel20_...
Befor e you can st ar t wr it ing Selenium code, you st ill need t o cr eat e a m odule and at least one Java class ( a .j ava file) . Fir st select t he Pr oj ect s r oot in I nt elliJ and r ight click.
5 de 8
28/05/2013 7:29
Selenium Document...
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...
And nex t , you m ust cr eat e a folder for t he sour ce code. By convent ion t his is alm ost alway s nam ed sr c .
6 de 8
28/05/2013 7:29
Selenium Document...
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...
And nex t , you m ust cr eat e a folder for t he sour ce code. By convent ion t his is alm ost alway s nam ed sr c .
Now we r e on t he last dialog. Ty pically you don t need t o select any t echnollogies her e. Unless you k now for a fact y ou will be using Gr oov y or som e ot her t echnology.
Now t hat t he m odule is cr eat ed, your pr oj ect should show t he following st r uct ur e.
7 de 8
28/05/2013 7:29
Selenium Document...
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...
Finally, you need t o cr eat e a .j ava file wit h a cor r esponding j ava class.
The .j ava file should now be cr eat ed. I t should look like t his in your pr oj ect .
I f your pr oj ect now look s like t he one displayed above, you r e done, congr at s! And hope you enj oy coding your fir st Selenium aut om at ion!
8 de 8
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp
1 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp
Pr ov ide Nam e t o your pr oj ect , Select JDK in Use a pr oj ect Specific JRE opt ion ( JDK 1.5 select ed in t his ex am ple) > click Nex t
Keep JAVA Set t ings int act in nex t window. Pr oj ect specific librar ies can be added here. ( This descr ibed in det ail in lat er par t of docum ent .)
2 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp
Click Finish > Click on Yes in Open Associat ed Per spect ive pop up window.
This would cr eat e Pr oj ect Google in Pack age Ex plor er / Nav igat or pane.
3 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp
Nam e t his folder as com and click on Finish but t on. This should get com pack age insider sr c folder.
4 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.selenium hq.org/docs/appendix_installing_java_driver_client.jsp
SelTest Case class can be kept inside core package. Cr eat e one m or e pack age inside src folder named testscripts. This is a place holder for t est scripts. Please notice this is about the organization of project and it entirely depends on indiv idual s choice / or ganizat ion s st andar ds. Test scr ipt s pack age can fur t her be segr egat ed depending upon the project requirements.
5 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp
Cr eat e a folder called lib inside pr oj ect Google. Right click on Pr oj ect nam e > New > Folder. Th is is a place holder for j ar files t o pr oj ect ( i.e. Selenium client dr iver, selenium server etc)
6 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp
Right click on lib folder > Build Pat h > Configur e build Pat h
Under Librar y t ab click on Add Ex t er nal Jar s t o nav igat e t o dir ect or y wher e j ar files are saved. Select t he j ar files which ar e t o be added and click on Open but t on.
7 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp
8 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp
Navigation
9 de 9
28/05/2013 7:29
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_python_driver_client.jsp
Mac The lat est Mac OS X ver sion ( Leopar d at t his t im e) com es wit h Py t hon pr e- inst alled. To inst all an ext r a Py t hon, get a univer sal binar y at http://www.pythonmac.org/ ( pack ages for Pyt hon 2.5.x) . You will get a .dm g
1 de 2
28/05/2013 7:30
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_installing_python_driver_client.jsp
The lat est Mac OS X ver sion ( Leopar d at t his t im e) com es wit h Py t hon pr e- inst alled. To inst all an ext r a Py t hon, get a univer sal binar y at http://www.pythonmac.org/ ( pack ages for Pyt hon 2.5.x) . You will get a .dm g file t hat you can m ount . I t cont ains a .pk g file t hat you can launch.
I nst alling t he Selenium dr iver client for pyt hon 1. Download t he last ver sion of Selenium Rem ot e Cont r ol fr om t he downloads page 2. Ext ract t he cont ent of t he downloaded zip file 3. Copy t he m odule wit h t he Selenium s dr iver for Py t hon ( selenium .py ) in the folder C:/Python25/Lib ( t his will allow you t o im por t it dir ect ly in any scr ipt you wr it e) . You will find t he m odule in t he ex t ract ed folder, it s locat ed inside selenium-python-driver-client.
Congr at ulat ions, you r e done! Now any pyt hon scr ipt t hat you cr eat e can im por t selenium and st ar t int er act ing wit h t he br owser s.
Navigation
2 de 2
28/05/2013 7:30
Locating Techniques
Selenium Documentation
http://docs.seleniumhq.org/docs/appendix_locating_techniques.jsp
starts-with
Many sit es use dynam ic values for elem ent s id at t r ibut es, which can m ake t hem difficult t o locat e. One sim ple solut ion is t o use XPat h funct ions and base t he locat ion on what you do know about t he elem ent . For exam ple, if your dynam ic ids have t he for m at <input id="text-12345" /> where 12345 is a dynam ic num ber you could use t he following XPat h: //input[starts-with(@id, 'text-')]
contains
I f an elem ent can be locat ed by a value t hat could be sur r ounded by ot her t ext , t he cont ains funct ion can be used. To dem onst rat e, t he elem ent <span class="top heading bold"> can be locat ed based on t he heading class wit hout having t o couple it wit h t he t op and bold classes using t he following XPat h: //span[contains(@class, 'heading')]. I ncident ally, t his would be m uch neat er ( and pr obably fast er ) using t he CSS locat or st rat egy css=span.heading
siblings
Not yet wr it t en - locat e elem ent s based on t heir siblings. Useful for for m s and t ables.
1 de 1
28/05/2013 7:31
Selenium Docu...
http://docs.seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriv...
Before Starting
I n or der t o m ake t he pr ocess of m igrat ing as painless as possible, m ake sur e t hat all your t est s r un pr oper ly wit h t he lat est Selenium r elease. This m ay sound obvious, but it s best t o have it said!
Getting Started
1 de 4 The fir st st ep when st ar t ing t he m igrat ion is t o change how you obt ain your inst ance of Selenium . When using Selenium RC, t his is done like 28/05/2013 7:32
Selenium Docu...
http://docs.seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriv...
Getting Started
The fir st st ep when st ar t ing t he m igrat ion is t o change how you obt ain your inst ance of Selenium . When using Selenium RC, t his is done like so:
Once you ve done t his, r un your exist ing t est s. This will give you a fair idea of how m uch wor k needs t o be done. The Selenium em ulat ion is good, but it s not com plet ely per fect , so it s com plet ely nor m al for t her e t o be som e bum ps and hiccups.
Next Steps
Once your t est s execut e wit hout er r or s, t he next st age is t o m igrat e t he act ual t est code t o use t he WebDr iver API s. Depending on how well abst ract ed your code is, t his m ight be a shor t pr ocess or a long one. I n eit her case, t he appr oach is t he sam e and can be sum m ed up sim ply: m odify code t o use t he new API when you com e t o edit it . I f you need t o ext ract t he under lying WebDr iver im plem ent at ion fr om t he Selenium inst ance, you can sim ply cast it t o WrapsDr iver :
This allows you t o cont inue passing t he Selenium inst ance ar ound as nor m al, but t o unwr ap t he WebDr iver inst ance as r equir ed. At som e point , you r e codebase will m ost ly be using t he newer API s. At t his point , you can flip t he r elat ionship, using WebDr iver t hr oughout and inst ant iat ing a Selenium inst ance on dem and:
Common Problems
For t unat ely, you r e not t he fir st per son t o go t hr ough t his m igrat ion, so her e ar e som e com m on pr oblem s t hat ot her s have seen, and how t o solve t hem .
This r elies on t he fact t hat t ype sim ply r eplaces t he cont ent of t he ident ified elem ent wit hout also fir ing all t he event s t hat would nor m ally be fir ed if a user int eract s wit h t he page. The final dir ect invocat ions of key* cause t he JS handler s t o fir e as expect ed. When using t he WebDr iver BackedSelenium , t he r esult of filling in t he for m field would be excit ing t ext t t : not what you d expect ! The r eason for t his is t hat WebDr iver m or e accurat ely em ulat es user behavior, and so will have been fir ing event s all along. This sam e fact m ay som et im es cause a page load t o fir e ear lier t han it would do in a Selenium 1 t est . You can t ell t hat t his has happened if a St aleElem ent Except ion is t hr own by WebDr iver. 2 de 4
28/05/2013 7:32
Selenium Docu...
http://docs.seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriv...
This m ay look com plex, but it s alm ost all boiler - plat e code. The only int er est ing bit is t hat t he Expect edCondit ion will be evaluat ed r epeat edly unt il t he apply m et hod r et ur ns som et hing t hat is neit her null nor Boolean.FALSE. Of cour se, adding all t hese wait calls m ay clut t er up your code. I f t hat s t he case, and your needs ar e sim ple, consider using t he im plicit wait s:
By doing t his, ever y t im e an elem ent is locat ed, if t he elem ent is not pr esent , t he locat ion is r et r ied unt il eit her it is pr esent , or unt il 30 seconds have passed.
Finding By XPath or CSS Selectors Doesn t Always Work, But It Does In Selenium 1
I n Selenium 1, it was com m on for xpat h t o use a bundled librar y rat her t han t he capabilit ies of t he br owser it self. WebDr iver will always use t he nat ive br owser m et hods unless t her e s no alt er nat ive. That m eans t hat com plex xpat h expr essions m ay br eak on some browsers. CSS Select or s in Selenium 1 wer e im plem ent ed using t he Sizzle librar y. This im plem ent s a super set of t he CSS Select or spec, and it s not always clear wher e you ve cr ossed t he line. I f you r e using t he WebDr iver BackedSelenium and use a Sizzle locat or inst ead of a CSS Select or for finding elem ent s, a war ning will be logged t o t he console. I t s wor t h t aking t he t im e t o look for t hese, par t icular ly if t est s ar e failing because of not being able t o find elem ent s.
There is No Browserbot
Selenium RC was based on Selenium Cor e, and t her efor e when you execut ed Javascr ipt , you could access bit s of Selenium Cor e t o m ake 28/05/2013 7:32
3 de 4
Selenium Docu...
http://docs.seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriv...
Selenium RC was based on Selenium Cor e, and t her efor e when you execut ed Javascr ipt , you could access bit s of Selenium Cor e t o m ake t hings easier. As WebDr iver is not based on Selenium Cor e, t his is no longer possible. How can you t ell if you r e using Selenium Cor e? Sim ple! Just look t o see if your get Eval or sim ilar calls ar e using selenium or br owser bot in t he evaluat ed Javascr ipt . You m ight be using t he br owser bot t o obt ain a handle t o t he cur r ent window or docum ent of t he t est . For t unat ely, WebDr iver always evaluat es JS in t he cont ext of t he cur r ent window, so you can use window or docum ent dir ect ly. Alt er nat ively, you m ight be using t he br owser bot t o locat e elem ent s. I n WebDr iver, t he idiom for doing t his is t o fir st locat e t he elem ent , and t hen pass t hat as an ar gum ent t o t he Javascr ipt . Thus:
becomes:
Not ice how t he passed in elem ent var iable appear s as t he fir st it em in t he JS st andar d ar gum ent s ar ray.
becomes:
Navigation
4 de 4
28/05/2013 7:32