Selenium Student Material
Selenium Student Material
Selenium Student Material
Testing with
SELENIUM
Page 1 of 69
1. History of Selenium
Open source browser based integration test framework built originally by Thoughtworks.
2. What is Selenium?
JavaScript
DHTML
Frames
3. Selenium Components
Selenium IDE
Selenium Core
Selenium RC
Selenium Grid
The Selenium-IDE (Integrated Development Environment) is the tool you use to develop
your Selenium test cases.
Page 2 of 69
It is Firefox plug-in
Based on Selenese
B. Toolbar: The toolbar contains buttons for controlling the execution of your test cases,
including a step feature for
C. Menu Bar:
File Menu: The File menu allows you to create, open and save test case and test
suite files.
Edit Menu: The Edit menu allows copy, paste, delete, undo and select all operations
for editing the commands in your test case.
Options Menu: The Options menu allows the changing of settings. You can set the
timeout value for certain commands, add user-defined user extensions to the base
set of Selenium commands, and specify the format (language) used when saving
your test cases.
D. Help Menu:
Exercises:
TCS #1: Manual Steps:
Page 4 of 69
Program:
Script Syntax:
<table>
<tr><td>open</td><td></td><td>/download/</td></tr>
<tr><td>assertTitle</td><td></td><td>Downloads</td></tr>
<tr><td>verifyText</td><td>//h2</td><td>Downloads</td></tr>
</table>
3.1.4 Introducing Selenium Commands
The command set is often called selenese. Selenium commands come in three flavors:
Actions, Accessory and Assertions.
b. Accessors: Accessors examine the state of the application and store the results in
variables, e.g. "storeTitle".
Page 6 of 69
TC#2:
1: Open Firefox Web Browser
2: In the address bar, Type http://www.yahoo.com
3: In the search input button, Type "energy efficient"
4: Click on the "Web Search" submit button
5: Wait for Search Results to come on "http:/search.yahoo.com"
6: Verify "energy efficient" text is present anywhere in the search results: (Select and
highlight anywhere in the search results page, "energy efficient" text is present.)
7: Verify the browsers title has the value "energy efficient - Yahoo! Search Results"
8. End.
TCS #3:
Open http://www.ge.com
In the result page, highlight Thank you for taking the time to contact GE
Right Click and Select waitForTextPresent Thank you for taking the time to contact GE
Right Click on GE.com Home Page link and Select verifyElementPresent link=GE.com
Home Page
Page 7 of 69
A file similar to this would allow running the tests all at once, one after another, from the
Selenium-IDE.
Edit Selenium Test Suite
If you have only one test case in your test suite, Open the GE_TS1.html in NotePad.
Now you can double click and see the entire test suite in your browser.
You can Edit the Test Suite in notepad when you want to
Change the name of the test cases
Add, Remove, and Rename test cases
Arrange order of test cases.
HTML Validator
ColorZilla
DOM Inspector
Steps:
1.
2.
3.
4.
5. Click on OK Button
6. Restart selenium and fire fox.
3.1.7 Format:
Format #: CSV Format
1. Go to ToolsSelenium IDE Options Format Tab Press the add button
2. Provide the name of format as CSV Format
3. Open this Link http://wiki.openqa.org/display/SIDE/Adding+Custom+Format
4. Copy The complete script From that page
5. Paste the JavaScript contents in Selenium IDE Format Source window
6. Press the OK button
Page 10 of 69
Page 11 of 69
verifyTextPresent
The command verifyTextPresent is used to verify specific text exists somewhere on the page.
VerifyElementPresent
Use this command when you must test for the presence of a specific UI element, rather then its
content.
verifyElementPresent can be used to check the existence of any HTML tag within the page. You
can check the existence of links, paragraphs, divisions <div>, etc. Here are a few more
examples.
VerifyText
Use verifyText when both the text and its UI element must be tested. verifyText must use a
locator. If you choose an XPath or DOM locator, you can verify that specific text appears at a
specific
location on the page relative to other UI components on the page.
B. Locating Elements
1. For many Selenium commands, a target is required.
2.This target identifies an element in the content of the web application, and consists of the
location strategy followed by the location in the format locatorType=location.
Locating by Identifier : your page source could have id and name attributes 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" />
Page 12 of 69
7 </form>
8 </body>
9 <html>
The following locator strategies would return the elements from the HTML snippet above
indicated by
line number:
identifier=loginForm (3)
identifier=username (4)
identifier=continue (5)
continue (5)
Since the identifier type of locator is the default, the identifier= in the first three examples
above is not necessary.
Locating by Id
This type of locator is more limited than the identifier locator type, but also more explicit. Use
this when you know an elements id attribute.
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 <input name= "continue" type= "button" value= "Clear" />
8 </form>
9 </body>
10 <html>
id= loginForm (3)
Locating by Name
The name locator type will locate the first element
The name locator type will locate the first element with a matching name attribute. If multiple
elements
have the same value for a name attribute, then you can use filters to further refine your location
strategy.
The default filter type is value (matching the value attribute).
1
<html>
Page 13 of 69
<body>
<form id= "loginForm" >
4 <input name= "username" type= "text" />
5 <input name= "password" type= "password" />
6 <input name= "continue" type= "submit" value= "Login" />
7 <input name= "continue" type= "button" value= "Clear" />
8 </form>
9 </body>
10 <html>
2
3
name=username (4)
name=continue value=Clear (7)
name=continue Clear (7)
name=continue type=button (7
link=Continue (4)
link=Cancel (5)
Locating by DOM
The Document Object Model represents an HTML document and can be accessed using
JavaScript. This location strategy takes JavaScript that evaluates to an element on the page,
which can be simply the elements location using the hierarchical dotted notation.
Since only dom locators start with document, it is not necessary to include the dom= label
when specifying a DOM locator.
<html>
<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 <input name= "continue" type= "button" value= "Clear" />
8 </form>
9 </body>
10 <html>
1
2
dom=document.getElementById(loginForm) (3)
dom=document.forms[loginForm] (3)
Page 14 of 69
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 variables to store constants at the beginning of a script
storeElementPresent
This corresponds to verifyElementPresent. It simply stores a boolean valuetrue or false
depending on whether the UI element is found.
storeText
StoreText corresponds to verifyText. It uses a locater to identify specific page text. The text, if
found, is stored in the variable. StoreText can be used to extract text from the page being
tested.
storeEval
StoreEval allows the test to store the result of running the script in a variable.
Page 16 of 69
All variables created in your test case are stored in a JavaScript associative array. An
associative array has string indexes rather than sequential numeric indexes. The associative
array containing your test cases variables is named storedVars. Whenever you wish to access
or manipulate a variable within a JavaScript snippet, you must refer to it as storedVars[yourVariableName].
This next example illustrates how a JavaScript snippet can include calls to methods, in this case
the JavaScript String objects toUpperCase method and toLowerCase method.
Page 17 of 69
JavaScript Evaluation
1. You can use any of the following Eval commands
assertEval, assertNotEval, VerifyEval, verifyNotEval, waitForEval,
waitForNotEval, storeEval
2. You can use any of the following Expression commands
assertExpression, assertNotExpression,verifyExpression, verifyNotExpression,
waitForExpression, waitForNotExpression, storeExpression, store and
WaitForCondition
Exercises:
TC#4:
Sort by Prizev
In this case I have decided to check the first two Amounts displayed on that page are in
the ascending order.
If A <= B then we assume the first two listed prices are in ascending order.
If B <= C then we assume that A, B and C are in ascending order. (i.e., A <= B <=C )
Page 18 of 69
Page 19 of 69
AlertPresent
verifyAlertPresent()
The best way to check the alerts are using this command
Returns:
True or False.
storeAlertPresent ( seleniumVariableName )
assertAlertPresent ( )
assertAlertNotPresent ( )
verifyAlertNotPresent ( )
waitForAlertPresent ( )
waitForAlertNotPresent ( )
Ex1:
Ex 2:
Page 20 of 69
goBack:
goBack and goBackAndWait are the two commands simulates a user clicking on the
back button of the browser.
Page 21 of 69
waitForPopup
Select win1, click the button Click and get the Welcome Message, minimize
win1
Ex:
Page 22 of 69
In <HEAD> tag
In <body> tag
And external key
a=10;
document.write(a);
Ex;-
a=10;
document.write(a);
a=java script; /*modifying variable */
document.write(a);
In JScript, there are three primary data types, two composite data types, and two
special data types.
The primary (primitive) data types are:
String
Number
Boolean
-> Boolean (true/false)
Page 24 of 69
a=true;
document. write (Typeof(a));
Out put
Boolean.
Ex :- n=12;
document.write(typeof(a));
Out put:-
number datatype
1. Number
n=12;
document.write(n);
Ex:-
n=12.5;
document.write(n);
Output;-
12.5
parseInt:Ex;- n=12.5;
document.write(parseint(n));
Output:- 12
Ex 2:-
n=12 tonnes
document.write(parseInt(n));
Output:- 12
Concatenation:
Ex 3:-
document.write(parseint(12cows));
document.write(=);
document.write(parseInt(12 cows);
document.write(<br>);
Syntax:-
document.write(parseInt(12cows)=+parseInt(12cows))+(<BR.);
Document.write(parseFloat(f));
Output;- 12.5
Ex2:- document.write(parseFloat(12.5 tonnes)=+parseFloat(12.5 tonnes));
Ex3:- img=<img src=chicken.JPEG>;
Document.write(img);
Ex 4:- for string concatenation:a=welcome to NageshQTP
b=online training
c=a+b;
c=a+ +b;
document.write(c);
Operators:
(++x)
X=10;
Y=++x;
(x++)
Page 26 of 69
X=10;
Y=x++;
Output= starts from 10, 11,
Ex:-
(post increment)
X=10;
x=10
D.W(x=+(++x)+<br>);
x=11
x=10
d.w(x--=+(x--)+<br>);
d.w(x=+(x)+<br>);
x=10
x=9
Logical operators:x
X&&y
X||y
t
Page 27 of 69
Ex:-
d.w(true&&false=+(true&&false)+<br>); =false
d.w(true|| false=+(true||false)+<br>); =true
Conditional operators:Conditional operators is used for determining execution of statement based on the
condition
Syntax:-
Ex:- x=9;
Type=(x%2==0)?Even:odd;
IF,
IF else
IF-else IF ladder
Nested if and
Switch cases
IF:If(condition)
{
code
}
Ex:-
var d=newData()
Var time=d.getHours()
If(time<10)
{
Document.write(<b> Good Morning</b>);
IF-else:Page 28 of 69
Syntax:If(condition)
{
Code
}
Else
{
Code
}
Ex:Age=15;
If(Age<=10)
{
d.w(Boy);
} else
{
d.w(young);
}
If-else IF Ladder:f(condition)
{ Code; }
Else if(con 2)
{ code; }
Else if(con 3)
{ Code; }
..n;
Ex:Perc=60;
If(perc>=70){ grade=A;}
else if(perc>=60){grade =B;}
else if(perc>=50){grade=c;}
Nested IF:If(condition1)
{
If(condition2)
{
Code;
}
else
{ Code; }
}
Ex:A=12;
B=13;
If(a>=b)
{
If(a>b)
{
Page 29 of 69
d.w(A is greater<br>);
}
else
{
d.w(A and B are Equal<br>);
}
}
else{
d.w(A is less);
}
Switch:Switch(expression)
{
Case value:
Code;
Break;
Case val2:
Code;
Break;
Default:
Code;
Break;
}
Ex:Dya=3;
Switch(day){
Case 1:
d.w(Monday <br>);
break;
case 2:
d.w(Tuesday <br>);
break:
.
.
.
Case 7:
d.w(Sunday <br>);
break;
default:
d.w(Enter valid number<br>);break;
}
Loops: While
While(condition)
{
Code
}
Ex:1
i=1;
while(i<=3)
{
d.w(i);
i++;
}
Ex:-2
Mon=new Array (jan,feb,mar,..dec);
m=0;
While(m<mon.length)
Page 31 of 69
{
d.w(month name=+mon[m]+<br>);
mi++;
}
Do-while:Do
{
Code;
}while(condition)
Ex:i=0
Do
{
d.w(i);
i++;
}while(i<=5);
For:For(initialization,condition,incrementation)
{
Code
}
Ex:1For(i=1;i<=3;i++)
{
d.w(i);
}
Ex:-2
Mon=new Array(jan,feb,mar,dec);
For(i=0;i<mon.length:i++)
{
d.w(mon[i]+<br>);
}
For-in:Syntax:For(index in arreg-nmae)
{
Array-name[index]
}
Ex:x=new Array(11,31,94);
For(i in x)
{
d.w(i+=+x[i]+<br>);
}
Functions:TYPE
I
II
Arg
*
yes
Return
*
*
Page 32 of 69
III
IV
*
yes
yes
yes
d.w(a=+a+<br>);
output:- first+val is a=9;
Type 4:- function with arguments and return values
Function square(x)
{
Return(x*x);
}
d.w(suqre(2));//4
d.w(square(suqre(2));//16
Built in methods: Date:D=new Date();
d.getDate();//1-11
d.getDay();//0-6
d.getMonth();//0-11
d.getYear();
d.getFullyear;//2009
d.getHours();//0-23
d.getMinutes();//0-59
d.getSeconds();//0-59
Ex:- for Built-in
Function p(text);
{
Document.write(text+<br>);
}
d=new Date();
P(d++d);
P(d.getdate()=+d.getDate());
P(d.getday()=+d.getday());
Math:Math;max(12,14);//14
Math;min(12,14);//12
Ex:Function p(text)
{
d.w(text+<br>);
}
//math.max(num1,num2);-> num
P(math.max(12,14)=+Math.max(12,14));
//Math.min(num1,num2);->num
P(math.min(12,14)=+Math.min(12,14));
//math.floor(num);->Lower limitation integer value
P(math.floor(12.94)=+Math.floor(12.94));//12
//math.ceil(num);->upper limitation integer value
P(math.ceil(12.14)=+Math.ceil(12.14));//13
//math.round(num)-> if >=.5 ceil,<.5 floor
P(math.round(12.14)=+Math.round(12.14));
P(math.round(12.14)=+Math.round(12.54));
//math.random()->0 and 1
Page 34 of 69
P(math.random()=+math.random());
String methods:Function p(text)
{
Document.write(text+<br>);
}
Str=javascript;
P(str=+str);
P(length=+str.length());
P(upper=+str.touppercase());
P(lower=+str.tolowercase());
P(str.substr=+str.substr(4));
P(str.substr(4,2)=+str.substr(4,2));
Replace of search string replacement(Replace)
P(str.replace( a,_)=+str.replace(a,_);
p(str.replace( a,_)=+str.replace(A,_);
Regular Expression:Function reg(expr,str)
{
R=new RegExp(expr);
Return r.test(str);
}
P(reg(b,abc)=+reg(b+abc));
^ mathches to beginning of the string(if you want to verify starting,letter in whole
stirng,we can use ca(^))
Ex:- P(reg(^b,abc)=+reg(^b+_abc));
Output:- false
P(reg(^a,abc)=+reg(^a+_abc));
Output:- True
$ mathches to end of stirng(if you want to verify ending character in whole string,we can
use $)
Ex:- P(reg(a$,abc)=+reg(a$+abc));
Output:- false
P(reg(c$,abc)=+reg(c$+abc));
Output:- True
->(.) mathes any single character(alphabet,number, special character, space)(if you want to
verify only single character we can use dot)
Ex:- P(reg(^.$,abc)=+reg(^.$+abc));
output:- false
P(reg(^.$,a)=+reg(^.$+a));
Output:- True
P(reg(\.doc$,resume.doc)=+reg(\.doc+resume.doc));
+ one or many times(if you want to verify any single char,if may be one time else many
times,we can use +)
P(reg(a+$,a)=+reg(a+$+a));
Output:- True
P(reg(a+$,aaa)=+reg(a+$+aaa));
Output:- False
P(reg(a+$,ab)=+reg(a+$+ab));
Page 35 of 69
Output:- false
* 0 to many times
Ex:- P(reg(a*$,)=+reg(a*$+));
Output:-True
P(reg(a*$,aa)=+reg(a*$+aa));
Output;- True
P(reg(a*$,ab)=+reg(a*$+ab));
Output:- False
? 0 or min one time or no.of times
P(reg(https?,http://www.google.com)=+reg(https?+http://www.google.com));
Output:- True
{n} - for n times
{n,} -min n times
{n, m}-min n times, max m times
[] use for specifying range of char allowe for the exp.
[a-z] [A-Z] [0-9] [abcd] [a-zA-Z0-9-> Alphanumeric
Ex:- P(reg(^[a-z]${3},abc)=+reg(^[a-z]${3}+abc));
Output:- True
P(veg(^[a-z]${3],ABC)=+reg(^[a-z]${3}+ABC));
\d -- matches with any digit(0-9)
\D matches a non-digit
\s -- matches a space
\S -- matches any non-space
\w -- matches word boundary(alphanumeric and under square)
\W -- non word boundary
| -- or
() -- matches sub expressions([] [] {})
Ex:- for mobile validation
Function isMobile(num)
{
Num=num.toString()
Exp=^[98][0-9]{9}$;
Return reg(exp,num);
]
Mobile=8876543210;
P(ismobile(mobile)?validMobile:invalid);
Ex:-2 for usMobile(124-136-106205)
Function isUsPhone(ph)
{
Return reg(^[0-9]{3}[\-]){2}[0-9]{6}$,ph);
}
Phone=234-345-234567;
P(isUsPhone(phone)/valid:invalid;
Ex 3:- Email id
<html>
<head>
<script>
Function isEmail(mail)
{
Page 36 of 69
Return reg(^[a-zA-Z0-9]\\w{3,}\.\\a{2,}@[a-zA-Z0-9\-]{2,}\.[a-zA-Z\.]{2,}$,mail);
}
Ma=Sridhar.metukuru@gmail.com;
P(isEmail(ma?valid:invalid;
</script>
</head>
</html>
Ex:- User name
Function isUser(name)
{
return reg(^[a-zA-Z][\.][a-zA-Z]{5},name);
}
Name=pradeep;
P(isuser)(name)?valid:invalid;
Ex:Function isUser(name)
{
return reg(^[a-zA-Z][a-zA-Z\.]{5,},name);
}
Name=Pradeep;
P(isuser(name)?valid:invalid);
Selenium Modes
Test Runner Mode
test cases in HTML tables
Record-Playback mode (Selenium IDE)
Selenium Remote Control (RC) Mode
test-cases in your language of choice
Page 37 of 69
Syntax:
command: allowNativeXpath
Target: True
2. assertAlert To Verify the Java Script Pop-Ups, similarly assertConfirmation.
3. answerOnNextPrompt(answer)
Arguments:
answer - the answer to give in response to the prompt pop-up
Instructs Selenium to return the specified answer string in response to the next
JavaScript prompt [window.prompt()].
4. assertAlertPresent()
Generated from isAlertPresent()
Returns:
true if there is an alert
Has an alert occurred?
This function never throws an exception
5. assertAllButtons(pattern)
Generated from getAllButtons()
Returns:
the IDs of all buttons on the page
Returns the IDs of all buttons on the page.
6. assertAllFields(pattern)
Generated from getAllFields()
Returns:
the IDs of all field on the page
Returns the IDs of all input fields on the page.
7. assertAllLinks(pattern)
Generated from getAllLinks()
Returns:
the IDs of all links on the page
Page 38 of 69
Saves the entire contents of the current window canvas to a PNG file. Contrast this with
the captureScreenshot command, which captures the contents of the OS viewport (i.e.
whatever is currently being displayed on the monitor), and is implemented in the RC
only. Currently this only works in Firefox when running in chrome mode, and in IE nonHTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is
mostly borrowed from the Screengrab! Firefox extension. Please see
http://www.screengrab.org and http://snapsie.sourceforge.net/ for details.
Similarly: captureEntirePageScreenshotAndWait
check(locator)
Arguments:
locator - an element locator
Check a toggle-button (checkbox/radio)
Similarly: checkAndWait
chooseCancelOnNextConfirmation(),chooseOkOnNextConfirmation(),
chooseOkOnNextConfirmationAndWait
Click, ClickAndWait, ClickAt, ClickAtAndWait, Close.
contextMenu, contextMenuAndWait, contextMenuAt, contextMenuAtAndWait.
createCookie, createCookieAndWait
deleteAllVisibleCookies()
Calls deleteCookie with recurse=true on all cookies visible to the current page. As noted
on the documentation for deleteCookie, recurse=true can be much slower than simply
deleting the cookies using a known domain/path.
Similarly: deleteAllVisibleCookiesAndWait, deleteCookie, deleteCookieAndWait,
doubleClick(locator)
Arguments:
locator - an element locator
Double clicks on a link, button, checkbox or radio button. If the double click action
causes a new page to load (like a link usually does), call waitForPageToLoad.
Similarly: doubleClickAndWait, doubleClickAt, doubleClickAtAndWait.
echo(message)
Arguments:
message - the message to print
Page 41 of 69
Prints the specified message into the third table cell in your Selenese tables. Useful for
debugging.
fireEvent(locator, eventName)
Arguments:
locator - an element locator
eventName - the event name, e.g. "focus" or "blur"
Explicitly simulate an event, to trigger the corresponding "onevent" handler.
Similarly: fireEventAndWait
focus(locator)
Arguments:
locator - an element locator
Move the focus to the specified element; for example, if the element is an input field,
move the cursor to that field.
Similarly: focusAndWait
goBack()
Simulates the user clicking the "back" button on their browser.
Similarly: goBackAndWait
ignoreAttributesWithoutValue(ignore)
Arguments:
ignore - boolean, true means we'll ignore attributes without value at the expense
of xpath "correctness"; false means we'll sacrifice speed for correctness.
Similarly: ignoreAttributesWithoutValueAndWait
open(url)
Arguments:
url - the URL to open; may be relative or absolute
Similarly: openWindow, openWindowAndWait
pause(waitTime)
Arguments:
waitTime - the amount of time to sleep (in milliseconds)
Wait for the specified amount of time (in milliseconds)
refresh()
Simulates the user clicking the "Refresh" button on their browser.
Page 42 of 69
Similarly: refreshAndWait
removeAllSelections(locator)
Arguments:
locator - an element locator identifying a multi-select box
Unselects all of the selected options in a multi-select element.
Similarly: removeAllSelectionsAndWait, removeSelection, removeSelectionAndWait
removeScript(scriptTagId)
Arguments:
scriptTagId - the id of the script element to remove.
Removes a script tag from the Selenium document identified by the given id. Does
nothing if the referenced tag doesn't exist.
Similarly: removeScriptAndWait
runScript(script)
Arguments:
script - the JavaScript snippet to run
Similarly: runScriptAndWait
select(selectLocator, optionLocator)
Arguments:
selectLocator - an element locator identifying a drop-down menu
optionLocator - an option locator (a label by default)
Select an option from a drop-down using an option locator.
Similarly: selectAndWait, selectFrame, selectPopUp, selectPopUpAndWait, selectWindow,
setTimeout(timeout)
Arguments:
timeout - a timeout in milliseconds, after which the action will return with an
error
Specifies the amount of time that Selenium will wait for actions to complete.
Actions that require waiting include "open" and the "waitFor*" actions.
store(expression, variableName)
Arguments:
expression - the value to store
variableName - the name of a variable in which the result is to be stored.
Page 43 of 69
uncheck(locator)
Arguments:
locator - an element locator
Uncheck a toggle-button (checkbox/radio)
Similarly: uncheckAndWait
verifyAlert(pattern)
Generated from getAlert()
Returns:
The message of the most recent JavaScript alert
Similarly: verifyAlertNotPresent, verifyAlertPresent, verifyAllButtons, verifyAllFields,
verifyAllLinks, verifyAllWindowNames, verifyAllWindowTitles etc..
verifyConfirmation(pattern)
Generated from getConfirmation()
Returns:
the message of the most recent JavaScript confirmation dialog
Retrieves the message of a JavaScript confirmation dialog generated during the previous
action.
Similarly: verifyConfirmationNotPresent, verifyConfirmationPresent
verifyText(locator, pattern)
Generated from getText(locator)
Arguments:
locator - an element locator
Returns:
the text of the element
Similarly: verifyTitle,verifyTable etc..
waitForAlert(pattern)
Generated from getAlert()
Returns:
The message of the most recent JavaScript alert
Retrieves the message of a JavaScript alert generated during the previous action, or fail
if there were no alerts.
Similarly: waitForAllButtons, waitForAllFields, waitForAllLinks, waitForAllWindowIds,
waitForAllWindowNames, waitForAllWindowTitles,
waitForConfirmationPresent()
Page 45 of 69
http://www.ge.com/
type
textToSearch
clickAndWait
searchSubmit
assertTitle
assertTextPresent
energy efficient
energy efficient
Tc# 2:
GE Test Case2
open
http://www.ge.com/
assertTitle
GE : imagination at work
clickAndWait
//div[@id='ge_footer']/ul/li[2]/a
assertTitle
clickAndWait
assertTitle
pause
3000
select
contact_subject
label=Other
Page 46 of 69
GE Test Case2
select
contact_country
label=United
States
type
contact_email
testing@test.com
type
contact_comments
No questions.
clickAndWait
//form[@id='contact_form']/p/input
verifyTextPresent
verifyTextPresent
file:///C:/Javascript/Class%20Ex/Ex16.html?txtAge=101&=Submit
assertTitle
Age Problem
idAge
click
idSubGo
open
Infant
type
idAge
click
idSubGo
deleteCookie
Kid
type
idAge
click
idSubGo
assertAlert
Adult
type
idAge
click
idSubGo
assertAlert
Senior
type
idAge
click
idSubGo
assertAlert
Grand Senior
type
idAge
click
idSubGo
-1
20
55
75
110
Page 47 of 69
type
idAge
check
idSubGo
pause
5000
clickAndWait
idSubGo
assertAlert
www
http://www.google.com/
type
clickAndWait
btnG
waitForTextPresent
energy efficiency
assertTitle
energy efficient
file:///C:/2009%20Selenium/Day3/Ex/HelloWorld.html
store
Kangeyan
echo
${vName}
vName
answerOnNextPrompt ${vName}
click
waitForPrompt
echo
${vName}
createCookie
idName
${vName}
TC# 6:
Reviewed Test Case Barnes and Noble Sorted Order
open
http://www.barnesandnoble.com/index.asp
type
search-input
clickAndWait
quick-search-button
javascript
Page 48 of 69
10000
clickAndWait
link=Price
storeText
//div[@id='bs-centercol']/div[3]/div[1]/div[2]/div/div/div/ul[1]/li[2]/strong
echo
${T1}
storeText
xpath=id('bs-centercol')/div[3]/div[3]/div[2]/div/div/div/ul[1]/li[1]/strong
echo
${T2}
storeText
//div[@id='bs-centercol']/div[3]/div[5]/div[2]/div/div/div/ul[1]/li[1]/strong
echo
${T3}
storeEval
echo
${T4}
storeEval
echo
${T5}
storeEval
echo
${R1}
storeEval
echo
${R2}
storeEval
T6
store
true
T7
echo
${T6}
verifyExpression ${T6}
T1
T2
T3
R1
R2
${T7}
echo
${T7}
storeEval
echo
${vSorted}
click
Welcome to Portnov!
select
OptWeb
clickAndWait
btnGo
assertTitle
label=Google
goBackAndWait
select
OptWeb
clickAndWait
btnGo
assertTitle
label=Portnov
goBackAndWait
select
OptWeb
clickAndWait
btnGo
assertTitle
Microsoft Corporation
label=Microsoft
goBackAndWait
select
OptWeb
clickAndWait
btnGo
assertTitle
Yahoo!
label=Yahoo
winBut
waitForPopUp
win1
30000
waitForPopUp
win2
30000
waitForPopUp
win3
30000
selectWindow
name=win1
click
assertAlert
Welcome to Portnov!
selectWindow
name=win3
click
//input[4]
click
Submit
assertConfirmation
assertAlert
submitted
selectWindow
null
click
Regular Expression
Tc#10: Verify Page Title
Reviewed Test Case Window Name Check
open
file:///C:/2009%20Selenium/Day%204/Ex/ShowWinName.html
click
winBut
assertAlert
regex:Ex1.html
win1
assertAlert
regex:Ex2.html
win2
assertAlert
regex:Ex3.html
win3
file:///C:/2009%20Selenium/Day
%204/Ex/UserInputForm.html
type
txtName
kangs p
type
txtEmail
KANGS@YAHOO.COM
click
//input[@value='Submit']
Page 51 of 69
Valid
verify
//form[@id='frm']/table.2.2
Table
Valid
storeV
txtName
alue
selName
echo
${selName}
storeV
txtEmail
alue
echo
selEmail
${selEmail}
assert
storedVars['selName']
Eval
regex:\w+\s\w+
regex:^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]
assert javascript:jStr=storedVars['selEmail'
+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|
Eval ]; jStr.toLowerCase()
int|jobs|mil|museum|name|nato|net|org|pro|travel)$
file:///C:/2009%20Selenium/Day%204/Ex/Narrating Test
Cases.html
type
txtName
kangs p
type
txtEmail
KANGS@YAHOO.COM
storeValue txtName
echo
selName
${selName}
storeValue txtEmail
echo
${selEmail}
click
//input[@value='Submit']
selEmail
verifyTable //form[@id='frm']/table.1.2
Valid
verifyTable //form[@id='frm']/table.2.2
Valid
assertE
storedVars['selName']
val
regex:\w+\s\w+
javascript:jStr=storedVars regex:^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]
assertE
['selEmail'];
{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|
val
jStr.toLowerCase()
name|nato|net|org|pro|travel)$
Testing Highlight
assertElementPresent idNameDisp
assertElementPresent idEmailDisp
Tc#11:
Test Case DevryPopupWindows Close
open
http://www.devrydegrees.com/7x/prequal.jsp;jsessionid=GYW5fw1VxepITK3Fi7CXsg**.ap
p8-all1?
redirected=redirect&CLK=0&CCID=&QTR=&ZN=&ZV=&KY_T=
refresh
setSpeed
3000
Page 53 of 69
click
//div[@id='footerlogo']/table/tbody/tr[1]/td[1]/a[1]/u
waitForPopU
Thandie
p
30000
selectWindow name=Thandie
assertTitle
click
//html/body/table/tbody/tr[4]/td/a
selectWindow null
click
//div[@id='footerlogo']/table/tbody/tr[1]/td[1]/a[1]/u
waitForPopU
Thandie
p
30000
selectWindow null
pause
10000
click
//div[@id='footerlogo']/table/tbody/tr[1]/td[1]/a[2]/u
waitForPopU
Thandie
p
30000
selectWindow name=Thandie
assertTitle
Programs-DeVry University
click
//html/body/table[2]/tbody/tr/td/p/a
selectWindow null
click
//div[@id='footerlogo']/table/tbody/tr[1]/td[2]/a[1]/u
waitForPopU
Thandie
p
30000
selectWindow name=Thandie
assertTitle
click
//html/body/table/tbody/tr[2]/td/a
selectWindow null
click
//div[@id='footerlogo']/table/tbody/tr[1]/td[2]/a[2]/u
waitForPopU
Thandie
p
30000
selectWindow name=Thandie
assertTitle
click
//html/body/table/tbody/tr[2]/td/a
selectWindow null
Page 54 of 69
http://www.yahoo.com/
storeEval
(new Date()).getTime()
StartTime
refresh
waitForPageToLoad
3000
storeEval
(new Date()).getTime()
echo
${StartTime}
echo
${EndTime}
storeEval
(${EndTime}-${StartTime})/1000
echo
${PageLoadTime} Seconds
storeEval
(new Date()).getTime()
open
http://www.yahoo.com/
waitForPageToLoad
3000
storeEval
(new Date()).getTime()
EndTime
storeEval
(${EndTime}-${StartTime})/1000
PageLoadTime
echo
${PageLoadTime} Seconds
EndTime
PageLoadTime
StartTime
Tc#13: AvgPageLoadTime
Test Case for PageLoadTime
open
http://www.yahoo.com/
storeEval
(new Date()).getTime()
StartTime
refresh
waitForPageToLoad
3000
storeEval
(new Date()).getTime()
echo
${StartTime}
echo
${EndTime}
storeEval
(${EndTime}-${StartTime})/1000
echo
${PageLoadTime1} Seconds
storeEval
(new Date()).getTime()
open
http://www.yahoo.com/
waitForPageToLoad
3000
EndTime
PageLoadTime1
StartTime
Page 55 of 69
(new Date()).getTime()
EndTime
storeEval
(${EndTime}-${StartTime})/1000
PageLoadTime2
echo
${PageLoadTime2} Seconds
storeEval
(${PageLoadTime1}+${PageLoadTime2})/2
echo
${AvgPageLoadTime} Seconds
AvgPageLoadTime
${timeBeforeLoad}
open("http://www.ge.com/");var
storeEval win=this.browserbot.getCurrentWindow();
if(win)win.onload=(window.status=(new Date().getTime()));
echo
timeAfterLoad
${timeAfterLoad}
storeEval ${timeAfterLoad}-${timeBeforeLoad}
echo
timeBeforeLoad
loadTimeMSecs
${loadTimeMSecs}
file:///C:/2009 Selenium/Day4/Ex/ListofCourses.html
assertTitle
AssertXPath
storeElementPresent
//table[@id='idCourse']/tbody/tr[7]/td[3]
echo
${Txt1}
Txt1
assertElementNotPresent //table[@id='idCourse']/tbody/tr[8]/td[3]
assertElementPresent
//table[@id='idCourse']/tbody/tr[7]/td[3]
allowNativeXpath
true
verifyXpathCount
//table[@id='idCourse']/tbody/tr
verifyXpathCount
//table[@id='idCourse']/tbody/tr[1]/td
verifyXpathCount
//table[@id='idCourse']/tbody/tr/td
28
verifyTable
idCourse.0.0
S#
Page 56 of 69
idCourse.0.1
Course Name
verifyTable
idCourse.4.0
verifyTable
idCourse.4.1
Selenium
verifyTable
idCourse.4.2
Kangs
verifyTable
idCourse.4.3
4/4/2009
verifyTable
idCourse.0.2
Instructor Name
verifyTable
idCourse.0.3
Start Date
verifyTable
idCourse.6.0
verifyTable
idCourse.6.1
Python
verifyTable
idCourse.6.2
Michell
verifyTable
idCourse.6.3
6/6/2009
storeText
//table[@id='idCourse']/tbody/tr[7]/td[4]
sLastRowCell4
echo
${sLastRowCell4}
Selenium Core
Introduction:
Selenium Core tests run directly in a browser, just as real users do. And they run in
Internet Explorer, Mozilla and Firefox on Windows, Linux, and Macintosh.
Selenium uses JavaScript and Iframes to embed a test automation engine in browsers.
Page 57 of 69
Selenium was designed specifically for the acceptance testing requirements of Agile
teams.
Selenium was designed specifically for the acceptance testing requirements of Agile
teams.
Cross Browser and Cross Platform compatibility testing. One can test and verify whether
the application works correctly on different browsers and operating systems. The same
script can run on any Selenium platform.
HTA Mode in IE
The web-developer need to create the menus, icons, toolbars, and title information then
only those will be available within that application.
HTAs pack all the power of object model, performance, rendering power, protocol
support, and channeldownload technologywithout enforcing the strict security model
and user interface of the browser.
HTAs can be created using the HTML and Dynamic HTML (DHTML).
Selenium Core provides an additional mechanism for running automated tests called
"HTA mode."
An HTA file is a special type of HTML file that is allowed to violate the same origin policy
and to write files to disk. When running in HTA mode, you don't have to install Selenium
Core on the same web server.
HTA files are also allowed to save test results directly to disk, rather than posting the test
results to a web server.
You need to install the Selenium Core within the web server where AUT is deployed.
apache_2.2.11-win32-x86-no_ssl.msi
2.
Go to http://seleniumhq.org/download/
Right Click on the Download Link under Selenium Core, and download the file under
Apache web server
Right click on the Zip file, and unzip by Selecting winzip select Extract to here
http://localhost/Selenium/core/TestRunner.html
If you are able to see Selenium Test Runner Control Panel, then the installation is
complete and successful.
http://localhost/Selenium/core/TestRunner.hta
../oragehrm/TestSuite.html
Press Go button
Now, you can run either individual test cases or entire suite. Do as you wish.
Page 60 of 69
Selenium-RC
1. Introduction
Selenium-RC is the solution for tests that need more than simple browser actions and linear
execution.
Page 61 of 69
Selenium-RC uses the full power of programming languages to create more complex tests like
reading and writing files, querying a database, emailing test results.
Youll want to use Selenium-RC whenever your test requires logic not supported by SeleniumIDE.
What logic could this be? For example, Selenium-IDE does not directly support:
condition statements
iteration
logging and reporting of test results
error handling, particularly unexpected errors
database testing
test case grouping
re-execution of failed tests
test case dependency
screenshot capture of test failures
Although these tasks are not supported by Selenium directly, all of them can be achieved by
using programming techniques with a language-specific Selenium-RC client library.
2. Installing Selenium RC
Checking JRE
Go to http://seleniumhq.org/download/
Cd C:\SeleniumRC\JavaServer
Keep the server running (Do not close this cmd line window)
Cd c:\ruby
Ruby testEE.rb
Browsers
Operating Systems
Programming Languages
Testing Frameworks
Bromine, JUnit & TenstNG (Java), NUnit (.Net), RSpec & Test::Unit (Ruby),
unittest (Python)
sets the forced default browser mode (e.g. "*iexplore) for all sessions, no
matter what is passed in getNewBrowserSession
userExtensions <file>:
Tests are executed in a separate window and supports web pages with
frames.
multiWindow:
interactive:
browserSessionReuse:
Page 64 of 69
avoidProxy:
set this flag to make the browser use proxy only for URLs containing
'/selenium-server'
firefoxProfileTemplate <dir>:
debug:
Provide browser and URL to run a single HTML Selenese Test suite and
then exit immediately.
Provide absolute path to the HTML test suite, and HTML results file.
proxyInjectionMode:
Debug mode provides more trace information and used for diagnostics
purpose
log:
The following additional flags are supported for proxy injection mode :
A regular expression which is matched against all test HTML content; the
second is a string which will replace matches. These flags can be used any
number of times. A simple example of how this could be useful: if you add
Page 65 of 69
The "interactive mode (IM)" allows you to run your test case commands on the Selenium
Server interactively.
To completely automate the test suites, it is best practice to write your tests in a suitable
programming language. Not using interactive mode.
Description
Cross Domain
*iexplore, *iehta
Yes
*iexploreproxy
No
*firefox, *chrome
Yes
Page 66 of 69
*firefoxproxy
Firefox normal
No
*opera
Opera mode
No
*safari
Safari mode
No
*custom
Custom mode
Dynamic
Selenium RC getNewBrowserSession
During the "interactive mode" one can get the current browser Session ID using the
getNewBrowserSession command.
Example: http://www.google.com
testComplete command will stop the current session. No longer you can use the same
session for further testing after executing this command.
Example:
cmd=type&1=q&2=energy
efficient&sessionId=500b9ffb521d4c67b37e649a7bd5e527
cmd=close&sessionId=500b9ffb521d4c67b37e649a7bd5e527
cmd=waitForTextPresent&1=energy
efficiency&sessionId=500b9ffb521d4c67b37e649a7bd5e527
Page 67 of 69
The session ID is optional. Use session ID when you have multiple sessions.
Both &1 and &2 parameters are optional. If the Selenese command contains
parameter then you may need it.
Copy the first line of the code and paste in the interactive mode (*4)
cmd=getNewBrowserSession&1=*iexplore&2=http://www.google.com
Open notepad/wordpad
C:\2009 Selenium\Ex\GE
TestSuite.html
GE Test Case1.html
GE Test Case3.html
GE Test Case.bat
Page 69 of 69