Anda di halaman 1dari 107

Selenium-IDE

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.

Installing the IDE


Using Fir efox , fir st , download t he I DE fr om t he Selenium HQ downloads page Fir efox will pr ot ect you fr om inst alling addons fr om unfam iliar locat ions, so you will need t o click Allow t o pr oceed wit h t he inst allat ion, as shown in t he following scr eenshot .

When downloading fr om Fir efox , you ll be pr esent ed wit h t he following window.

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.

Opening the IDE


To r un t he Selenium - I DE, sim ply select it fr om t he Fir efox Tools m enu. I t opens as follows wit h an em pt y scr ipt - edit ing window and a m enu for loading, or cr eat ing new t est cases.

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 .

Pause/ Resum e: Allows st opping and r e- st ar t ing of a r unning t est case.

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.

Recor d: Recor ds t he user s br owser act ions.

Test Case Pane


Your scr ipt is displayed in t he t est case pane. I t has t wo t abs, one for displaying t he com m and and t heir param et er s in a r eadable t able for m at .

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.

Building Test Cases


Ther e ar e t hr ee pr im ar y m et hods for developing t est cases. Fr equent ly, a t est developer will r equir e all t hr ee t echniques.

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.

Adding Verifications and Asserts With the Context Menu


Your t est cases will also need t o check t he pr oper t ies of a web- page. This r equir es assert and verify com m ands. We won t descr ibe t he specifics of t hese com m ands her e; t hat is in the chapter on Selenium Com m ands Selenese . Her e we ll sim ply descr ibe how t o add them to your test case. Wit h Selenium - I DE r ecor ding, go t o t he br owser display ing your t est applicat ion and r ight click any wher e on t he page. You will see a cont ex t m enu showing verify and/or assert commands. The fir st t im e you use Selenium , t her e m ay only be one Selenium com m and list ed. As you use t he I DE however, you will find addit ional com m ands will quick ly be added t o t his menu. Selenium - I DE will at t em pt t o pr edict what com m and, along wit h t he par am et er s, you will need for a select ed UI elem ent on t he cur r ent web- page. Let s see how t his wor k s. Open a web- page of your choosing and select a block of t ex t on t he page. A par agr aph or a heading will wor k fine. Now, r ight - click t he select ed t ex t . The cont ex t m enu should give you a verifyTextPresent command and the suggested parameter should be t he t ex t it self. Also, not ice t he Show All Available Com m ands m enu opt ion. This shows m any, m any m or e com m ands, again, along wit h suggest ed par am et er s, for t est ing your cur r ent ly select ed UI elem ent . Tr y a few m or e UI elem ent s. Tr y r ight - click ing an im age, or a user cont r ol like a but ton or a check box . You m ay need t o use Show All Available Com m ands t o see opt ions ot her t han verifyTextPresent. Once you select t hese ot her opt ions, t he m or e com m only used ones will show up on t he pr im ar y cont ext m enu. For ex am ple, select ing verifyElementPresent for an im age should lat er cause t hat com m and t o be available on t he pr im ar y cont ext m enu t he nex t t im e you select an im age and r ight - click . Again, t hese com m ands will be ex plained in det ail in t he chapt er on Selenium com m ands. For now t hough, feel fr ee t o use t he I DE t o r ecor d and select com m ands int o a t est case and t hen r un it . You can lear n a lot about t he Selenium com m ands sim ply by ex per im ent ing wit h t he I DE.

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 .

Opening and Saving a Test Case


Like m ost pr ogr am s, t her e ar e Save and Open com m ands under t he File m enu. However, Selenium dist inguishes bet ween t est cases and t est suit es. To save your Selenium - I DE tests for lat er use you can eit her save t he indiv idual t est cases, or save t he t est suit e. If the test cases of your t est suit e have not been saved, you ll be pr om pt ed t o save t hem befor e sav ing t he t est suit e. When you open an exist ing t est case or suit e, Selenium - I DE displays it s Selenium com m ands in t he Test Case Pane.

Running Test Cases


The I DE allows m any opt ions for r unning your t est case. You can r un a t est case all at once, st op and st ar t it , r un it one line at a t im e, r un a single com m and you ar e cur r ent ly developing, and you can do a bat ch r un of an ent ir e t est suit e. Execut ion of t est cases is ver y flexible in the IDE. Run a Test Case Click t he Run but t on t o r un t he cur r ent ly displayed t est case. Run a Test Suite Click t he Run All but t on t o r un all t he t est cases in t he cur r ent ly loaded t est suit e. Stop and Start The Pause but t on can be used t o st op t he t est case while it is r unning. The icon of t his but t on t hen changes t o indicat e t he Resum e but t on. To cont inue click Resum e. Stop in the Middle You can set a br eak point in t he t est case t o cause it t o st op on a par t icular com m and. This is useful for debugging your t est case. To set a br eak point , select a com m and, r ight - click, and fr om t he cont ex t m enu select Toggle Br eakpoint . Start from the Middle You can t ell t he I DE t o begin r unning fr om a specific com m and in t he m iddle of t he t est case. This also is used for debugging. To set a st ar t point , select a com m and, r ight - click , and from t he cont ex t m enu select Set / Clear St ar t Point . Run Any Single Command Double- click any single com m and t o r un it by it self. This is useful when wr it ing a single com m and. I t let s you im m ediat ely t est a com m and you ar e const r uct ing, when you ar e not sur e if it is cor r ect . You can double- click it t o see if it r uns cor r ect ly. This is also available from the context menu.

Using Base URL to Run Test Cases in Different Domains


The Base URL field at t he t op of t he Selenium - I DE window is ver y useful for allowing t est cases t o be r un acr oss differ ent dom ains. Suppose t hat a sit e nam ed ht t p: / / news.por t al.com had an in- house bet a sit e nam ed ht t p: / / bet a.news.por t al.com . Any t est cases for t hese sit es t hat begin wit h an open st at em ent should specify a relative URL as the argument to open rather than an absolute URL ( one st ar t ing wit h a pr ot ocol such as ht t p: or ht t ps: ) . Selenium - I DE will t hen cr eat e an absolut e URL by appending t he open com m and s ar gum ent ont o t he end of t he value of Base URL. For ex am ple, t he t est case below would be r un against ht t p: / / news.por t al.com / about .ht m l:

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

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

28/05/2013 7:23

Selenium-IDE

Selenium Documentation

http://docs.selenium hq.org/docs/02_selenium _ide.jsp

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 .

Commonly Used Selenium Commands


To conclude our int r oduct ion of Selenium , we ll show you a few t y pical Selenium com m ands. These ar e pr obably t he m ost com m only used com m ands for building t est s. open opens a page using a URL. click/clickAndWait per for m s a click oper at ion, and opt ionally wait s for a new page t o load. verifyTitle/assertTitle ver ifies an ex pect ed page t it le. verifyTextPresent ver ifies ex pect ed t ex t is som ewher e on t he page. verifyElementPresent ver ifies an ex pect ed UI elem ent , as defined by it s HTML t ag, is pr esent on t he page. verifyText ver ifies ex pect ed t ex t and it s cor r esponding HTML t ag ar e pr esent on t he page. verifyTable ver ifies a t able s ex pect ed cont ent s. waitForPageToLoad pauses execut ion unt il an ex pect ed new page loads. Called aut om at ically when click AndWait is used. 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.

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.

Verifying Page Elements


Ver ify ing UI elem ent s on a web page is pr obably t he m ost com m on feat ur e of your aut om ated t est s. Selenese allows m ult iple way s of check ing for UI elem ent s. I t is im por t ant t hat you under st and t hese differ ent m et hods because t hese m et hods define what you ar e act ually t est ing. For ex am ple, will you t est t hat ... 1. an elem ent is pr esent som ewher e on t he page? 2. specific t ex t is som ewher e on t he page? 3. specific t ex t is at a specific locat ion on t he page? For ex am ple, if you ar e t est ing a t ex t heading, t he t ex t and it s posit ion at t he t op of the page ar e pr obably r elevant for your t est . I f, however, you ar e t est ing for t he ex ist ence of an im age on t he hom e page, and t he web designer s fr equent ly change t he specific im age file along wit h it s posit ion on t he page, t hen you only want t o t est t hat an image ( as opposed t o t he specific im age file) ex ist s somewhere 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" />

xpath=/html/body/form[1] (3) - Absolute path (would break if the HTML was

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

and t he value loginFor m


xpath=//form[input/@name='username'] (3) - First form element with an input child

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>

link=Continue (4) link=Cancel (5)

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

Matching Text Patterns


Like locat or s, patterns ar e a t y pe of par am et er fr equent ly r equir ed by Selenese com m ands. Ex am ples of com m ands which r equir e pat t er ns ar e verifyTextPresent, verifyTitle, verifyAlert, assertConfirmation, verifyText, and verifyPrompt. And as has been m ent ioned above, link locat or s can ut ilize a pat t er n. Pat t er ns allow you t o describe, via t he use of special char act er s, what t ex t is ex pect ed r at her t han hav ing t o specify t hat t ex t ex act ly. There are three types of patterns: globbing, regular expressions, and exact.

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

Let s ex am ine t he r egular ex pr ession above one par t at a t im e:


Sunrise: * [0-9]{1,2} : [0-9]{2} [ap]m

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.

The AndWait Commands


The differ ence bet ween a com m and and it s AndWait alt er nat ive is t hat t he r egular com m and (e.g. click) will do t he act ion and cont inue wit h t he following com m and as fast as it can, while the AndWait alt er nat ive ( e.g. clickAndWait) t ells Selenium t o wait for t he page t o load aft er t he act ion has been done. The AndWait alt er nat ive is alway s used when t he act ion causes t he br owser t o nav igat e t o anot her page or r eload t he pr esent one. Be awar e, if you use an AndWait com m and for an act ion t hat does not t r igger a nav igat ion/ r efr esh, your t est will fail. This happens because Selenium will r each t he AndWait s t im eout wit hout seeing any nav igat ion or r efr esh being m ade, causing Selenium t o r aise a t im eout except ion.

The waitFor Commands in AJAX applications


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,

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 .

Sequence of Evaluation and Flow Control


When a scr ipt r uns, it sim ply r uns in sequence, one com m and aft er anot her. Selenese, by it self, does not suppor t condit ion st at em ent s ( if- else, et c.) or it er at ion ( for, while, et c.) . Many useful t est s can be conduct ed wit hout flow cont r ol. However, for a funct ional t est of dy nam ic cont ent , possibly involv ing m ult iple pages, pr ogr am m ing logic is oft en needed. When flow cont r ol is needed, t her e ar e t hr ee opt ions: 1. Run t he scr ipt using Selenium - RC and a client libr ar y such as Java or PHP t o ut ilize the pr ogr am m ing language s flow cont r ol feat ur es. 2. Run a sm all JavaScr ipt snippet fr om wit hin t he scr ipt using t he st or eEval com m and. 3. I nst all t he got o_sel_ide.j s ex t ension. Most t est er s will ex por t t he t est scr ipt int o a pr ogr am m ing language file t hat uses t he Selenium - RC API ( see t he Selenium - I DE chapt er ) . However, som e or ganizat ions pr efer t o run t heir scr ipt s fr om Selenium - I DE whenever possible ( for inst ance, when t hey have m any j unior - level people r unning t est s for t hem , or when pr ogram m ing sk ills ar e lacking) . I f t his is your case, consider a JavaScr ipt snippet or t he got o_sel_ide.j s ex t ension.

Store Commands and Selenium Variables


You can use Selenium var iables t o st or e const ant s at t he beginning of a scr ipt . Also, when com bined wit h a dat a- dr iven t est design ( discussed in a lat er sect ion) , Selenium var iables can be used t o st or e values passed t o your t est pr ogr am fr om t he com m and- line, fr om anot her pr ogr am , or fr om a file. The plain store com m and is t he m ost basic of t he m any st or e com m ands and can be used t o sim ply st or e a const ant value in a selenium var iable. I t t akes t wo par am et er s, t he t ex t value t o be st or ed and a selenium var iable. Use t he st andar d var iable nam ing convent ions of only alphanum er ic char act er s when choosing a nam e for your var iable. Command store Target Value

paul@m y sit e.org userName

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.

JavaScript and Selenese Parameters


JavaScr ipt can be used wit h t wo t y pes of Selenese par am et er s: scr ipt and non- scr ipt ( usually ex pr essions) . I n m ost cases, you ll want t o access and/ or m anipulat e a t est case var iable inside t he JavaScr ipt snippet used as a Selenese par am et er. All var iables cr eat ed in your t est case 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 ] .

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 ] .

JavaScript Usage with Script Parameters


Sever al Selenese com m ands specify a script par am et er including assertEval, verifyEval, storeEval, and waitForEval. These par am et er s r equir e no special sy nt ax . A Selenium - I DE user would sim ply place a snippet of JavaScr ipt code int o t he appr opr iat e field, nor m ally t he Target field ( because a script param et er is nor m ally t he fir st or only par am et er ) . The ex am ple below illust r at es how a JavaScr ipt snippet can be used t o per for m a sim ple num er ical calculat ion: Command store storeEval Target 10 st or edVar s[ hit s ] - st or edVar s[ block quot es ] Value hit s block quot es paragraphs

storeXpathCount / / block quot 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

st or edVar s[ nam e ] .t oUpper Case( ) uc st or edVar s[ nam e ] .t oLower Case( ) lc

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( ) }

echo - The Selenese Print Command


Selenese has a sim ple com m and t hat allows you t o pr int t ex t t o your t est s out put . This is useful for pr ov iding infor m at ional pr ogr ess not es in your t est which display on t he console as your t est is r unning. These not es also can be used t o pr ov ide cont ex t wit hin your t est r esult r epor t s, which can be useful for finding wher e a defect ex ist s on a page in t he event your test finds a pr oblem . Finally, echo st at em ent s can be used t o pr int t he cont ent s of Selenium var iables. Command echo echo Target Test ing page foot er now. User nam e is Value

Alerts, Popups, and Multiple Windows


Suppose t hat you ar e t est ing a page t hat look s like t his.

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.

Breakpoints and Startpoints


The Sel- I DE suppor t s t he set t ing of br eak point s and t he abilit y t o st ar t and st op t he r unning of a t est case, fr om any point wit hin t he t est case. That is, one can r un up t o a specific com m and in t he m iddle of t he t est case and inspect how t he t est case behaves at t hat point . To do t his, set a br eakpoint on t he com m and j ust befor e t he one t o be ex am ined. To set a br eak point , select a com m and, r ight - click , and fr om t he cont ex t m enu select Toggle Breakpoint. Then click t he Run but t on t o r un your t est case fr om t he beginning up t o t he br eak point . I t is also som et im es useful t o r un a t est case fr om som ewher e in t he m iddle t o t he end of t he t est case or up t o a br eak point t hat follows t he st ar t ing point . For ex am ple, suppose your t est case fir st logs int o t he websit e and t hen per for m s a ser ies of t est s and you are t r y ing t o debug one of t hose t est s. However, you only need t o login once, but you need to keep r er unning your t est s as you ar e developing t hem . You can login once, t hen r un your t est case fr om a st ar t point placed aft er t he login por t ion of your t est case. That will pr event you fr om hav ing t o m anually logout each t im e you r er un your t est case. To set a st ar t point , select a com m and, r ight - click, and fr om t he cont ext m enu select Set/Clear Start Point. Then click t he Run but t on t o execut e t he t est case beginning at t hat st ar t point .

Stepping Through a Testcase


To execut e a t est case one com m and at a t im e ( st ep t hr ough it ) , follow t hese st eps: 1. St ar t t he t est case r unning wit h t he Run but t on fr om t he t oolbar.

2. I m m ediat ely pause t he execut ing t est case wit h t he Pause but t on.

3. Repeat edly select t he St ep 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.

Page Source for Debugging


Oft en, when debugging a t est case, you sim ply m ust look at t he page sour ce ( t he HTML for t he webpage you r e t r y ing t o t est ) t o det er m ine a pr oblem . Fir efox m akes t his easy. Sim ply r ight - click t he webpage and select View- > Page Sour ce. The HTML opens in a separ at e window. Use it s Sear ch feat ur e ( Edit = > Find) t o sear ch for a key wor d t o find t he HTML for t he UI elem ent you r e t r y ing t o t est . Alt er nat ively, select j ust t hat por t ion of t he webpage for which you want t o see t he source. Then r ight - click t he webpage and select View Select ion Sour ce. I n t his case, t he separate HTML window will cont ain j ust a sm all am ount of sour ce, wit h highlight ing on t he por t ion r epr esent ing your select ion.

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.

Writing a Test Suite


A t est suit e is a collect ion of t est cases which is displayed in t he left m ost pane in the IDE. The t est suit e pane can be m anually opened or closed v ia select ing a sm all dot halfway down the r ight edge of t he pane ( which is t he left edge of t he ent ir e Selenium - I DE window if t he pane is closed) . The t est suit e pane will be aut om at ically opened when an ex ist ing t est suit e is opened or when t he user select s t he New Test Case it em fr om t he File m enu. I n t he lat t er case, t he new test case will appear im m ediat ely below t he pr ev ious t est case. Selenium - I DE also suppor t s loading pr e- ex ist ing t est cases by using t he File - > Add Test Case m enu opt ion. This allows you t o add ex ist ing t est cases t o a new t est suit e. A t est suit e file is an HTML file cont aining a one- colum n t able. Each cell of each r ow in t he < t body > sect ion cont ains a link t o a t est case. The ex am ple below is of a t est suit e cont aining four test cases:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Sample Selenium Test Suite</title> </head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td>Test Cases for De Anza A-Z Directory Links</td></tr> </thead> <tbody> <tr><td><a href="./a.html">A Links</a></td></tr> <tr><td><a href="./b.html">B Links</a></td></tr> <tr><td><a href="./c.html">C Links</a></td></tr> <tr><td><a href="./d.html">D Links</a></td></tr> </tbody> </table> </body> </html>

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.

Executing Selenium-IDE Tests on Different Browsers


While Selenium - I DE can only r un t est s against Fir efox , t est s developed wit h Selenium - IDE can be r un against ot her br owser s, using a sim ple com m and- line int er face t hat invokes t he Selenium - RC ser ver. This t opic is cover ed in t he Run Selenese tests sect ion on Selenium - RC chapter. The -htmlSuite com m and- line opt ion is t he par t icular feat ur e of int er est .

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.

How Does WebDriver Drive the Browser Compared to Selenium-RC?


Selenium -WebDr iver m akes dir ect calls t o t he br owser using each br owser s nat ive suppor t for aut om at ion. How t hese dir ect calls ar e made, and the features they support depends on the browser you are using. I nfor m at ion on each br owser dr iver is pr ovided lat er in t his chapter. For t hose fam iliar wit h Selenium - RC, t his is quit e differ ent fr om what you ar e used t o. Selenium - RC wor ked t he sam e way for each suppor t ed br owser. I t inj ect ed j avascr ipt funct ions int o t he br owser when t he br owser was loaded and t hen used it s j avascr ipt t o dr ive t he AUT wit hin t he br owser. WebDr iver does not use t his t echnique. Again, it dr ives t he br owser dir ect ly using t he br owser s built in suppor t for aut om at ion.

WebDriver and the Selenium-Server


You m ay, or m ay not , need t he Selenium Ser ver, depending on how you int end t o use Selenium -WebDr iver. I f you will be only using t he WebDr iver API you do not need t he Selenium - Ser ver. I f your br owser and t est s will all r un on t he sam e m achine, and your t est s only use t he WebDr iver API , t hen you do not need t o r un t he Selenium - Ser ver ; WebDr iver will r un t he br owser dir ect ly. Ther e ar e som e r easons t hough t o use t he Selenium - Ser ver wit h Selenium -WebDr iver. You ar e using Selenium - Gr id t o dist r ibut e your t est s over m ult iple m achines or vir t ual m achines ( VMs) . You want t o connect t o a r em ot e m achine t hat has a par t icular br owser ver sion t hat is not on your cur r ent m achine. You ar e not using t he Java bindings ( i.e. Pyt hon, C# , or Ruby) and would like t o use Ht m lUnit Dr iver

Setting Up a Selenium-WebDriver Project


To inst all Selenium m eans t o set up a pr oj ect in a developm ent so you can wr it e a pr ogram using Selenium . How you do t his depends on your pr ogram m ing language and your developm ent envir onm ent . 1 de 18

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

developer s in your or ganizat ion can help you get up t o speed.

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

Migrating from Selenium 1.0


For t hose who alr eady have t est suit es wr it t en using Selenium 1.0, we have pr ovided t ips on how t o m igrat e your exist ing code t o Selenium 2.0. Sim on St ewar t , t he lead developer for Selenium 2.0, has wr it t en an ar t icle on m igrat ing fr om Selenium 1.0. We ve included t his as an appendix. Migrating From Selenium RC to Selenium WebDriver

Introducing the Selenium-WebDriver API by Example


WebDr iver is a t ool for aut om at ing web applicat ion t est ing, and in par t icular t o ver ify t hat t hey wor k as expect ed. I t aim s t o pr ovide a fr iendly API t hat s easy t o explor e and under st and, easier t o use t han t he Selenium - RC ( 1.0) API , which will help t o m ake your t est s easier t o r ead and m aint ain. I t s not t ied t o any par t icular t est fram ewor k, so it can be used equally well in a unit t est ing or fr om a plain old m ain m et hod. This sect ion int r oduces WebDr iver s API and helps get you st ar t ed becom ing fam iliar wit h it . St ar t by set t ing up a WebDr iver pr oj ect if you haven t alr eady. This was descr ibed in t he pr evious sect ion, Set t ing Up a Selenium - WebDr iver Pr oj ect . Once your pr oj ect is set up, you can see t hat WebDr iver act s j ust as any nor m al librar y: it is ent ir ely self- cont ained, and you usually don t need t o r em em ber t o st ar t any addit ional pr ocesses or r un any inst aller s befor e using it , as opposed t o t he pr oxy ser ver wit h Selenium - RC. Not e: addit ional st eps ar e r equir ed t o use Chr om e Dr iver, Opera Dr iver, Andr oid Dr iver and iPhone Dr iver You r e now r eady t o wr it e som e code. An easy way t o get st ar t ed is t his exam ple, which sear ches for t he t er m Cheese on Google and t hen out put s t he r esult page s t it le t o t he console.

from from from from

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.

Selenium-WebDriver API Commands and Operations


Fetching a Page
The fir st t hing you r e likely t o want t o do wit h WebDr iver is navigat e t o a page. The nor m al way t o do t his is by calling get :

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.

Locating UI Elements (WebElements)


Locat ing elem ent s in WebDr iver can be done on t he WebDr iver inst ance it self or on a WebElem ent . Each of t he language bindings expose a Find Elem ent and Find Elem ent s m et hod. The fir st r et ur ns a WebElem ent obj ect ot her wise it t hr ows an except ion. The lat t er r et ur ns a list of WebElem ent s, it can r et ur n an em pt y list if no DOM elem ent s m at ch t he quer y. 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.

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>

element = driver.find_element_by_id("coolestWidgetEvah") or from selenium.webdriver.common.by import By element = driver.find_element(by=By.ID, value="coolestWidgetEvah"

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"

cheeses = driver.find_elements_by_class_name("cheese") or from selenium.webdriver.common.by import By cheeses = driver.find_elements(By.CLASS_NAME, "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>

frame = driver.find_element_by_tag_name("iframe") or from selenium.webdriver.common.by import By frame = driver.find_element(By.TAG_NAME, "iframe")

6 de 18

28/05/2013 7:37

Selenium WebDriver

Selenium Documentation

http://docs.seleniumhq.org/docs/03_webdriver.jsp

from selenium.webdriver.common.by import By frame = driver.find_element(By.TAG_NAME, "iframe")

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"/>

cheese = driver.find_element_by_name("cheese") or from selenium.webdriver.common.by import By cheese = driver.find_element(By.NAME, "cheese")

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>>

cheese = driver.find_element_by_link_text("cheese") or from selenium.webdriver.common.by import By cheese = driver.find_element(By.LINK_TEXT, "cheese")

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

cheese = driver.find_element_by_partial_link_text("cheese") or from selenium.webdriver.common.by import By cheese = driver.find_element(By.PARTIAL_LINK_TEXT, "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

Driver Ht m lUnit Dr iver

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

This is a lit t le abst ract , so for t he following piece of HTML:


<input type="text" name="example" /> <INPUT type="text" name="other" />

inputs = driver.find_elements_by_xpath("//input") or from selenium.webdriver.common.by import By inputs = driver.find_elements(By.XPATH, "//input")

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

Selenium Documentation / / input //INPUT 1 ( exam ple ) 0 2 2

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:

element = driver.execute_script("return $('.cheese')[0]")

Finding all t he input elem ent s t o t he ever y label on a page:

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'))

User Input - Filling In Forms


We ve alr eady seen how t o ent er t ext int o a t ext ar ea or t ext field, but what about t he ot her elem ent s? You can t oggle t he st at e of checkboxes, and you can use click t o set som et hing like an OPTI ON t ag select ed. Dealing wit h SELECT t ags isn t t oo bad:

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()

Moving Between Windows and Frames


Som e web applicat ions have m any fram es or m ult iple windows. WebDr iver suppor t s m oving bet ween nam ed windows using t he swit chTo m et hod:

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 :

<a href="somewhere.html" target="windowName">Click here to open a new wi

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:

for handle in driver.window_handles: driver.switch_to_window(handle)

You can also swit ch fr om fram e t o fram e ( or int o ifram es) :

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:

alert = driver.switch_to_alert() # usage: alert.dismiss(), etc.

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.

Navigation: History and Location


Ear lier, we cover ed navigat ing t o a page using t he get com m and ( driver.get("http://www.example.com")) As you ve seen, WebDr iver has a num ber of sm aller, t ask- focused int er faces, and navigat ion is a useful t ask. Because loading a page is such a fundam ent al r equir em ent , t he m et hod t o do t his lives on t he m ain WebDr iver int er face, but it s sim ply a synonym t o:

driver.get("http://www.example.com")

# python doesn't have driver.navig

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()

Changing the User Agent


This is easy wit h t he Fir efox Dr iver :

Drag And Drop


Her e s an exam ple of using t he Act ions class t o per for m a drag and dr op. Nat ive event s ar e r equir ed t o be enabled.

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()

Driver Specifics and Tradeoffs Selenium-WebDriver s Drivers


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: 12 de 18

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

driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver

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:

driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver

13 de 18

28/05/2013 7:37

Selenium WebDriver

Selenium Documentation

http://docs.seleniumhq.org/docs/03_webdriver.jsp

driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver

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 :

profile = webdriver.FirefoxProfile() profile.native_events_enabled = True driver = webdriver.Firefox(profile)

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.

Internet Explorer Driver


This dr iver is cont r olled by a .dll and is t hus only available on Windows OS. Each Selenium r elease has it s cor e funct ionalit y t est ed against ver sions 6, 7 and 8 on XP , and 9 on Windows7. Usage

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.

Alternative Back-Ends: Mixing WebDriver and RC Technologies


WebDriver-Backed Selenium-RC
The Java ver sion of WebDr iver pr ovides an im plem ent at ion of t he Selenium - RC API . These m eans t hat you can use t he under lying WebDr iver t echnology using t he Selenium - RC API . This is pr im ar ily pr ovided for backwar ds com pat ibilit y. I t allows t hose who have exist ing t est suit es using t he Selenium - RC API t o use WebDr iver under t he cover s. I t s pr ovided t o help ease t he m igrat ion pat h t o Selenium -WebDr iver. Also, t his allows one t o use bot h API s, side- by- side, in t he sam e t est code. Selenium -WebDr iver is used like t his:

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

Backing WebDriver with Selenium


WebDr iver doesn t suppor t as m any br owser s as Selenium RC does, so in or der t o pr ovide t hat suppor t while st ill using t he WebDr iver API, you can make use of the SeleneseCommandExecutor Safar i is suppor t ed in t his way wit h t he following code ( be sur e t o disable pop- up blocking) :

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.

Running Standalone Selenium Server for use with RemoteDrivers


From Selenium s Download page download selenium - ser ver st andalone- < ver sion> .j ar and opt ionally I EDr iver Ser ver. I f you plan t o wor k wit h Chr om e, download it fr om Google Code. Unpack I EDr iver Ser ver and/ or chr om edr iver and put t hem in a dir ect or y which is on t he $PATH / % PATH% - t he Selenium Ser ver should t hen be able t o handle r equest s for I E / Chr om e wit hout addit ional m odificat ions. St ar t t he ser ver on t he com m and line wit h
java -jar <path_to>/selenium-server-standalone-<version>.jar

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

For ot her com m and line opt ions, execut e


java -jar <path_to>/selenium-server-standalone-<version>.jar -help

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

WebDriver: Advanced Usage

Selenium Documentation

http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

WebDriver: Advanced Usage


Explicit and Implicit Waits
Wait ing is hav ing t he aut om at ed t ask execut ion elapse a cer t ain am ou nt of t im e befor e cont inuing wit h t h e nex t st ep.

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.

from from from from

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

ff = webdriver.Firefox() ff.get("http://somedomain/url_that_delays_loading") try: element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By finally: ff.quit()

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.

from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) element = wait.until(EC.element_to_be_clickable((By.Id,'someid')))

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.

from selenium import webdriver

1 de 4

ff = webdriver.Firefox()

28/05/2013 7:37

WebDriver: Advanced Usage

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

from selenium import webdriver

driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilitie driver.get("http://www.google.com") driver.get_screenshot_as_file('/Screenshots/google.png')

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

Windows n/a n/a Y 7

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

Browser Startup Manipulation


2 de 4
Todo

28/05/2013 7:37

WebDriver: Advanced Usage

Selenium Documentation

http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

Browser Startup Manipulation


Todo Topics t o be included: r est or ing cook ies ch anging fir efox pr ofile r u nning br owser s wit h plugins

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

WebDriver: Advanced Usage

Selenium Documentation

http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

driver = webdriver.Firefox(proxy=proxy) # for remote caps = webdriver.DesiredCapabilities.FIREFOX proxy.add_to_capabilities(caps) driver = webdriver.Remote(desired_capabilities=caps)

Opera Todo

HTML5
Todo

Parallelizing Your Test Runs


Todo

Navigation

4 de 4

28/05/2013 7:37

Selenium 1 (Selenium RC)

Selenium Documentation

http://docs.seleniumhq.org/docs/05_selenium_rc.jsp

Selenium 1 (Selenium RC)


Introduction
As you can r ead in Br ief Hist or y of The Selenium Pr oj ect , Selenium RC was the main Selenium pr oj ect for a long t im e, befor e t he WebDr iver / Selenium m er ge br ought up Selenium 2, t he newest and m or e power ful t ool. Selenium 1 is st ill act ively suppor t ed ( m ost ly in m aint enance m ode) and pr ov ides som e feat ur es t hat m ay not be available in Selenium 2 for a while, including suppor t for several languages ( Java, Javascr ipt , Ruby, PHP , Py t hon, Per l and C# ) and suppor t for alm ost every br owser out t her e.

How Selenium RC Works


Fir st , we will descr ibe how t he com ponent s of Selenium RC operat e and t he r ole each plays in running your test scripts.

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 1 (Selenium RC)

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.

Installing Selenium Server


The Selenium RC ser ver is sim ply a Java jar file ( selenium - ser v er - st andalone- < v er sionnum ber > .j ar ) , which doesn t r equir e any special inst allat ion. Just downloading t he zip file and ex t ract ing t he ser ver in t he desir ed dir ect or y is sufficient .

Running Selenium Server


Befor e st ar t ing any t est s you m ust st ar t t he ser ver. Go t o t he dir ect or y wher e Selenium RC s ser ver is locat ed and r un t he following fr om a com m and- line console. j ava - j ar selenium - ser ver - st andalone- < ver sion- num ber > .j ar This can be sim plified by cr eat ing a bat ch or shell execut able file ( .bat on Windows and .sh on Linux ) cont aining t he com m and above. Then m ake a shor t cut t o t hat execut able on your desk t op and sim ply double- click t he icon t o st ar t t he ser ver. For t he ser ver t o r un you ll need Java inst alled and t he PATH envir onm ent var iable correctly configur ed t o r un it fr om t he console. You can check t hat you have Java cor r ect ly inst alled by r unning t he following on a console. java -version I f you get a ver sion num ber ( which needs t o be 1.5 or lat er ) , you r e r eady t o st ar t using Selenium RC.

Using the Java Client Driver


Download Selenium j ava client dr iver zip fr om t he Selenium HQ downloads page. Ex t ract selenium - j ava- < ver sion- num ber > .j ar file Open your desir ed Java I DE ( Eclipse, Net Beans, I nt elliJ, Net weaver, et c.) Create a java project. Add t he selenium - j ava- < ver sion- num ber > .j ar files t o your pr oj ect as r efer ences. Add t o your pr oj ect classpat h t he file selenium - j ava- < ver sion- num ber > .j ar. Fr om Selenium -I DE, ex por t a scr ipt t o a Java file and include it in your Java pr oj ect , or wr it e your Selenium t est in Java using t he selenium - j ava- client API . The API is pr esent ed lat er in t his chapt er. You can eit her use JUnit , or Test Ng t o r un your t est , or you can wr it e your own sim ple m ain( ) pr ogram . These concept s ar e ex plained lat er in t his sect ion. Run Selenium ser ver fr om t he console. Execut e your t est fr om t he Java I DE or fr om t he com m and- line. For det ails on Java t est pr oj ect configur at ion, see t he Appendix sect ions Configur ing Selenium RC With Eclipse and Configuring Selenium RC With Intellij.

Using the Python Client Driver


I nst all Selenium v ia PI P , inst r uct ions linked at Selenium HQ downloads page Eit her wr it e your Selenium t est in Py t hon or ex por t a scr ipt fr om Selenium -I DE t o a py t hon file. Run Selenium ser ver fr om t he console Execut e your t est fr om a console or your Py t hon I DE 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.

2 de 17

Using the .NET Client Driver

28/05/2013 7:25

Selenium 1 (Selenium RC)

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.

Using the .NET Client Driver


Download Selenium RC from the SeleniumHQ downloads page Ex t ract t he folder Download and inst all NUnit ( Not e: You can use NUnit as your t est engine. I f you r e not fam iliar yet wit h NUnit , you can also wr it e a sim ple m ain( ) funct ion t o r un your t est s; however NUnit is ver y useful as a t est engine.) Open your desir ed .Net I DE ( Visual St udio, Shar pDevelop, MonoDevelop) Cr eat e a class librar y ( .dll) Add r efer ences t o t he following DLLs: nm ock .dll, nunit .cor e.dll, nunit . fram ewor k .dll, Thought Wor ks.Selenium .Cor e.dll, Thought Wor ks.Selenium .I nt egrat ionTest s.dll and Thought Wor ks.Selenium .Unit Test s.dll Wr it e your Selenium t est in a .Net language ( C# , VB.Net ) , or ex por t a scr ipt fr om Selenium - I DE t o a C# file and copy t his code int o t he class file you j ust cr eat ed. Wr it e your own sim ple m ain( ) pr ogram or you can include NUnit in your pr oj ect for r unning your t est . These concept s ar e ex plained lat er in t his chapt er. Run Selenium ser ver fr om console Run your t est eit her fr om t he I DE, fr om t he NUnit GUI or fr om t he com m and line For specific det ails on .NET client dr iver configurat ion wit h Visual St udio, see t he appendix .NET client dr iv er configur at ion .

Using the Ruby Client Driver


I f you do not alr eady have Ruby Gem s, inst all it fr om RubyForge Run gem install selenium-client At t he t op of your t est scr ipt , add require "selenium/client" Wr it e your t est scr ipt using any Ruby t est har ness ( eg Test : : Unit , Mini: : Test or RSpec). Run Selenium RC ser ver fr om t he console. Execut e your t est in t he sam e way you would r un any ot her Ruby scr ipt . For det ails on Ruby client dr iver configurat ion, see t he Selenium - Client docum ent at ion

From Selenese to a Program


The pr im ar y t ask for using Selenium RC is t o conver t your Selenese int o a pr ogram m ing language. I n t his sect ion, we pr ov ide several differ ent language- specific ex am ples.

Sample Test Script


Let s st ar t wit h an ex am ple Selenese t est scr ipt . I m agine r ecor ding t he following t est with Selenium-IDE. open type click AndWait / q btnG selenium rc

assertTextPresent Result s * for selenium r c Note: This example would work with the Google search page http://www.google.com

Selenese as Programming Code


Her e is t he t est scr ipt ex por t ed ( via Selenium -I DE) t o each of t he suppor t ed pr ogram m ing languages. I f you have at least basic k nowledge of an obj ect - or ient ed pr ogram m ing language, you will under st and how Selenium r uns Selenese com m ands by r eading one of t hese ex am ples. To see an ex am ple in a specific language, select one of t hese but t ons.

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 1 (Selenium RC)

Selenium Documentation

http://docs.seleniumhq.org/docs/05_selenium_rc.jsp

def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors)

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.

Programming Your Test


Now we ll illust rat e how t o pr ogram your own t est s using exam ples in each of t he suppor t ed pr ogram m ing languages. Ther e ar e essent ially t wo t ask s: Generat e your scr ipt int o a pr ogram m ing language fr om Selenium -I DE, opt ionally m odify ing t he r esult . Wr it e a ver y sim ple m ain pr ogram t hat execut es t he generat ed code. Opt ionally, you can adopt a t est engine plat for m like JUnit or Test NG for Java, or NUnit for .NET if you ar e using one of t hose languages. Her e, we show language- specific ex am ples. The language- specific API s t end t o differ from one t o anot her, so you ll find a separat e ex planat ion for each. Java C# Python Ruby Perl, PHP

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/")

The generat ed code will look similar t o t his.

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 1 (Selenium RC)

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.

Learning the API


The Selenium RC API uses nam ing convent ions t hat , assum ing you under st and Selenese, m uch of t he int er face will be self- ex planat or y. Her e, however, we explain t he m ost cr it ical and possibly less obv ious aspect s.

Starting the Browser

self.selenium = selenium("localhost", 4444, "*firefox", "http://www.google.com/") self.selenium.start()

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 1 (Selenium RC)

Selenium Documentation

http://docs.selenium hq.org/docs/05_selenium _rc.jsp

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.

Test Framework Reporting Tools


Test fram ewor k s ar e available for m any pr ogram m ing languages. These, along wit h t heir pr im ar y funct ion of pr ov iding a flex ible t est engine for execut ing your t est s, include librar y code for r epor t ing r esult s. For ex am ple, Java has t wo com m only used t est fram ewor k s, JUnit and Test NG. .NET also has it s own, NUnit . We won t t each t he fram ewor k s t hem selves her e; t hat s beyond t he scope of t his user guide. We will sim ply int r oduce t he fram ewor k feat ur es t hat r elat e t o Selenium along wit h som e t echniques you can apply. Ther e ar e good book s available on t hese t est fram ewor k s however along wit h infor m at ion on t he int er net .

Test Report Libraries


Also available ar e t hir d- par t y librar ies specifically cr eat ed for r epor t ing t est r esults in your chosen pr ogram m ing language. These oft en suppor t a var iet y of for m at s such as HTML or PDF.

What s The Best Approach?


Most people new t o t he t est ing fram ewor ks will begin wit h t he fram ewor k s built - in r epor t ing feat ur es. Fr om t her e m ost will ex am ine any available librar ies as t hat s less time consum ing t han developing your own. As you begin t o use Selenium no doubt you will st art put t ing in your own pr int st at em ent s for r epor t ing pr ogr ess. That m ay gradually lead to you developing your own r epor t ing, possibly in parallel t o using a librar y or t est framework. Regar dless, aft er t he init ial, but shor t , lear ning cur ve you will nat urally develop what works best for your own sit uat ion.

Test Reporting Examples


To illust rat e, we ll dir ect you t o som e specific t ools in som e of t he ot her languages suppor t ed by Selenium . The ones list ed her e ar e com m only used and have been used ex t ensively ( and t her efor e r ecom m ended) by t he aut hor s of t his guide. Test Reports in Java I f Selenium Test cases ar e developed using JUnit t hen JUnit Repor t can be used t o generate test reports. Refer to JUnit Repor t for specifics. I f Selenium Test cases ar e developed using Test NG t hen no ex t er nal t ask is r equir ed t o generat e t est r epor t s. The Test NG fr am ewor k gener at es an HTML r epor t 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, 28/05/2013 colour-coded view of the test results. See ReportNG for more.

6 de 17

7:25

Selenium 1 (Selenium RC)

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

Adding Some Spice to Your Tests


Now we ll get t o t he whole r eason for using Selenium RC, adding pr ogram m ing logic t o your t est s. I t s t he sam e as for any pr ogram . Pr ogram flow is cont r olled using condit ion statements and it erat ion. I n addit ion you can r epor t pr ogr ess infor m at ion using I / O. I n t his sect ion we ll show som e ex am ples of how pr ogram m ing language const r uct s can be com bined wit h Selenium t o solve com m on t est ing pr oblem s. You will find as you t ransit ion fr om t he sim ple t est s of t he ex ist ence of page elem ents to tests of dy nam ic funct ionalit y involv ing m ult iple web- pages and var y ing dat a t hat you will require pr ogram m ing logic for ver ify ing ex pect ed r esult s. Basically, t he Selenium -I DE does not support it erat ion and st andar d condit ion st at em ent s. You can do som e condit ions by em bedding j avascr ipt in Selenese param et er s, however it erat ion is im possible, and m ost condit ions will be m uch easier in a pr ogram m ing language. I n addit ion, you m ay need except ion handling for er r or r ecover y. For t hese r easons and ot her s, we have wr it t en t his sect ion t o illust rate the use of com m on pr ogram m ing t echniques t o give you gr eat er ver ificat ion power in your aut omated testing. The ex am ples in t his sect ion ar e wr it t en in C# and Java, alt hough t he code is sim ple and can be easily adapt ed t o t he ot her suppor t ed languages. I f you have som e basic knowledge of an obj ect - or ient ed pr ogram m ing language you shouldn t have difficult y under st anding t his section.

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

assertTextPresent Result s * for selenium r c

assertTextPresent Result s * for selenium ide

7 de 17

28/05/2013 7:25

Selenium 1 (Selenium RC)

Selenium Documentation

http://docs.seleniumhq.org/docs/05_selenium_rc.jsp

click AndWait type click AndWait

btnG q btnG selenium grid

assertTextPresent Result s * for selenium ide

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:

I f elem ent q is not on t he page t hen an except ion is t hr own:

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.

Executing JavaScript from Your Test


JavaScr ipt com es ver y handy in exer cising an applicat ion which is not dir ect ly suppor ted by selenium. The getEval m et hod of selenium API can be used t o execut e JavaScr ipt fr om selenium RC. Consider an applicat ion having check boxes wit h no st at ic ident ifier s. I n t his case one could evaluat e JavaScr ipt fr om selenium RC t o get ids of all check boxes and t hen exer cise them.

To count number of images on a 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

To see t he list of opt ions, r un t he ser ver wit h t he -h option.


$ java -jar selenium-server-standalone-<version-number>.jar -h

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 1 (Selenium RC)

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.

$ java -jar selenium-server-standalone-<version-number>.jar -Dhttp.proxyHost=proxy.com -Dhttp.proxyPo

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 1 (Selenium RC)

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

Specifying the Firefox Profile


Fir efox will not r un t wo inst ances sim ult aneously unless you specify a separat e pr ofile for each inst ance. Selenium RC 1.0 and lat er r uns in a separat e pr ofile aut om at ically, so if you ar e using Selenium 1.0, you can pr obably sk ip t his sect ion. However, if you r e using an older ver sion of Selenium or if you need t o use a specific pr ofile for your t est s ( such as adding an ht t ps cer t ificat e or hav ing som e addons inst alled) , you will need t o ex plicit ly specify the profile. Fir st , t o cr eat e a separat e Fir efox pr ofile, follow t his pr ocedur e. Open t he Windows Start m enu, select Run , t hen t ype and ent er one of t he following:
firefox.exe -profilemanager firefox.exe -P

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

Run Selenese Directly Within the Server Using -htmlSuite


You can r un Selenese ht m l files dir ect ly wit hin t he Selenium Ser ver by passing t he ht m l file t o t he ser ver s com m and line. For inst ance:
java -jar selenium-server-standalone-<version-number>.jar -htmlSuite "*firefox" "http://www.google.com" "c:\absolute\path\to\my\HTMLSuite.html" "c:\absolute\path\to\my\results.html"

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.

Selenium Server Logging


Server-Side Logs When launching selenium ser ver t he -log opt ion can be used t o r ecor d valuable debugging information reported by the Selenium Server to a text file.
java -jar selenium-server-standalone-<version-number>.jar -log selenium.log

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

The m essage for m at is


TIMESTAMP(HH:mm:ss) LEVEL [THREAD] LOGGER - MESSAGE

This m essage m ay be m ult iline.

10 de 17

Browser-Side Logs

28/05/2013 7:25

Selenium 1 (Selenium RC)

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.

Specifying the Path to a Specific Browser


You can specify t o Selenium RC a pat h t o a specific br owser. This is useful if you have different ver sions of t he sam e br owser and you wish t o use a specific one. Also, t his is used t o allow your t est s t o r un against a br owser not dir ect ly suppor t ed by Selenium RC. When specifying t he r un m ode, use t he * cust om specifier followed by t he full pat h t o t he br owser s executable:
*custom <path to browser>

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.

The Same Origin Policy


The m ain r est r ict ion t hat Selenium faces is t he Sam e Or igin Policy. This secur it y r est r ict ion is applied by ever y br owser in t he m ar ket and it s obj ect ive is t o ensur e t hat a sit e s content will never be accessible by a scr ipt fr om anot her sit e. The Sam e Or igin Policy dict at es that any code loaded wit hin t he br owser can only operat e wit hin t hat websit e s dom ain. I t cannot per for m funct ions on anot her websit e. So for ex am ple, if t he br owser loads JavaScr ipt code when it loads www.m y sit e.com , it cannot r un t hat loaded code against www.m y sit e2.com even if t hat s anot her of your sit es. I f t his wer e possible, a scr ipt placed on any websit e you open would be able t o r ead infor m at ion on your bank account if you had t he account page opened on ot her t ab. This is called XSS ( Cr oss- sit e Scr ipt ing) . To wor k wit hin t his policy, Selenium - Cor e ( and it s JavaScr ipt com m ands t hat m ake all the m agic happen) m ust be placed in t he sam e or igin as t he Applicat ion Under Test ( sam e URL). Hist or ically, Selenium - Cor e was lim it ed by t his pr oblem since it was im plem ent ed in JavaScr ipt . Selenium RC is not , however, r est r ict ed by t he Sam e Or igin Policy. I t s use of the Selenium Ser ver as a pr ox y avoids t his pr oblem . I t , essent ially, t ells t he br owser t hat the br owser is wor k ing on a single spoofed websit e t hat t he Ser ver pr ov ides. Note You can find addit ional infor m at ion about t his t opic on Wik ipedia pages about Sam e Or igin Policy and XSS.

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 1 (Selenium RC)

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 .

Heightened Privileges Browsers


This wor k flow in t his m et hod is ver y sim ilar t o Pr ox y I nj ect ion but t he m ain differ ence is t hat t he br owser s ar e launched in a special m ode called Heightened Privileges, which allows websit es t o do t hings t hat ar e not com m only per m it t ed ( as doing XSS, or filling file upload input s and pr et t y useful st uff for Selenium ) . By using t hese br owser m odes, Selenium Core is able t o dir ect ly open t he AUT and r ead/ int eract wit h it s cont ent wit hout hav ing t o pass t he whole AUT t hr ough t he Selenium RC ser ver. Her e is t he ar chit ect ural diagram .

12 de 17

28/05/2013 7:25

Selenium 1 (Selenium RC)

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 .

Handling HTTPS and Security Popups


Many applicat ions swit ch fr om using HTTP t o HTTPS when t hey need t o send encr y pt ed infor m at ion such as passwor ds or cr edit car d infor m at ion. This is com m on wit h m any of t oday s web applicat ions. Selenium RC suppor t s t his. To ensur e t he HTTPS sit e is genuine, t he br owser will need a secur it y cer t ificat e. Ot herwise, when t he br owser accesses t he AUT using HTTPS, it will assum e t hat applicat ion is not t r ust ed . When t his occur s t he br owser displays secur it y popups, and t hese popups cannot be closed using Selenium RC. When dealing wit h HTTPS in a Selenium RC t est , you m ust use a r un m ode t hat suppor t s this and handles t he secur it y cer t ificat e for you. You specify t he r un m ode when your t est pr ogram init ializes Selenium . I n Selenium RC 1.0 bet a 2 and lat er use * fir efox or * iex plor e for t he r un m ode. I n ear lier ver sions, including Selenium RC 1.0 bet a 1, use * chr om e or * ieht a, for t he r un m ode. Using t hese r un m odes, you will not need t o inst all any special secur it y cer t ificat es; Selenium RC will handle it for you. I n ver sion 1.0 t he r un m odes * fir efox or * iexplor e ar e r ecom m ended. However, t her e ar e addit ional r un m odes of * iex plor epr ox y and * fir efox pr ox y. These ar e pr ov ided for back wards com pat ibilit y only, and should not be used unless r equir ed by legacy t est pr ogr am s. Their use will pr esent lim it at ions wit h secur it y cer t ificat e handling and wit h t he r unning of m ult iple windows if your applicat ion opens addit ional br owser windows. I n ear lier ver sions of Selenium RC, * chr om e or * ieht a wer e t he r un m odes t hat suppor t ed HTTPS and t he handling of secur it y popups. These wer e consider ed ex per im ent al m odes alt hough t hey becam e quit e st able and m any people used t hem . I f you ar e using Selenium 1.0 you do not need, and should not use, these older run modes.

Security Certificates Explained


Nor m ally, your br owser will t r ust t he applicat ion you ar e t est ing by inst alling a secur it y cer t ificat e which you alr eady own. You can check t his in your br owser s opt ions or I nt er net pr oper t ies ( if you don t k now your AUT s secur it y cer t ificat e ask your syst em adm inistrator). When Selenium loads your br owser it inj ect s code t o int er cept m essages bet ween t he br owser and t he ser ver. The br owser now t hink s unt r ust ed soft war e is t r y ing t o look like your applicat ion. I t r esponds by aler t ing you wit h popup m essages. To get ar ound t his, Selenium RC, ( again when using a r un m ode t hat suppor t t his) will 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.

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 1 (Selenium RC)

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.

Supporting Additional Browsers and Browser Configurations


The Selenium API suppor t s r unning against m ult iple br owser s in addit ion t o I nt er net Explorer and Mozilla Fir efox . See t he Selenium HQ.or g websit e for suppor t ed br owser s. I n addit ion, when a br owser is not dir ect ly suppor t ed, you m ay st ill r un your Selenium t est s against a br owser of your choosing by using t he * cust om r un- m ode ( i.e. in place of * fir efox or * iexplor e) when your t est applicat ion st ar t s t he br owser. Wit h t his, you pass in t he path to the br owser s execut able wit hin t he API call. This can also be done fr om t he Ser ver in int eract ive mode.

cmd=getNewBrowserSession&1=*custom c:\Program Files\Mozilla Firefox\MyBrowser.exe&2=http://www.google.co

Running Tests with Different Browser Configurations


Nor m ally Selenium RC aut om at ically configur es t he br owser, but if you launch t he br owser using t he * cust om r un m ode, you can for ce Selenium RC t o launch t he br owser as- is, wit hout using an aut om at ic configurat ion. For ex am ple, you can launch Fir efox wit h a cust om configurat ion like t his:

cmd=getNewBrowserSession&1=*custom c:\Program Files\Mozilla Firefox\firefox.exe&2=http://www.google.c

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.

Troubleshooting Common Problems


When get t ing st ar t ed wit h Selenium RC t her e s a few pot ent ial pr oblem s t hat ar e com m only encount er ed. We pr esent t hem along wit h t heir solut ions her e.

Unable to Connect to Server


When your t est pr ogram cannot connect t o t he Selenium Ser ver, Selenium t hr ows an except ion in your t est pr ogram . I t should display t his m essage or a sim ilar one:
"Unable to connect to remote server (Inner Exception Message: No connection could be made because the target machine actively refused it )" (using .NET and XP Service Pack 2)

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.

Unable to Load the Browser


Ok, not a fr iendly er r or m essage, sor r y, but if t he Selenium Ser ver cannot load t he browser you will likley see t his er r or.
(500) Internal Server Error

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

http://docs.selenium hq.org/docs/05_selenium _rc.jsp

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.

Selenium Cannot Find the AUT


I f your t est pr ogram st ar t s t he br owser successfully, but t he br owser doesn t display the websit e you r e t est ing, t he m ost likely cause is your t est pr ogram is not using t he correct URL. This can easily happen. When you use Selenium - I DE t o ex por t your scr ipt , it inser t s a dum m y URL. You m ust m anually change t he URL t o t he cor r ect one for your applicat ion t o be tested.

Firefox Refused Shutdown While Preparing a Profile


This most often occurs when your run your Selenium RC test program against Firefox, but you alr eady have a Fir efox br owser session r unning and, you didn t specify a separat e pr ofile when you st ar t ed t he Selenium Ser ver. The er r or fr om t he t est pr ogram look s like this:
Error: java.lang.RuntimeException: Firefox refused shutdown while preparing a profile

Her e s t he com plet e er r or m essage fr om t he ser ver :


16:20:03.919 INFO - Preparing Firefox profile... 16:20:27.822 WARN - GET /selenium-server/driver/?cmd=getNewBrowserSession&1=*fir efox&2=http%3a%2f%2fsage-webapp1.qa.idc.com HTTP/1.1 java.lang.RuntimeException: Firefox refused shutdown while preparing a profile at org.openqa.selenium.server.browserlaunchers.FirefoxCustomProfileLaunc her.waitForFullProfileToBeCreated(FirefoxCustomProfileLauncher.java:277) ... Caused by: org.openqa.selenium.server.browserlaunchers.FirefoxCustomProfileLaunc her$FileLockRemainedException: Lock file still present! C:\DOCUME~1\jsvec\LOCALS ~1\Temp\customProfileDir203138\parent.lock

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.

Error message: (Unsupported major.minor version 49.0) while starting server


This er r or say s you r e not using a cor r ect ver sion of Java. The Selenium Ser ver r equires Java 1.5 or higher. To check double- check your j ava ver sion, r un t his fr om t he com m and line.
java -version

You should see a message showing the Java version.


java version "1.5.0_07" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_07-b03) Java HotSpot(TM) Client VM (build 1.5.0_07-b03, mixed mode)

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.

404 error when running the getNewBrowserSession command


I f you r e get t ing a 404 er r or while at t em pt ing t o open a page on http://www.google.com / selenium - ser ver / , t hen it m ust be because t he Selenium Ser ver was not cor r ect ly configur ed as a pr ox y. The selenium - ser ver dir ect or y doesn t ex ist on google.com ; it only appear s t o ex ist when t he pr ox y is pr oper ly configur ed. Pr oxy Configurat ion highly depends on how t he br owser is launched wit h * fir efox, * iex plor e, * opera, or * cust om . * iex plor e: I f t he br owser is launched using * iex plor e, you could be hav ing a pr oblem wit h I nt er net Ex plor er s pr ox y set t ings. Selenium Ser ver at t em pt s To configur e t he global pr oxy set t ings in t he I nt er net Opt ions Cont r ol Panel. You m ust make sure that those are correctly configured when Selenium Ser ver launches t he br owser. Tr y looking at your I nt er net Opt ions cont r ol panel. Click on t he Connect ions t ab and click 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

15 de 17

28/05/2013 7:25

Selenium 1 (Selenium RC)

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.

Permission Denied Error


The m ost com m on r eason for t his er r or is t hat your session is at t em pt ing t o v iolat e t he sam e- or igin policy by cr ossing dom ain boundar ies ( e.g., accesses a page fr om ht t p: / / dom ain1 and then accesses a page from http://domain2) or swit ching pr ot ocols ( m ov ing fr om http://domainX to https://domainX). This er r or can also occur when JavaScr ipt at t em pt s t o find UI obj ect s which ar e not yet available ( befor e t he page has com plet ely loaded) , or ar e no longer available ( aft er the page has st ar t ed t o be unloaded) . This is m ost t y pically encount er ed wit h AJAX pages which ar e wor k ing wit h sect ions of a page or subfram es t hat load and/ or r eload independent ly of t he lar ger page. This er r or can be int er m it t ent . Oft en it is im possible t o r epr oduce t he pr oblem wit h a debugger because t he t r ouble st em s fr om race condit ions which ar e not r epr oducible when t he debugger s over head is added t o t he sy st em . Per m ission issues ar e cover ed in som e det ail in t he t ut or ial. Read t he sect ion about t he The Sam e Or igin Policy, Pr ox y I nj ect ion car efully.

Handling Browser Popup Windows


Ther e ar e sever al k inds of Popups t hat you can get dur ing a Selenium t est . You m ay not be able t o close t hese popups by r unning selenium com m ands if t hey ar e init iat ed by t he browser and not your AUT. You may need to know how to manage these. Each type of popup needs t o be addr essed differ ent ly. HTTP basic aut hent icat ion dialogs: These dialogs pr om pt for a user nam e/ passwor d t o login t o t he sit e. To login t o a sit e t hat r equir es HTTP basic authentication, use a username and password in the URL, as descr ibed in RFC 1738, like t his: open( ht t p: / / m y user nam e: m y user passwor d@m yex am ple.com / blah/ blah /blah ) . SSL cer t ificat e war nings: Selenium RC aut om at ically at t em pt s t o spoof SSL cer t ificat es when it is enabled as a pr ox y ; see m or e on t his in t he sect ion on HTTPS. I f your br owser is configur ed cor r ect ly, you should never see SSL certificate warnings, but you may need to configure your br owser t o t r ust our danger ous Cy ber Villains SSL cer t ificat e aut hor it y. Again, r efer t o t he HTTPS sect ion for how t o do t his. m odal JavaScr ipt aler t / confir m at ion/ pr om pt dialogs: Selenium t r ies t o conceal t hose dialogs fr om you ( by r eplacing window.aler t , window.confir m and window.pr om pt ) so t hey won t st op t he execut ion of your page. I f you r e seeing an aler t pop- up, it s pr obably because it fir ed dur ing t he page load pr ocess, which is usually t oo ear ly for us t o pr ot ect t he page. Selenese cont ains com m ands for asser t ing or ver ify ing aler t and confir m at ion popups. See t he sect ions on t hese t opics in Chapt er 4.

On Linux, why isn t my Firefox browser session closing?


On Unix / Linux you m ust invoke fir efox- bin dir ect ly, so m ake sur e t hat execut able is on t he pat h. I f execut ing Fir efox t hr ough a shell scr ipt , when it com es t im e t o k ill t he browser Selenium RC will k ill t he shell scr ipt , leav ing t he br owser r unning. You can specify the path t o fir efox- bin dir ect ly, like t his.
cmd=getNewBrowserSession&1=*firefox /usr/local/firefox/firefox-bin&2=http://www.google.com

Firefox *chrome doesn t work with custom profile


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.

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 1 (Selenium RC)

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.

Problems With Verify Commands


If you export your tests from Selenium-IDE, you may find yourself getting empty verify st r ings fr om your t est s ( depending on t he pr ogram m ing language used) . Note: This section is not yet developed.

Safari and MultiWindow Mode


Note: This section is not yet developed.

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"

IE and Style Attributes


I f you ar e r unning your t est s on I nt er net Ex plor er and you cannot locat e elem ent s using their style at t r ibut e. For ex am ple:
//td[@style="background-color:yellow"]

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");

Where can I Ask Questions that Aren t Answered Here?


Tr y our user gr oup

17 de 17

28/05/2013 7:25

Test Design Considerations

Selenium Documentation

http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp

Introducing Test Design


We ve pr ovided in t his chapt er infor m at ion t hat will be useful t o bot h t hose new t o t est aut om at ion and for t he exper ienced QA pr ofessional. Her e we descr ibe t he m ost com m on t ypes of aut om at ed t est s. We also descr ibe design pat t er ns com m only used in t est aut om at ion for im pr oving t he m aint enance and ext ensibily of your aut om at ion suit e. The m or e exper ienced r eader will find t hese int er est ing if not alr eady using t hese t echniques.

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 Static Content


The sim plest t ype of t est , a content test, is a sim ple t est for t he exist ence of a st at ic, non- changing, UI elem ent . For inst ance Does each page have it s expect ed page t it le? This can be used t o ver ify your t est found an expect ed page aft er following a link. Does t he applicat ion s hom e page cont ain an im age expect ed to be at the top of the page? Does each page of t he websit e cont ain a foot er ar ea wit h links t o t he com pany cont act page, pr ivacy policy, and t radem ar ks infor m at ion? Does each page begin wit h heading t ext using t he < h1> t ag? And, does each page have t he cor r ect t ext wit hin t hat header ? You m ay or m ay not need cont ent t est s. I f your page cont ent is not likely t o be affect ed t hen it m ay be m or e efficient t o t est page cont ent m anually. I f, for exam ple, your applicat ion involves files being m oved t o differ ent locat ions, cont ent t est s m ay pr ove valuable.

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

Test Design Considerations

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.

Testing Dynamic Elements


Oft en a web page elem ent has a unique ident ifier used t o uniquely locat e t hat elem ent wit hin t he page. Usually t hese ar e im plem ent ed using t he ht m l t ag s id at t r ibut e or it s nam e at t r ibut e. These nam es can be a st at ic, i.e unchanging, st r ing const ant . They can also be dynam ically generat ed values t hat var y each inst ance of t he page. For exam ple, som e web ser ver s m ight nam e a displayed docum ent doc3861 one inst ance of a page, and doc6148 on a differ ent inst ance of t he page depending on what docum ent t he user was r et r ieving. A t est scr ipt ver ifying t hat a docum ent exist s m ay not have a consist ent ident ifier t o use for locat ing t hat docum ent . Oft en, dynam ic elem ent s wit h var ying ident ifier s ar e on som e t ype of r esult page based on a user act ion. This t hough cer t ainly depends on t he funct ion of t he web applicat ion. Her e s an exam ple.
<input type="checkbox" value="true" id="addForm:_ID74:_ID75:0:_ID79:0: checkBox"/>

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

Test Design Considerations

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.

Trade-offs: assertTextPresent, assertElementPresent, assertText


You should now be fam iliar wit h t hese com m ands, and t he m echanics of using t hem . I f not , please r efer t o Chapt er 3 fir st . When const r uct ing your t est s, you will need t o decide Do I only check t hat t he t ext exist s on t he page? ( verify/assertTextPresent) Do I only check t hat t he HTML elem ent exist s on t he page? That is, t he t ext , im age, or ot her cont ent is not t o be checked, only t he HTML t ag is what is r elevant . ( verify/assertElementPresent) Must I t est bot h, t he elem ent and it s t ext cont ent ? ( verify/assertText) Ther e is no r ight answer. I t depends on t he r equir em ent s for your t est . Which, of cour se, depend on t he r equir em ent s for t he applicat ion you r e t est ing. I f in doubt , use assertText since t his is t he st r ict est t ype of checkpoint . You can always change it lat er but at least you won t be m issing any pot ent ial failur es. Verify/assertText is t he most specific test t ype. This can fail if eit her t he HTML elem ent ( t ag) OR t he t ext is not what your t est is expect ing. Per haps your web- designer s ar e fr equent ly changing t he page and you don t want your t est t o fail ever y t im e t hey do t his because t he changes t hem selves ar e expect ed per iodically. However, assum e you st ill need t o check t hat something is on t he page, say a paragraph, or heading t ext , or an im age. I n t his case you can use verify/assertElementPresent. I t will ensur e t hat a par t icular t ype of elem ent exist s ( and if using XPat h can ensur e it exist s r elat ive t o ot her obj ect s wit hin t he page) . But you don t car e what t he cont ent is. You only car e t hat a specific elem ent , say, an im age, is at a specific locat ion. 3 de 10 7:35 Get t ing a feel for t hese t ypes of decisions will com e wit h t im e and28/05/2013 a

Test Design Considerations

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.

Locating Dynamic Elements


As was descr ibed ear lier in t he sect ion on t ypes of t est s, a dynam ic elem ent is a page elem ent whose ident ifer var ies wit h each inst ance of t he page. For exam ple,

<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

Test Design Considerations

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

Or, in Selenium 1.0

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.

<input type="checkbox" value="true" id="addForm:_ID74:_ID75:0:_ID79:0:ch name="addForm:_ID74:_ID75:0:_ID79:0:checkBox"/>

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

Or, again in Selenium - RC

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

Test Design Considerations

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 .

Locating Ajax Elements


As was pr esent ed in t he Test Types subsect ion above, a page elem ent im plem ent ed wit h Aj ax is an elem ent t hat can be dynam ically r efr eshed wit hout having t o r efr esh t he ent ir e page. The best way t o locat e and ver ify an Aj ax elem ent is t o use t he Selenium 2.0 WebDr iver API . I t was specifically designed t o addr ess t est ing of Aj ax elem ent s wher e Selenium 1 has som e lim it at ions. I n Selenim 2.0 you use t he wait For ( ) m et hod t o wait for a page elem ent t o becom e available. The param et er is a By obj ect which is how WebDr iver im plem ent s locat or s. This is explained in det ail in t he WebDr iver chapt er s. To do t his wit h Selenium 1.0 ( Selenium - RC) a bit m or e coding is involved, but it isn t difficult . The appr oach is t o check for t he elem ent , if it s not available wait for a pr edefined per iod and t hen again r echeck it . This is t hen execut ed wit h a loop wit h a pr edet er m ined t im e- out t er m inat ing t he loop if t he elem ent isn t found. Let s consider a page which br ings a link ( link= aj axLink) on click of a but t on on page ( wit hout r efr eshing t he page) This could be handled by Selenium using a for loop.

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.

Wrapping Selenium Calls


As wit h any pr ogram m ing, you will want t o use ut ilit y funct ions t o handle code t hat would ot her wise be duplicat ed t hr oughout your t est s. One way t o pr event t his is t o wrap fr equent ly used selenium calls wit h funct ions or class m et hods of your own design. For exam ple, m any t est s will fr equent ly click on a page elem ent and wait for page t o load m ult iple t im es wit hin a t est .

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.

Safe Operations for Element Presence


Anot her com m on usage of wrapping Selenium m et hods is t o check for pr esence of an elem ent on page befor e car r ying out som e operat ion. This is som et im es called a safe operat ion . For inst ance, t he following m et hod could be used t o im plem ent a safe operat ion t hat depends on an expect ed elem ent being pr esent .

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

Test Design Considerations

Selenium Documentation t his.

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

Test Design Considerations

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.

Page Object Design Pattern


Page Obj ect is a Design Pat t er n which has becom e popular in t est aut om at ion for enhancing t est m aint enance and r educing code duplicat ion. A page obj ect is an obj ect- or ient ed class t hat ser ves as an int er face t o a page of your AUT. The t est s t hen use t he m et hods of t his page obj ect class whenever t hey need t o int eract wit h t hat page of t he UI . The benefit is t hat if t he UI changes for t he page, t he t est s t hem selves don t need t o change, only t he code wit hin t he page obj ect needs t o change. Subsequent ly all changes t o suppor t t hat new UI ar e locat ed in one place. The Page Obj ect Design Pat t er n pr ovides t he following advant ages. 1. Ther e is clean separat ion bet ween t est code and page specific code such as locat or s ( or t heir use if you r e using a UI m ap) and layout . 2. Ther e is single r eposit or y for t he ser vices or operat ions offer ed by t he page rat her t han having t hese ser vices scat t er ed t hr ough out t he tests. I n bot h cases t his allows any m odificat ions r equir ed due t o UI changes t o all be m ade in one place. Useful infor m at ion on t his t echnique can be found on num er ous blogs as t his t est design pat t er n is becom ing widely used. We encourage the reader who wishes to know more to search the internet for blogs on this subject. Many have wr it t en on t his design pat t er n and can pr ovide useful t ips beyond t he scope of t his user guide. To get you st ar t ed, t hough, we ll illust rat e page obj ect s wit h a sim ple exam ple. Fir st , consider an exam ple, t ypical of t est aut om at ion, t hat does not use a page object.

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

Test Design Considerations

Selenium Documentation

http://docs.seleniumhq.org/docs/06_test_design_considerations.jsp had t o use t his login page.

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.

Data Driven Testing


Dat a Dr iven Test ing r efer s t o using t he sam e t est ( or t est s) m ult iple t im es wit h var ying dat a. These dat a set s ar e oft en fr om ext er nal files i.e. .csv file, t ext file, or per haps loaded fr om a dat abase. Dat a dr iven t est ing is a com m only used t est aut om at ion t echnique used t o validat e an applicat ion against m any var ying input . When t he t est is designed for var ying dat a, t he input dat a can expand, essent ially cr eat ing addit ional t est s, wit hout r equir ing changes t o t he t est code. In Python:

9 de 10

# Collection of String values source = open("input_file.txt", "r") values = source.readlines() source.close()

28/05/2013 7:35

Test Design Considerations

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.

How Selenium-Grid Works With a Hub and Nodes


A gr id consist s of a single hub, and one or m or e nodes. Bot h ar e st ar t ed using t he selenium - ser ver.j ar execut able. We ve list ed som e exam ples in t he following sect ions of t his chapt er. The hub r eceives a t est t o be execut ed along wit h infor m at ion on which br owser and plat for m ( i.e. WI NDOWS, LI NUX, et c) wher e t he t est should be r un. I t knows t he configurat ion of each node t hat has been r egist er ed t o t he hub. Using t his infor m at ion it select s an available node t hat has t he r equest ed br owser - plat for m com binat ion. Once a node has been select ed, Selenium com m ands init iat ed by t he t est ar e send t he t he hub, which passes t hem t o t he node assigned t o t hat t est . The node r uns t he br owser, and execut es t he Selenium com m ands wit hin t hat br owser against t he applicat ion under t est . A diagram illust rat es t his. Refer t o t he second diagram on t his page ( t he fir st one is illust rat ing Selenium - RC) . The second diagram was for Selenium - Gr id 1, however it st ill applies and is a good illust rat ion of what we r e descr ibing her e. The only differ ence is one of t er m inology. Replace t he t er m Selenium Rem ot e Cont r ol wit h Selenium - Gr id node t he diagram will m at ch our descr ipt ion for Selenium - Gr id 2.

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

You should see t he following logging out put .

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

Specifying the Port


The default por t used by t he hub is 4444. The por t being r efer r ed t o hear, is t he TCP/ I P por t used when t he client , t hat is, t he aut om at ed t est s connect t o t he Selenium - Gr id hub. I f anot her applicat ion on your com put er is alr eady using t his por t , or if, you alr eady have a Selenium - Ser ver st ar t ed, you ll see t he following m essage in t he log out put .

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.

Node Configuration Timing Parameters Getting Command-Line Help


The Selenium - Ser ver pr ovides list ings of available opt ions wit h a br ief descr ipt ion of each. Cur r ent ly ( sum m er 2012) , t he com m and- line help has som e oddit ies, but it can be helpful if you know wher e t o look and how t o int er pr et t he infor m at ion. 4 de 6 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 28/05/2013 7:26

Selenium-Grid

Selenium Documentation how t o int er pr et t he infor m at ion.

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.

Prototype generates additional commands


All getFoo and isFoo m et hods on t he Selenium pr ot ot ype aut om at ically r esult in t he availabilit y of st or eFoo, asser t Foo, asser t Not Foo, ver ifyFoo, ver ifyNot Foo, wait For Foo, and wait For Not Foo com m ands. Exam ple, if you add a getTextLength() m et hod, t he following com m ands will aut om at ically be available: storeTextLength, assertTextLength, assertNotTextLength, verifyTextLength, verifyNotTextLength, waitForTextLength, and waitForNotTextLength commands.

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.

Using User-Extensions With Selenium-IDE


User - ext ensions ar e ver y easy t o use wit h t he selenium I DE. 1. Cr eat e your user ext ension and save it as user - ext ensions.j s. While t his nam e isn t t echnically necessar y, it s good pract ice t o keep t hings consist ent . 2. Open Fir efox and open Selenium -I DE. 3. Click on Tools, Opt ions 4. I n Selenium Cor e Ext ensions click on Br owse and find t he user - ext ensions. j s file. Click on OK. 5. Your user - ext ension will not yet be loaded, you m ust close and r est ar t Selenium - I DE. 6. I n your em pt y t est , cr eat e a new com m and, your user - ext ension should now be an opt ions in t he Com m ands dr opdown.

Using User-Extensions With Selenium RC


I f you Google Selenium RC user - ext ension t en t im es you will find t en differ ent appr oaches t o using t his feat ur e. Below, is t he official Selenium suggest ed appr oach.

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 WebDriver Cheat Sheet

Selenium Documentation

http://docs.seleniumhq.org/docs/appendix_cheat_sheet.jsp

Role Based Interfaces in Selenium WebDriver


One of t he differ ences bet ween Selenium RC and Selenium WebDr iver is t hat t he WebDr iver API s m ake ext ensive use of r ole- based int er faces t o allow user s t o det er m ine whet her a par t icular dr iver suppor t s a feat ur e. This can m ake it har d t o know what feat ur es ar e available wit hout fir st knowing which int er face t o t r y and use. The key int er faces ar e list ed below. Interface HasCapabilit ies Role Pr ovides access t o t he capabilit ies suppor t ed by t his dr iver. Documentation Java HasCapabilit ies.j ava

Javascr ipt Execut or Allows t he execut ion of ar bit r ar y JS commands. Rot at able

Java Javascr ipt Execut or.j ava

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

How to Install the Android Driver

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

.NET client driver configuration

Selenium Documentation

http://docs.seleniumhq.org/docs/appendix_installing_dotnet_driver_client.jsp

.NET client driver configuration


.NET client Dr iver can be used wit h Micr osoft Visual St u dio. To Configur e it wit h Visual St udio do as Following. Launch Visual St u dio an d nav igat e t o File > New > Pr oj ect .

Select Visual C# > Class Libr ar y > Nam e your pr oj ect > Click on OK but t on.

A Class ( .cs) is cr eat ed. Renam e it as appr opr iat e.

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

.NET client driver configuration

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

Wit h This Visual St u dio is r eady for Seleniu m Test Cases.

Navigation

2 de 2

28/05/2013 7:28

Importing Sel2.0 Project into Eclipse using Maven

Selenium Document...

http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...

Importing Sel2.0 Project into Eclipse using Maven


Once y ou hav e cr eat ed your pom .x m l file in your pr oj ect , you can have m aven aut ogenerate the pr oj ect files necessar y for eclipse wit h a sim ple com m and:
mvn eclipse:eclipse

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 .

Importing Sel2.0 Project into IntelliJ Using Maven


We are currently working on this appendix. The information provided here is accurate, although it may not be finished. I n t his appendix we pr ov ide t he st eps, including scr een capt ur es, showing how t o cr eate a Selenium 2.0 j ava client- dr iver pr oj ect in I nt elliJ I DEA. These st eps assum e you have alr eady used m aven wit h a pom .x m l file t o set up t he pr oj ect . This pr ocess is descr ibed in t he Selenium 2.0 chapt er. You m ust have followed t hat pr ocess befor e you can per for m t hese st eps. This appendix t hen shows you how t o im por t t he m aven- cr eat ed Selenium 2.0 j ava pr oj ect int o I nt elliJ. Fir st , open I nt elliJ and fr om t he ent r y page, click Cr eat e New Pr oj ect .

Fr om t he New Pr oj ect dialog select I m por t Pr oj ect fr om Ex t er nal Model.

1 de 8

28/05/2013 7:29

Importing Sel2.0 Project into Eclipse using Maven

Selenium Document...

http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...

Fr om t he list of pr oj ect t y pes, select m av en.

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.

Click t he ... but t on t o set t he r oot folder.

2 de 8

28/05/2013 7:29

Importing Sel2.0 Project into Eclipse using Maven

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.

Enter a name for your project.

3 de 8

28/05/2013 7:29

Importing Sel2.0 Project into Eclipse using Maven

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

Importing Sel2.0 Project into Eclipse using Maven

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

Importing Sel2.0 Project into Eclipse using Maven

Selenium Document...

http://docs.seleniumhq.org/docs/appendix_installing_java_driver_Sel20_...

And select Cr eat e Module.

I n t he dialog select t he radio but t on Cr eat e Module Fr om Scr at ch.

Select Java Module and ent er a nam e for t he new m odule.

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

Importing Sel2.0 Project into Eclipse using Maven

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

Importing Sel2.0 Project into Eclipse using Maven

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.

Ent er t he class nam e.

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 1.0 Java Client Driver Configuration

Selenium Documentation

http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp

Selenium 1.0 Java Client Driver Configuration


I n General configurat ion of Selenium - RC wit h any j ava I DE would hav e following st eps: Download Seleniu m - RC fr om t he Selenium HQ downloads page Start any java IDE Create new project Add selenium - j ava- < ver sion- num ber > .j ar t o y our pr oj ect classpat h Recor d your t est fr om Selenium - I DE and t ranslat e it t o j ava code ( Selenium I DE has aut om at ic t r anslat ion feat u r e t o generat e t est s in var iet y of languages) Run selenium ser ver fr om console Run your test in the IDE These point s hav e been delineat ed below wit h r efer ence t o Eclipse and I nt elliJ:

Configuring Selenium-RC With Eclipse


Eclipse is a m ult i- language soft war e developm ent plat for m com pr ising an I DE and a plu g- in sy st em t o ex t en d it . I t is wr it t en pr im ar ily in Java and is used t o develop applicat ions in t his language and, by m eans of t he var ious plug- ins, in ot her languages as well as C/ C+ + , Cobol, Py t hon, Per l, PHP and m or e. Following lines descr ibes configur at ion of Selenium - RC wit h Eclipse - Ver sion: 3.3.0. (Europa Release) . I t sh ould not be t oo differ ent for higher ver sions of Eclipse Laun ch Eclipse. Select File > New > Ot her.

Java > Java Project > Next

1 de 9

28/05/2013 7:29

Selenium 1.0 Java Client Driver Configuration

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 1.0 Java Client Driver Configuration

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 1.0 Java Client Driver Configuration

Selenium Documentation

http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp

Right click on sr c folder and click on New > Folder

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 1.0 Java Client Driver Configuration

Selenium Documentation

http://docs.selenium hq.org/docs/appendix_installing_java_driver_client.jsp

Following t he sam e st eps cr eat e core folder inside com

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 1.0 Java Client Driver Configuration

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)

This would cr eat e lib folder in Pr oj ect dir ect or y.

6 de 9

28/05/2013 7:29

Selenium 1.0 Java Client Driver Configuration

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 1.0 Java Client Driver Configuration

Selenium Documentation

http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp

Aft er hav ing added j ar files click on OK but t on.

Added librar ies would appear in Pack age Ex plor er as following:

8 de 9

28/05/2013 7:29

Selenium 1.0 Java Client Driver Configuration

Selenium Documentation

http://docs.seleniumhq.org/docs/appendix_installing_java_driver_client.jsp

Configuring Selenium-RC With Intellij


Watch t his ex cellent t ut or ial by Sim on St ewar t on st ar t in g a Selenium pr oj ect wit h I nt elliJ

Navigation

9 de 9

28/05/2013 7:29

Python Client Driver Configuration

Selenium Documentation

http://docs.seleniumhq.org/docs/appendix_installing_python_driver_client.jsp

Python Client Driver Configuration


Download Selenium - RC fr om t he Selenium HQ downloads page Ex t r act t he file selenium.py Eit her wr it e your Selenium t est in Pyt hon or expor t a scr ipt fr om Selenium - I DE t o a python file. Add t o your t est s pat h t he file selenium.py Run Selenium ser ver fr om t he console Execute your test from a console or your Python IDE The following st eps descr ibe t he basic inst allat ion pr ocedur e. Aft er following t his, the user can st ar t using t he desir ed I DE, ( even wr it e t est s in a t ext pr ocessor and r un t hem fr om command line! ) wit hout any ex t r a wor k ( at least on t he Selenium side) . I nst alling Pyt hon Note This will cover py t hon inst allat ion on Windows and Mac only, as in m ost linux dist r ibut ions py t hon is alr eady pr e- inst alled by default . Windows 1. Download Act ive py t hon s inst aller fr om Act iveSt at e s official sit e: ht t p: / / act ivest at e.com / Pr oduct s/ act ivepyt hon/ index.m ht m l 2. Run t he inst aller downloaded ( Act ivePy t hon-x.x .x .x- win32-x86.m si)

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

Python Client Driver Configuration

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

Useful XPATH patterns


text
Not yet wr it t en - locat e elem ent s based on t he t ext cont ent of t he node.

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.

Starting to use CSS instead of XPATH


Locating elements based on class
I n or der t o locat e an elem ent based on associat ed class in XPat h you m ust consider t hat t he elem ent could have m ult iple classes and defined in any or der. However wit h CSS locat or s t his is m uch sim pler ( and fast er ) . XPath: //div[contains(@class, 'article-heading')] CSS: css=div.article-heading

1 de 1

28/05/2013 7:31

Migrating From Selenium RC to Selenium WebDriver

Selenium Docu...

http://docs.seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriv...

How to Migrate to Selenium WebDriver


A com m on quest ion when adopt ing Selenium 2 is what s t he cor r ect t hing t o do when adding new t est s t o an exist ing set of t est s? User s who ar e new t o t he fram ewor k can begin by using t he new WebDr iver API s for wr it ing t heir t est s. But what of user s who alr eady have suit es of exist ing t est s? This guide is designed t o dem onst rat e how t o m igrat e your exist ing t est s t o t he new API s, allowing all new t est s t o be wr it t en using t he new feat ur es offer ed by WebDr iver. The m et hod pr esent ed her e descr ibes a piecem eal m igrat ion t o t he WebDr iver API s wit hout needing t o r ewor k ever yt hing in one m assive push. This m eans t hat you can allow m or e t im e for m igrat ing your exist ing t est s, which m ay m ake it easier for you t o decide wher e t o spend your effort. This guide is wr it t en using Java, because t his has t he best suppor t for m aking t he m igrat ion. As we pr ovide bet t er t ools for ot her languages, t his guide shall be expanded t o include t hose languages.

Why Migrate to WebDriver


Moving a suit e of t est s fr om one API t o anot her API r equir es an enor m ous am ount of effor t . Why would you and your t eam consider m aking t his m ove? Her e ar e som e r easons why you should consider m igrat ing your Selenium Test s t o use WebDr iver. Sm aller, com pact API . WebDr iver s API is m or e Obj ect Or ient ed t han t he or iginal Selenium RC API . This can m ake it easier t o wor k wit h. Bet t er em ulat ion of user int eract ions. Wher e possible, WebDr iver m akes use of nat ive event s in or der t o int eract wit h a web page. This m or e closely m im ics t he way t hat your user s wor k wit h your sit e and apps. I n addit ion, WebDr iver offer s t he advanced user int eract ions API s which allow you t o m odel com plex int eract ions wit h your sit e. Suppor t by br owser vendor s. Opera, Mozilla and Google ar e all act ive par t icipant s in WebDr iver s developm ent , and each have engineer s wor king t o im pr ove t he fram ewor k. Oft en, t his m eans t hat suppor t for WebDr iver is baked int o t he br owser it self: your t est s r un as fast and as st ably as possible.

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

Migrating From Selenium RC to Selenium WebDriver

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:

This should be r eplaced 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 .

Clicking and Typing is More Complete


A com m on pat t er n in a Selenium RC t est is t o see som et hing like:

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

WaitForPageToLoad Returns Too Soon

28/05/2013 7:32

Migrating From Selenium RC to Selenium WebDriver

Selenium Docu...

http://docs.seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriv...

if a St aleElem ent Except ion is t hr own by WebDr iver.

WaitForPageToLoad Returns Too Soon


Discover ing when a page load is com plet e is a t r icky business. Do we m ean when t he load event fir es , when all AJAX r equest s ar e com plet e , when t her e s no net wor k t raffic , when docum ent .r eadySt at e has changed or som et hing else ent ir ely? WebDr iver at t em pt s t o sim ulat e t he or iginal Selenium behavior, but t his doesn t always wor k per fect ly for var ious r easons. The m ost com m on r eason is t hat it s har d t o t ell t he differ ence bet ween a page load not having st ar t ed yet , and a page load having com plet ed bet ween m et hod calls. This som et im es m eans t hat cont r ol is r et ur ned t o your t est befor e t he page has finished ( or even st ar t ed! ) loading. The solut ion t o t his is t o wait on som et hing specific. Com m only, t his m ight be for t he elem ent you want t o int eract wit h next , or for som e Javascr ipt var iable t o be set t o a specific value. An exam ple would be:

Wher e visibilit yOfElem ent Locat ed is im plem ent ed as:

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

Migrating From Selenium RC to Selenium WebDriver

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.

Executing Javascript Doesn t Return Anything


WebDr iver s Javascr ipt Execut or will wrap all JS and evaluat e it as an anonym ous expr ession. This m eans t hat you need t o use t he r et ur n keywor d:

becomes:

Navigation

4 de 4

28/05/2013 7:32

Anda mungkin juga menyukai