+ All Categories
Home > Documents > Selenium Student Material

Selenium Student Material

Date post: 22-Dec-2015
Category:
Upload: vvenkat123
View: 26 times
Download: 1 times
Share this document with a friend
Description:
selenium
87
Automated Web Testing with SELENIUM Page 1 of 87
Transcript
Page 1: Selenium Student Material

Automated Web

Testing with

SELENIUM

Page 1 of 68

Page 2: Selenium Student Material

1. History of Selenium

• In 2004 invented by Jason R. Huggins and team.

• Original name is JavaScript Functional Tester [JSFT]

• Open source browser based integration test framework built originally by Thoughtworks.

• 100% JavaScript and HTML

• Web testing tool

• That supports testing Web 2.0 applications

• Supports for Cross-Browser Testing(ON Multiple Browsers)

• And multiple Operating Systems

• Cross browser – IE 6/7, Firefox .8+, Opera, Safari 2.0+

2. What is Selenium?

• Acceptance Testing tool for web-apps

• Tests run directly in browser

• Selenium can be deployed on Windows, Linux, and Macintosh.

• Implemented entirely using browser technologies -

JavaScript

DHTML

Frames

3. Selenium Components

– Selenium IDE

– Selenium Core

– Selenium RC

– Selenium Grid

3.1 Selenium IDE

• The Selenium-IDE (Integrated Development Environment) is the tool you use to develop your Selenium test cases.

Page 2 of 68

Page 3: Selenium Student Material

• It is Firefox plug-in

• Firefox extension which allows record/play testing paradigm

• Automates commands, but asserts must be entered by hand

• Creates the simplest possible Locator

• Based on Selenese

3.1.1 Overview of Selenium IDE:

A. Test Case PaneB. ToolbarC. Menu BarD. Log/Reference/UI-Element/Rollup Pane

A. Test Case Pane: Your script is displayed in the test case pane. It has two tabs. one for displaying the command (source) and their parameters in a readable “table” format.

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:

3.1.2 Recording and Run settings

When Selenium-IDE is first opened, the record button is ON by default.

During recording, Selenium-IDE will automatically insert commands into your test case based

on your actions.

a. Remember Base URL MODE - Using Base URL to Run Test Cases in Different Domains

Page 3 of 68

Page 4: Selenium Student Material

b. Record Absolute recording mode – Run Test Cases in Particular Domain.

3.1.3 Running Test Cases

Run a Test Case Click the Run button to run the currently displayed test case.

Run a Test Suite Click the Run All button to run all the test cases in the currently loaded test suite.

Stop and Start The Pause button can be used to stop the test case while it is running. The icon of this button then changes to indicate the Resume button. To continue click Resume.

Stop in the Middle You can set a breakpoint in the test case to cause it to stop on a particular command. This is useful for debugging your test case. To set a breakpoint, select a command, right-click, and from the context menu select Toggle Breakpoint.

Start from the Middle You can tell the IDE to begin running from a specific command in the middle of the test case. This also is used for debugging. To set a startpoint, select a command, right-click, and from the context menu select Set/Clear Start Point.

Run Any Single Command Double-click any single command to run it by itself. This is useful when writing a single command. It lets you immediately test a command you are constructing, when you are not sure if it is correct. You can double-click it to see if it runs correctly. This is also available from the context menu.

Exercises:

TC’S #1: Manual Steps:

• Open (Example : Type www.google.com)

• Type “energy efficient” in the Google Search Input Box

• Click outside on an empty spot

• Click Search Button

• Verify the Text Present as “energy efficient”

• Assert the Title as “energy efficient - Google Search”

• Save the test case with .HTML Extension.

Page 4 of 68

Page 5: Selenium Student Material

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.

a. Actions: user actions on application / Command the browser to do something.

Actions are commands that generally manipulate the state of the application. 1. Click link- click / Clickandwait 2. Selecting items

b. Accessors: Accessors examine the state of the application and store the results in variables, e.g. "storeTitle".

c. Assertions: For validating the application we are using Assertions

Page 5 of 68

Page 6: Selenium Student Material

1. For verifying the web pages

2. For verifying the text

3. For verifying alerts

Assertions can be used in 3 modes:

assert

verify

waitFor

Example: "assertText","verifyText" and "waitForText".

NOTE:

1. When an "assert" fails, the test is aborted.

2. When a "verify" fails, the test will continue execution

3. "waitFor" commands wait for some condition to become true

Commonly Used Selenium Commands

These are probably the most commonly used commands for building test.

open - opens a page using a URL.

click/clickAndWait - performs a click operation, and optionally waits for a new page to load.

verifyTitle/assertTitle - verifies an expected page title.

verifyTextPresent- verifies expected text is somewhere on the page.

verifyElementPresent -verifies an expected UI element, as defined by its HTML tag, is present on the page.

verifyText - verifies expected text and it’s corresponding HTML tag are present on the page.

verifyTable - verifies a table’s expected contents.

waitForPageToLoad -pauses execution until an expected new page loads. Called automatically when clickAndWait is used.

waitForElementPresent -pauses execution until an expected UI element, as defined by its HTML tag, is present on the page.

Page 6 of 68

Page 7: Selenium Student Material

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.

TC’S #3:

• File à New Test Case (Make Selenium IDE in Record Mode)

• Open http://www.ge.com

• Go all the way down, click on the “Contact Information” link

• Click on “Feedback & Inquiries” link

– Consumer/Other (Leave the default option)

– Select a Subject (Other)

– Select a Country (U.A.E)

– Email (type [email protected])

– Comments or Questions (type Just testing)

– Submit (click once)

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

• Highlight “Feel free to continue browsing.”

• Right Click and Select VerifyTextPresent “Feel free to continue browsing.”

• Right Click on “GE.com Home Page” link and Select verifyElementPresent “link=GE.com Home Page”

Page 7 of 68

Page 8: Selenium Student Material

3.1.5 Test Suite:

A test suite is a collection of tests. Often one will run all the tests in a test suite as one

continuous batch-job.

When using Selenium-IDE, test suites also can be defined using a simple HTML file. The syntax

again is simple. An HTML table defines a list of tests where each row defines the filesystem

path to each test.

Steps for creating test suite:

1. Create more Tc’s save each Test Case with <.html> extension.

2. Open Firefox

3. Open Tools à Selenium IDE

4. File à Open à new Test Suite

5. File à Open à Add Test cases

Page 8 of 68

Page 9: Selenium Student Material

6. Add more test cases

7. Save Suite with <.Html> extensions.

Test Suite Syntax:

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

• Add a line of code before the end of </tbody> tag

<tr><td><a href="GE_TC2.html">GE Test Case 2</a></td></tr>

• File → Save then Exit.

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

Useful Selenium FireFox Add-ONS:

• Chris Pederick's Web Developer toolbar• XPather • Firebug• Xpath Checker• Regular Expressions Tester• JavaScript Debugger

Page 9 of 68

Page 10: Selenium Student Material

• Web Developer• HTML Validator • ColorZilla • DOM Inspector

3.1.6 User Extensions

User extensions are JavaScript files that allow one to create our own customizations and

features to add additional functionality.

There are a number of useful extensions created by users.

Perhaps the most popular of all Selenium-IDE extensions is one which provides flow control in

the form of while loops and primitive conditionals. This extension is the goto_sel_ide.js.

Steps:1. Download goto_sel_ide.js file.2. Save into selenium core extensions folder3. Selenium-IDE’s Options=>Options=>General tab4. Browse extension file

5. Click on OK Button

6. Restart selenium and fire fox.

3.1.7 Format:

Format #: CSV Format

1. Go to ToolsàSelenium 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

Page 10 of 68

Page 11: Selenium Student Material

6. Press the “OK” button

7. Under the Separator Option, select “Comma” and Press “Ok” button

Now we have created two new formats:

1. Comma Separated Values (CSV)

2. Tab Delimited Values (TDV)

Ex#1: Test case with New Format.

1. Open any of the existing test cases you have stored by going to

File à Open à GE Test Case1.html

2. Go to Format à Select CSV Format from the available options3. Save by going File à Save Test Case As option, GE Test Case1.csv 4. Open the GE Test Case1.csv in Excel Application5. With little formatting, you can look at your test cases in a nice formatted way in Excel

Sheet.6. You can able to send your test cases to the Business Users easily through excel sheet.

3.1.8. Selenium Commands A. Verifying Page Elements:

Verifying UI elements on a web page is probably the most common feature of your automated

tests. Selenese allows multiple ways of checking for UI elements.

Ex: 1. an element is present somewhere on the page?

2. specific text is somewhere on the page?

3. specific text is at a specific location on the page? To verify these UI elements.

We are using Assertion or Verification.

Page 11 of 68

Page 12: Selenium Student Material

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. Youcan 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 alocator. If you choose an XPath or DOM locator, you can verify that specific text appears at a specificlocation 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 68

Page 13: Selenium Student Material

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 element’s 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 68

Page 14: Selenium Student Material

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>• name=username (4)• name=continue value=Clear (7)• name=continue Clear (7)• name=continue type=button (7

C. Locating Hyperlinks by Link Text

This is a simple method of locating a hyperlink in your web page by using the text of the link. If twolinks with the same text are present, then the first match 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 DOMThe 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 element’s 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.

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>

• dom=document.getElementById(’loginForm’) (3)• dom=document.forms[’loginForm’] (3)

Page 14 of 68

Page 15: Selenium Student Material

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

Regular Expression Patterns

The “AndWait” Commands – clickAndWait

Store Commands and Selenium Variables

Page 15 of 68

Page 16: Selenium Student Material

You can use Selenium variables to store constants at the beginning of a script

Example Test Case:

storeElementPresentThis corresponds to verifyElementPresent. It simply stores a boolean value–“true” or “false”–

depending on whether the UI element is found.

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

3.1.9. JavaScript and Selenese Parameters

Page 16 of 68

Page 17: Selenium Student Material

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 case’s variables is named storedVars. Whenever you wish to access

or manipulate a variable within a JavaScript snippet, you must refer to it as stored-

Vars[’yourVariableName’].

3.1.9.1. JavaScript Usage with Script Parameters

Several Selenese commands specify a script parameter including assertEval, verifyEval,

storeEval, and waitForEval. These parameters require no special syntax. A Selenium-IDE user

would simply place a snippet of JavaScript code into the appropriate field, normally the Target

field (because a script parameter is normally the first or only parameter).

This next example illustrates how a JavaScript snippet can include calls to methods, in this case

the JavaScript String object’s toUpperCase method and toLowerCase method.

3.1.9.2. JavaScript Usage with Non-Script Parameters

JavaScript can also be used to help generate values for parameters, even when the parameter

is not specified to be of type script. However, in this case, special syntax is required–the

JavaScript snippet must be enclosed inside curly braces and preceded by the label javascript,

as in javascript {*yourCodeHere*}. Below is an example in which the type command’s second

parameter value is generated via JavaScript code using this special syntax:

Page 17 of 68

Page 18: Selenium Student Material

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

3.1.9.3. echo - The Selenese Print CommandSelenese has a simple command that allows you to print text to your test’s output.

Exercises:

TC#4:

• Open a specific URL (http://www.barnesandnoble.com/)

• Search for a specific text (“Javascript”) in #1 page

• Sort by “Prizev”

• How do you check “Online Price: $$$” is in sorted order?

• In this case I have decided to check the first two Amounts displayed on that page are in

the ascending order.

• The first value is A, the second value is B

• If A <= B then we assume the first two listed prices are in ascending order.

• Now get the third value C

• If B <= C then we assume that A, B and C are in ascending order. (i.e., A <= B <=C )

Page 18 of 68

Page 19: Selenium Student Material

Page 19 of 68

Page 20: Selenium Student Material

AlertPresent

• verifyAlertPresent()

– The best way to check the alerts are using this command

– This command never throws an exception

• Returns:

– True or False.

• Other AlertPresent Commands are:

– storeAlertPresent ( seleniumVariableName )

– assertAlertPresent ( )

– assertAlertNotPresent ( )

– verifyAlertNotPresent ( )

– waitForAlertPresent ( )

– waitForAlertNotPresent ( )

Ex1:

Ex 2:

goBack:

• goBack and goBackAndWait are the two commands simulates a user clicking on the

“back” button of the browser.

• Download the SelectAWebSite.html under Exercises.

• Record the test as listed below:

– Select Google, after going to Google assertTitle then go back

– Select Portnov, after going to PortNov assertTitle then go back

Page 20 of 68

Page 21: Selenium Student Material

– Select Microsoft, after going to MicroSoft assertTitle then go back

– Select Yahoo, after going to MicroSoft assertTitle then go back

waitForPopup

Page 21 of 68

Page 22: Selenium Student Material

• waitForPopUp ( windowID,timeout ) and selectWindow ( windowID ) are the two commands allows you to test the Popup Windows.

• selectWindow selects a specific Popup, use null to select Parent window.

• Download Ex1.html to Ex3.html under wait for Popup, Open CreatePopUps.html in Firefox browser.

• Record the test as listed below:

– Click Create Windows button

– Select win1, click the button “Click and get the Welcome Message”, minimize win1

– Select win3, select any option, press “Submit” button

Go back to the parent window, press “close button”

Ex:

Page 22 of 68

Page 23: Selenium Student Material

3.1.10. Java Script

What is the use of java script?

1. Java script can be used by for printing some dynamic html contents2. For validating the forms in the web page3. Ajax - CE is advanced one for java script.

Print:- document. write

We can use java script in 3 modes in html

In <HEAD> tag In <body> tag And external key

External java script;- (java script with in the page)

Script.js(file name)

document.write(“JS from script.js page<br>”);

Ex:-

<html>

<head>

<script src=’script.js’ type=’text/javascript’ language=”javascript”>

</script>

</head>

</html>

Variables:-

Ex:- a=10;

document.write(a);

Ex;- a=10;

document.write(a);

a=’’java script”; /*modifying variable */

document.write(a);

Comment lines - Two types

// -> single line comment

/* multiline comments */

Page 23 of 68

Page 24: Selenium Student Material

Detecting errors in JavaScript (fire fox);-

In fire fox browser Go to tools Select error console.

Data types:-

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)->Typeof(exp):- it wise display exp type

Ex:- 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’

Page 24 of 68

Page 25: Selenium Student Material

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.”);

ParseFloat:-

Ex 1:- f=”12.5 tonnes”

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: Unary – single operand

Binary- two operand

Territory-three operand

Assignment operators: (=,+=,-=,*=,/=,%=) Arthemetic operators: (+,-,*,/,%) Relational operators: (<,>,<=,>=) Comparision operators: (==,===,!=,!==)

Page 25 of 68

Page 26: Selenium Student Material

Iteration operators: (++,--) Logical operators: (&&,||,1) Conditional operators: (?:)

(or)Ternary operators

String Concatination: +

Iteration operators:-

Pre increment:- (++x)

X=10;

Y=++x;

Output= starts from 11, 12,

Post increment:- (x++)

X=10;

Y=x++;

Output= starts from 10, 11,

Ex:- (post increment)

X=10;

document.write(‘x=’+(x)+’<br>’); Output : x=10

document.write(‘x=’+(x++)+’<br>’); Output :x++=10

document.write(‘x=’+(x)+’<br>’);//x=11

Ex:- (pre increment)

X=10;

D.W(‘x+’+(x)+’<br>’; x=10

D.W(“x=’+(++x)+’<br>’); x=11

D.W(‘x=’ +(x)+’<br>’); x=11

-> Pre decrementation:-

X=10

Page 26 of 68

Page 27: Selenium Student Material

d.w(‘x=’+(--x)+’<br>’); x=9

-> post decrementation:-

X=10

d.w(‘x=’+(x)+’<br>’); x=10

d.w(‘x--=’+(x--)+’<br>’); x=10

d.w(‘x=’+(x)+’<br>’); x=9

Logical operators:-

x y X&&y X||y

t t t t

t f f t

f t f t

f f f f

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:- (condition)? “true Black”:”False Black”;

Ex:- x=9;

Type=(x%2==0)?”Even”:”odd”;

Control structure:-

Control structures is divided into two ways

1. Conditional Based

2. Loop Based

1. Conditional based :-

1. IF,

Page 27 of 68

Page 28: Selenium Student Material

2. IF –else3. IF-else IF ladder4. Nested if and5. 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:-

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

Page 28 of 68

Page 29: Selenium Student Material

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

Page 29 of 68

Page 30: Selenium Student Material

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

Arrays:-

Array is a collection of similar elements Syntax for creating the array is

<var name>=new Array (value 1,value 2,…value n);Ex:- users=new Array(‘sree’,siva’,’mahe’);To get length of array:-users.length: 3(//maximum numerical index +1)users[0];//sreeusers[1];//siva

we can replace value of arrayusers[1]=”ram”;we can add one more field to the arrayusers[3]=”rama”;

To get array countusers[users.length]=’mary’; [Appending].

Ex:-Tags=new Array(‘barbie’,’Teddy’,’mickey’,’donald’);d.w(‘toys.length=’+toys.length+’<br>);//4d.w[‘toys[2]=’’+toys [2]+’<br>’);//mickeyd.w[‘toys=’+toys+’<br>’);//B,T,M,D.toys[3]+=’Duck’;d.w(‘toys=’+toys+’<br>’);// B,T,M,D,Dtoys[toys.length]=’Newtoy’;d.w(‘toys=’+toys+’<br’>);//B,T,M,D,D,N

Multidimentional arrays:- Ex:- a=new Array(2,4);B=new Array(6,8);Multi=new Array(a,b);B=new Array(‘1’,’name’));d.w(‘multi[0][0]=’tmulti[0][1]+’<br>’);

Page 30 of 68

Page 31: Selenium Student Material

Loops:- While

While(condition){ Code}

Ex:1 i=1; while(i<=3)

{d.w(i);i++;}

Ex:-2Mon=new Array (‘jan’,’feb’,’mar’,..’dec’);

m=0;While(m<mon.length){d.w(‘month name=’+mon[m]+’<br>’);mi++;}

Do-while:-Do{Code;}while(condition)Ex:-

i=0Do{d.w(i);i++;}while(i<=5);

For:-For(initialization,condition,incrementation){Code}Ex:1-

For(i=1;i<=3;i++){d.w(i);}

Ex:-2Mon=new Array(‘jan’,’feb’,’mar’,…’dec’);

Page 31 of 68

Page 32: Selenium Student Material

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 Arg ReturnI * *II yes *III * yesIV yes yes

Two types of functions

1. User defined functions2. Built in functions

User defined functions:- A user define function is re-usable block of code. Functions can be classified into fur types, based on arguments and values.

Type 1:-Syntax:- function function name()

{Code;[return<value>;]}

Ex:- for type 1Function welcome(){document.write(“welcome to the site%”);}Welcome();X=welcome();//user defineDocument write(‘x=’+x+’,<br>’);

For Type 2 category:-Function bold(text){document.write(‘<b>’+text+”<br>”);

Page 32 of 68

Page 33: Selenium Student Material

ex:- for type 2function welcome(user){Document.write(“welcome”+user+”<br>”);}Welcome(“sree”);

Type 3-functions:-Function x(){return 9;}P=x();Ex:- function x(){d.w(“first value is’);return 9;d.w(“last value is’);calling function:-a=x();d.w(‘a=’+a+’<br>’);output:- first+val is a=9;

Type 4:- function with arguments and return valuesFunction square(x){Return(x*x);}d.w(suqre(2));//4d.w(square(suqre(2));//16Built in methods:-

Date:-D=new Date();d.getDate();//1-11d.getDay();//0-6d.getMonth();//0-11d.getYear();d.getFullyear;//2009d.getHours();//0-23d.getMinutes();//0-59d.getSeconds();//0-59Ex:- for Built-inFunction p(text);{Document.write(text+’<br>’);}d=new Date();P(‘d+’+d);P(‘d.getdate()=’+d.getDate());P(‘d.getday()=’+d.getday());

Page 33 of 68

Page 34: Selenium Student Material

…………… Math:-

Math;max(12,14);//14Math;min(12,14);//12Ex:-Function p(text){d.w(text+’<br>’);}//math.max(num1,num2);-> numP(‘math.max(12,14)=’+Math.max(12,14));//Math.min(num1,num2);->numP(‘math.min(12,14)=’+Math.min(12,14));//math.floor(num);->Lower limitation integer valueP(‘math.floor(12.94)=’+Math.floor(12.94));//12//math.ceil(num);->upper limitation integer valueP(‘math.ceil(12.14)=’+Math.ceil(12.14));//13//math.round(num)-> if >=.5 ceil,<.5 floorP(‘math.round(12.14)=’+Math.round(12.14));P(‘math.round(12.14)=’+Math.round(12.54));//math.random()->0 and 1P(‘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:- falseP(‘reg(“^a”,”abc”)=’+reg(“^a”+”_abc”));

Page 34 of 68

Page 35: Selenium Student Material

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:- falseP(‘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:- falseP(‘reg(“^.$”,”a”)=’+reg(“^.$”+”a”));Output:- TrueP(‘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:- TrueP(‘reg(“a+$”,”aaa”)=’+reg(“a+$”+”aaa”));Output:- FalseP(‘reg(“a+$”,”ab”)=’+reg(“a+$”+”ab”));Output:- false

* 0 to many timesEx:- P(‘reg(“a*$”,””)=’+reg(“a*$”+””));Output:-TrueP(‘reg(“a*$”,”aa”)=’+reg(“a*$”+”aa”));Output;- TrueP(‘reg(“a*$”,”ab”)=’+reg(“a*$”+”ab”));Output:- False

? 0 or min one time or no.of timesP(‘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-> AlphanumericEx:- P(‘reg(“^[a-z]${3}”,”abc”)=’+reg(“^[a-z]${3}”+”abc”));Output:- TrueP(‘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)

Page 35 of 68

Page 36: Selenium Student Material

{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){Return reg(‘^[a-zA-Z0-9]\\w{3,}\.\\a{2,}@[a-zA-Z0-9\-]{2,}\.[a-zA-Z\.]{2,}$’,mail);}[email protected];P(isEmail(ma?’valid’:’invalid’;</script></head></html>Ex:- User nameFunction 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

Page 36 of 68

Page 37: Selenium Student Material

test cases in HTML tables

• Record-Playback mode (Selenium IDE)

• Selenium Remote Control (RC) Mode

test-cases in your language of choice

Test Runner Demo• See Demo suite

• Look at tests bundled with Selenium

• Running selenium test in slow and fast mode

Selenium IDE Commands

1. allowNativeXpath(allow)Arguments:

allow - boolean, true means we'll prefer to use native XPath

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)

Page 37 of 68

Page 38: Selenium Student Material

Generated from getAllButtons()Returns:the IDs of all buttons on the pageReturns the IDs of all buttons on the page.

6. assertAllFields(pattern)Generated from getAllFields()Returns:the IDs of all field on the pageReturns the IDs of all input fields on the page.

7. assertAllLinks(pattern)Generated from getAllLinks()Returns:the IDs of all links on the pageReturns the IDs of all links on the page.

Similarly some other commands:

assertAllWindowIds, assertAllWindowNames, assertAllWindowTitles, assertAttribute, assertAttributeFromAllWindows.

assertNotAllButtons, assertNotAllFields,assertNotAllWindowIds, assertNotAllWindowNames, assertNotAllWindowTitles, assertNotAttribute, assertNotAttributeFromAllWindows.

assertElementPresent(locator)

Generated from isElementPresent(locator)

Arguments:

locator - an element locator

Returns:true if the element is present, false otherwiseVerifies that the specified element is somewhere on the page.

Similarly some other commands: assertElementNotPresent

assertEval(script, pattern)Generated from getEval(script)

Arguments:

script - the JavaScript snippet to run

Returns:

Page 38 of 68

Page 39: Selenium Student Material

the results of evaluating the snippetGets the result of evaluating the specified JavaScript snippet. The snippet may have multiple lines, but only the result of the last line will be returned.

Similarly: assertExpression,

assertHtmlSource(pattern)Generated from getHtmlSource()

Returns:the entire HTML sourceReturns the entire HTML source between the opening and closing "html" tags.

assertLocation(pattern)Generated from getLocation()

Returns:the absolute URL of the current pageGets the absolute URL of the current page.

assertNotXpathCount(xpath, pattern)Generated from getXpathCount(xpath)

Arguments:

xpath - the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you.

Returns:the number of nodes that match the specified xpathReturns the number of nodes that match the specified xpath, eg. "//table" would give the number of tables.

Similarly: assertXpathcount

assertText(locator, pattern)Generated from getText(locator)

Returns:the text of the elementGets the text of an element. This works for any element that contains text. This command uses either the textContent (Mozilla-like browsers) or the innerText (IE-like browsers) of the element, which is the rendered text shown to the user.

Similarly: assertTitle, assertTable, assertSpeed, assertPromt,assertVisible, aasertValue

assignId(locator, identifier)

Arguments:

locator - an element locator pointing to an element identifier - a string to be used as the ID of the specified element

Temporarily sets the "id" attribute of the specified element, so you can locate it in the future using its ID rather than a slow/complicated XPath. This ID will disappear once the page is reloaded.

Page 39 of 68

Page 40: Selenium Student Material

Similarly: assignIdAndWait

captureEntirePageScreenshot(filename, kwargs)

Arguments:

filename - the path to the file to persist the screenshot as. No filename extension will be appended by default. Directories will not be created if they do not exist, and an exception will be thrown, possibly by native code.

kwargs - a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" . Currently valid options:

backgroundthe background CSS for the HTML document. This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text).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 non-HTA 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.

Page 40 of 68

Page 41: Selenium Student Material

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

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

Page 41 of 68

Page 42: Selenium Student Material

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.

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: removeScriptAndWaitrunScript(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,

Page 42 of 68

Page 43: Selenium Student Material

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.

This command is a synonym for storeExpression.

Similarly: storeAlert, storeAlertPresent, storeAllButtons, storeAllFields, storeAllLinks, storeAllWindowIds, storeAllWindowNames, storeAllWindowTitles, storeAttribute, storeBodyText, storeConfirmation, storeConfirmationPresent etc…..

storeCookie, storeCookieByName, storeCookiePresent, etc……

storeEval(script, variableName)Generated from getEval(script)

Arguments:

script - the JavaScript snippet to run

Returns:the results of evaluating the snippet

similarly: storeExpression etc……

storeXpathCount(xpath, variableName)Generated from getXpathCount(xpath)

Arguments:

xpath - the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you.

Returns:the number of nodes that match the specified xpathReturns the number of nodes that match the specified xpath, eg. "//table" would give the number of tables.

submit(formLocator)

Arguments:

Page 43 of 68

Page 44: Selenium Student Material

formLocator - an element locator for the form you want to submit

Submit the specified form. This is particularly useful for forms without submit buttons, e.g. single-input "Search" forms.

Similarly: submitAndWait

type(locator, value)

Arguments:

locator - an element locator value - the value to type

Sets the value of an input field, as though you typed it in.

Similarly: typeAndWait

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

Page 44 of 68

Page 45: Selenium Student Material

Returns:the text of the element

Similarly: verifyTitle,verifyTable etc…..

waitForAlert(pattern)Generated from getAlert()

Returns:The message of the most recent JavaScript alertRetrieves 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()Generated from isConfirmationPresent()

Returns:true if there is a pending confirmationHas confirm() been called?

Similarly: waitForCondition

waitForTitle(pattern)Generated from getTitle()

Returns:the title of the current pageGets the title of the current page.

Similary: waitForTable etc……

Tc#1 : Verify Page Title and specified Text

GE Test Case 1

open http://www.ge.com/

type textToSearch energy efficient

clickAndWait searchSubmit

assertTitle exact:GE: Search Results

assertTextPresent energy efficient

Tc# 2:

Page 45 of 68

Page 46: Selenium Student Material

GE Test Case2

open http://www.ge.com/

assertTitle GE : imagination at work

clickAndWait //div[@id='ge_footer']/ul/li[2]/a

assertTitleGE Contact Information: Web Questions, Online Help, Press Contacts

clickAndWait link=Feedback and Inquiries

assertTitle Feedback & Inquiries : Contact Information : GE

pause 3000

select contact_subject label=Other

select contact_countrylabel=United States

type contact_email [email protected]

type contact_comments No questions.

clickAndWait //form[@id='contact_form']/p/input

verifyTextPresent Thank you for taking the time to contact GE.

verifyTextPresent Feel free to continue browsing

verifyElementPresent link=GE.com Home Page

Tc# 3: Verify alerts

Age Test Case

open file:///C:/Javascript/Class%20Ex/Ex16.html?txtAge=101&=Submit

assertTitle Age Problem

verifyTextPresent Enter Your Age

type idAge -1

click idSubGo

open Infant

type idAge 5

click idSubGo

deleteCookie Kid

type idAge 20

click idSubGo

Page 46 of 68

Page 47: Selenium Student Material

Age Test Case

assertAlert Adult

type idAge 55

click idSubGo

assertAlert Senior

type idAge 75

click idSubGo

assertAlert Grand Senior

type idAge 110

click idSubGo

assertAlert I hate this life

type idAge www

check idSubGo

pause 5000

clickAndWait idSubGo

assertAlert Something wrong, enter your right age!

Tc# 4: Wait for Text Present

TC_Google_EE

open http://www.google.com/

type q energy efficient

clickAndWait btnG

waitForTextPresent energy efficiency

assertTitle energy efficient - Google Search

Tc #5: Creating Variables and storing data and calling multipletimes

TestCase_HelloWorld

open file:///C:/2009%20Selenium/Day3/Ex/HelloWorld.html

store Kangeyan vName

echo ${vName}

answerOnNextPrompt ${vName}

click link=Click here to enter your name

waitForPrompt Please enter your name.

Page 47 of 68

Page 48: Selenium Student Material

TestCase_HelloWorld

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 javascript

clickAndWait quick-search-button

pause 10000

clickAndWait link=Price

storeText//div[@id='bs-center-col']/div[3]/div[1]/div[2]/div/div/div/ul[1]/li[2]/strong

T1

echo ${T1}

storeTextxpath=id('bs-center-col')/div[3]/div[3]/div[2]/div/div/div/ul[1]/li[1]/strong

T2

echo ${T2}

storeText//div[@id='bs-center-col']/div[3]/div[5]/div[2]/div/div/div/ul[1]/li[1]/strong

T3

echo ${T3}

storeEvalvar A= new Number("${T1}".substr(1));var B=new Number("${T2}".substr(1)); var Result1=false; if (A<=B) Result1=true;Result1

T4

echo ${T4}

storeEvalvar B= new Number("${T2}".substr(1));var C=new Number("${T3}".substr(1)); var Result2=false; if (B<=C) Result2=true;Result2

T5

echo ${T5}

storeEval var Result1= new Boolean("${T4}");Result1 R1

echo ${R1}

storeEval var Result2= new Boolean("${T5}");Result2 R2

echo ${R2}

storeEvalvar Result1= new Boolean("${T4}");var Result2=new Boolean("${T5}");  Result1 && Result2

T6

store true T7

echo ${T6}

verifyExpression ${T6} ${T7}

echo ${T7}

Page 48 of 68

Page 49: Selenium Student Material

Reviewed Test Case Barnes and Noble Sorted Order

storeEvalvar isSorted = new Boolean("${T6}"); var strResult ='Not in Sorted Order'; if (isSorted) strResult='Ascending Order'; strResult

vSorted

echo ${vSorted}

Tc# 7: Example For Alert Massege

Test Case Alert Button Click

open file:\\C:\2009 Selenium\Day 3\Ex\ClickAlert.html

click //input[@value='Click and get the Welcome Message']

assertAlert Welcome to Portnov!

Tc# 8: Example For goBackAndWait

Test Case Go Back And Wait

open file:\C:\2009 Selenium\Day 3\Ex\SelectAWebSite.html

select OptWeb label=Google

clickAndWait btnGo

assertTitle Google

goBackAndWait

select OptWeb label=Portnov

clickAndWait btnGo

assertTitleCareer Training & Career Change: Software Testing and Software QA (Quality Assurance) @ Portnov Computer School

goBackAndWait

select OptWeb label=Microsoft

clickAndWait btnGo

assertTitle Microsoft Corporation

goBackAndWait

select OptWeb label=Yahoo

clickAndWait btnGo

assertTitle Yahoo!

Page 49 of 68

Page 50: Selenium Student Material

Tc#9: Example for Alert conformation

Reviewed Test Case Popup

open file:\\C:\2009 Selenium\Day 3\Ex\CreatePopUps.html

click winBut

waitForPopUp win1 30000

waitForPopUp win2 30000

waitForPopUp win3 30000

selectWindow name=win1

click //input[@value='Click and get the Welcome Message']

assertAlert Welcome to Portnov!

selectWindow name=win3

click //input[4]

click Submit

assertConfirmation Are you sure you want to submit this answer?

assertAlert submitted

selectWindow null

click //input[@name='winBut' and @value='Close Windows']

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

assertAlertregex:Ex1.htmlwin1

assertAlertregex:Ex2.htmlwin2

Page 50 of 68

Page 51: Selenium Student Material

Reviewed Test Case Window Name Check

assertAlertregex:Ex3.htmlwin3

Tc#11: Regular Expression

Reviewed Test Case RegEx Email Check

openfile:///C:/2009%20Selenium/Day%204/Ex/UserInputForm.html

type txtName kangs p

type txtEmail [email protected]

click //input[@value='Submit']

verifyTable

//form[@id='frm']/table.1.2 Valid

verifyTable

//form[@id='frm']/table.2.2 Valid

storeValue

txtName selName

echo ${selName}

storeValue

txtEmail selEmail

echo ${selEmail}

assertEval

storedVars['selName'] regex:\w+\s\w+

assertEval

javascript:jStr=storedVars['selEmail']; jStr.toLowerCase()

regex:^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$

Narrating Regular Expression Tc’s

Store Value

Name and Email are stored in a Selenium Variable Use echo to see the values in Log

Narrating Test Cases

openfile:///C:/2009%20Selenium/Day%204/Ex/Narrating Test Cases.html

type txtName kangs p

type txtEmail [email protected]

Page 51 of 68

Page 52: Selenium Student Material

Narrating Test Cases

storeValue txtName selName

echo ${selName}

storeValue txtEmail selEmail

echo ${selEmail}

click //input[@value='Submit']

verifyTable //form[@id='frm']/table.1.2 Valid

verifyTable //form[@id='frm']/table.2.2 Valid

Regular Expression Testing

Name is tested with regex:\w+\s\w+ Email is first converted into lower case then tested using regex.

assertEval

storedVars['selName'] regex:\w+\s\w+

assertEval

javascript:jStr=storedVars['selEmail']; jStr.toLowerCase()

regex:^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$

Testing Highlight

Verify Text with exact spelling "Name" using XPath Highlight a text using XPath

verifyText //form[@id='frm']/table/tbody/tr[2]/td[1]/span[1] exact:Name:

highlight //form[@id='frm']/table/tbody/tr[2]/td[1]/span[1]

Assert Element Present

Valid Name Id is present Valid Email ID is present

assertElementPresent idNameDisp

assertElementPresent idEmailDisp

Page 52 of 68

Page 53: Selenium Student Material

Tc#11:

Test Case DevryPopupWindows Close

openhttp://www.devry-degrees.com/7x/prequal.jsp;jsessionid=GYW5fw1VxepITK3Fi7CXsg**.app8-all1?redirected=redirect&CLK=0&CCID=&QTR=&ZN=&ZV=&KY_T=

refresh

setSpeed 3000

assertTitle DeVry Online Focus Site

click //div[@id='footerlogo']/table/tbody/tr[1]/td[1]/a[1]/u

waitForPopUp

Thandie 30000

selectWindow name=Thandie

assertTitle Accreditation - DeVry University

click //html/body/table/tbody/tr[4]/td/a

selectWindow null

click //div[@id='footerlogo']/table/tbody/tr[1]/td[1]/a[1]/u

waitForPopUp

Thandie 30000

selectWindow null

pause 10000

click //div[@id='footerlogo']/table/tbody/tr[1]/td[1]/a[2]/u

waitForPopUp

Thandie 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

waitForPopUp

Thandie 30000

selectWindow name=Thandie

assertTitle Your California Privacy Rights

click //html/body/table/tbody/tr[2]/td/a

selectWindow null

Page 53 of 68

Page 54: Selenium Student Material

Test Case DevryPopupWindows Close

click //div[@id='footerlogo']/table/tbody/tr[1]/td[2]/a[2]/u

waitForPopUp

Thandie 30000

selectWindow name=Thandie

assertTitle Privacy Policy - DeVry University

click //html/body/table/tbody/tr[2]/td/a

selectWindow null

Tc#12: Verify Page Load Time

Test Case for PageLoadTime_Simple

open http://www.yahoo.com/

storeEval (new Date()).getTime() StartTime

refresh

waitForPageToLoad 3000

storeEval (new Date()).getTime() EndTime

echo ${StartTime}

echo ${EndTime}

storeEval (${EndTime}-${StartTime})/1000 PageLoadTime

echo ${PageLoadTime} Seconds

storeEval (new Date()).getTime() StartTime

open http://www.yahoo.com/

waitForPageToLoad 3000

storeEval (new Date()).getTime() EndTime

storeEval (${EndTime}-${StartTime})/1000 PageLoadTime

echo ${PageLoadTime} Seconds

Tc#13: AvgPageLoadTime

Test Case for PageLoadTime

open http://www.yahoo.com/

storeEval (new Date()).getTime() StartTime

refresh

Page 54 of 68

Page 55: Selenium Student Material

Test Case for PageLoadTime

waitForPageToLoad 3000

storeEval (new Date()).getTime() EndTime

echo ${StartTime}

echo ${EndTime}

storeEval (${EndTime}-${StartTime})/1000 PageLoadTime1

echo ${PageLoadTime1} Seconds

storeEval (new Date()).getTime() StartTime

open http://www.yahoo.com/

waitForPageToLoad 3000

storeEval (new Date()).getTime() EndTime

storeEval (${EndTime}-${StartTime})/1000 PageLoadTime2

echo ${PageLoadTime2} Seconds

storeEval (${PageLoadTime1}+${PageLoadTime2})/2 AvgPageLoadTime

echo ${AvgPageLoadTime} Seconds

Tc# 14: Page Load Time in milli Seconds

Test Case for PageLoadTime_MilliSeconds

storeEval var d=(new Date().getTime()); d; timeBeforeLoad

echo ${timeBeforeLoad}

storeEvalopen("http://www.ge.com/");var win=this.browserbot.getCurrentWindow(); if(win)win.onload=(window.status=(new Date().getTime()));

timeAfterLoad

echo ${timeAfterLoad}

storeEval ${timeAfterLoad}-${timeBeforeLoad} loadTimeMSecs

echo ${loadTimeMSecs}

Tc#15: Get Xpathcount, rows count and TablecountXXX

Page 55 of 68

Page 56: Selenium Student Material

Test Case Xpath

open file:///C:/2009 Selenium/Day4/Ex/ListofCourses.html

assertTitle AssertXPath

storeElementPresent //table[@id='idCourse']/tbody/tr[7]/td[3] Txt1

echo ${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 7

verifyXpathCount //table[@id='idCourse']/tbody/tr[1]/td 4

verifyXpathCount //table[@id='idCourse']/tbody/tr/td 28

verifyTable idCourse.0.0 S#

verifyTable idCourse.0.1 Course Name

verifyTable idCourse.4.0 4

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 6

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}

Page 56 of 68

Page 57: Selenium Student Material

Selenium CoreIntroduction:

• Selenium Core is a test tool for web applications.

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

• Selenium was designed specifically for the acceptance testing requirements of Agile teams.

Selenium Core Concepts

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

• Application Functional testing. Create regression tests to verify application functionality and user acceptance.

HTA Mode in IE

• HTML Applications (HTAs) are full-fledged web applications.

• These applications are trusted by the Microsoft Internet Explorer browser.

• 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 channel–download technology—without enforcing the strict security model and user interface of the browser.

• HTAs can be created using the HTML and Dynamic HTML (DHTML).

HTA Mode in Selenium Core

• Selenium Core provides an additional mechanism for running automated tests called "HTA mode."

Page 57 of 68

Page 58: Selenium Student Material

• HTA Mode only works on Windows, and only with IE.

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

Installing Selenium Core

• Installing Selenium Core is a two step process

– First: Install an web server (e.g. Apache)

– Second: Install the Selenium Core under the Web Server

• You need to install the Selenium Core within the web server where AUT is deployed.

1. Installing Apache Web Server• Go to http://httpd.apache.org/download.cgi

• Download Win32 Binary without crypto (no mod_ssl) (MSI Installer):

• apache_2.2.11-win32-x86-no_ssl.msi

• Double click the downloaded file and install it

2. Check Apache Works• Open your Windows Explorer

• Go to C:\Program Files\Apache Software Foundation\Apache2.2\htdocs

• Check index.html file is there

• Open index.html check whether it will display “it works” Message or Not.

3. Installing Selenium Core• Create a folder under (*1)

– C:\Program Files\Apache Software Foundation\Apache2.2\htdocs

• Name the new folder as “Selenium”

– C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\Selenium

• Go to http://seleniumhq.org/download/

• Right Click on the Download Link under Selenium Core, and download the file under Apache web server

• Save the selenium-core-1.0-beta-2.zip file

Page 58 of 68

Page 59: Selenium Student Material

• Under the folder C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\Selenium

• Right click on the Zip file, and unzip by Selecting winzip à select Extract to here

• In your address bar type the below URL:

• http://localhost/Selenium/core/TestRunner.html

• If you are able to see Selenium Test Runner Control Panel, then the installation is complete and successful.

Selenium Core Test Suites

1. Open Selenium IDE2. Create multiple Test cases, save with .html extensions.3. Create these test cases as Testsuite.html4. In Windows Explorer Go to C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\Selenium5. Create a new folder called “oragehrm” 6. Save all Test cases, Test Suites under “orangehrm” Folder.

Running Test cases with IE Browser

1. Open your IE browser, go to http://localhost/Selenium/core/TestRunner.html

2. In the test suite input box, type as follows:3. ../orangehrm/TestSuite.html4. Press “Go” button5. Now, you can run either individual test cases or entire suite. Do as you wish.

Running Test cases with Firfox Browser

1. Open your Firefox browser, go to http://localhost/Selenium/core/TestRunner.html

2. In the test suite input box, type as follows:3. ../orangehrm/TestSuite.html4. Press “Go” button5. Now, you can run either individual test cases or entire suite. Do as you wish.

Running the Test Suite Using HTA Mode

• Test now in IE browser

– http://localhost/Selenium/core/TestRunner.hta

– A File download – Security Warning may display

– Click “Run” button

Page 59 of 68

Page 60: Selenium Student Material

• In the test suite input box, type as follows:

– ../oragehrm/TestSuite.html

• Press “Go” button

• Now, you can run either individual test cases or entire suite. Do as you wish.

Difference between HTA & HTML Mode

• HTA Mode allows you to save the results to a file

Page 60 of 68

Page 61: Selenium Student Material

Selenium-RC

1. IntroductionSelenium-RC is the solution for tests that need more than simple browser actions and linear execution.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.You’ll want to use Selenium-RC whenever your test requires logic not supported by Selenium-IDE.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

• Installing Selenium Remote Control (RC) requires three step process:

– First: Install JRE 1.5 or later

– Second: Install the Selenium RC

– Third: Install Ruby Client

Checking JRE

• Go to Start à Run à cmd

– Java – version (*1)

• If you see an older version (< 1.5) it is better to uninstall it

Second: Installing Selenium RC

Page 61 of 68

Page 62: Selenium Student Material

• Go to http://seleniumhq.org/download/

• Select RC download (*1) link and store the file in C:\

• UnZip the selenium-remote-control-1.0-beta-2-dist.zip in C:\

• Rename the selenium-remote-control-1.0-beta-2 folder into SeleniumRC

• Rename the selenium-java-client-driver-1.0-beta-2 folder into JavaClient

• Rename the selenium-server-1.0-beta-2 into JavaServer

• Open Windows Explorer go to C:\SeleniumRC\JavaServer

• Go to Start à Run à Cmd (enter the following command)

• Cd C:\SeleniumRC\JavaServer

• Java -jar selenium-server.jar -interactive

Third: Install Ruby Client

Install Ruby into C:\ Go to Start à Run à cmd

- Cd c:\seleniumRC\RubyClient\

- gem install selenium-client Make sure it shows successfully installed selenium-client

Start Selenium server with Batch File

– Open Note Pad and Type below– java -jar C:\SeleniumRC\JavaServer\selenium-server.jar – Save as .bat extension

Stop Selenium server in IE"C:\Program Files\Internet Explorer\iexplore.exe" http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer

3. Run a Simple TestStep1: save Test case with rb extenstion

• Open the test case in Selenium IDE• Go to Options à Format à Ruby – Selenium RC• Select File à Save Test Case As • Save the file name as “name.rb” in C:\PrgRuby

Step2: Start the Selenium Server

• Go to Start à Run à cmd

– Java -jar selenium-server.jar (*7)

• Keep the server running (Do not close this cmd line window)

Step3: Run the Ruby Test

Page 62 of 68

Page 63: Selenium Student Material

• Open another cmd line window, go to Start à Run à cmd

• Navigate to the path where you have saved “testEE.rb”

– Cd c:\ruby

– Execute the below command

– Ruby testEE.rb

4. Platforms Supported by Selenium RC

• Browsers

– Firefox, IE, Safari and Opera etc..

• Operating Systems

– Windows, OS X, Linux, and Solaris

• Programming Languages

– C#, Java, Perl, PHP, Python, and Ruby

• Testing Frameworks

– Bromine, JUnit & TenstNG (Java), NUnit (.Net), RSpec & Test::Unit (Ruby), unittest (Python)

5. RC Command Line Options

Usage: java -jar selenium-server.jar [-interactive] [-options]

• port <nnnn>:(default 4444)

– the port number the selenium server should use

• timeout <nnnn>: (eg: 180)

– an integer number of seconds

• interactive:

– Interactively enter the commands.

• multiWindow:

– Tests are executed in a separate window and supports web pages with frames.

• forcedBrowserMode <browser>: (eg: *iehta)

Page 63 of 68

Page 64: Selenium Student Material

– sets the forced default browser mode (e.g. "*iexplore“) for all sessions, no matter what is passed in getNewBrowserSession

• userExtensions <file>:

– indicates a JavaScript file that will be loaded into selenium

• browserSessionReuse:

– stops re-initialization and spawning of the browser between tests

• avoidProxy:

– Uses by default proxy for browser request

– set this flag to make the browser use proxy only for URLs containing '/selenium-server'

• firefoxProfileTemplate <dir>:

– By default generates a fresh empty Firefox profile for every test.

– Provide a directory to use your profile directory instead.

• debug:

– Debug mode provides more trace information and used for diagnostics purpose

• log:

– When enabled writes debug information out to a log file

• htmlSuite <browser> <startURL> <suiteFile> <resultFile>:

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

– A proxy injection mode is a mode where the selenium server acts as a proxy server for all content going to the AUT. Under this mode, multiple domains can be visited.

• The following additional flags are supported for proxy injection mode :

– dontInjectRegex <regex>: an optional regular expression that proxy injection mode can use to know when to bypass injection

Page 64 of 68

Page 65: Selenium Student Material

– userJsInjection <file>: specifies a JavaScript file which will then be injected into all pages

• userContentTransformation <regex> <replacement>:

– 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 "-userContentTransformation https http" then all "https" strings in the HTML of the test application will be changed to be "http".

• Java system properties:

– Dhttp.proxyHost and -Dhttp.proxyPort

• Normally Selenium RC overrides the proxy server configuration, using the Selenium Server as a proxy. Use these options if you need to use your own proxy together with the Selenium Server proxy.

• Use the proxy settings like this:

– java -Dhttp.proxyHost=myproxy.com -Dhttp.proxyPort=1234 -jar selenium-server.jar

– HTTP proxy requires authentication, you will also need to set -Dhttp.proxyUser and -Dhttp.proxyPassword, in addition to http.proxyHost and http.proxyPort.

– java -Dhttp.proxyHost=myproxy.com -Dhttp.proxyPort=1234 -Dhttp.proxyUser=joe -Dhttp.proxyPassword=example -jar selenium-server.jar

6. Selenium RC - Interactive Mode Running

• The "interactive mode (IM)" allows you to run your test case commands on the Selenium Server interactively.

• This approach is suited for novice programmers to understand.

• To completely automate the test suites, it is best practice to write your tests in a suitable programming language. Not using interactive mode.

• Type exit to quit from interactive mode

6.1 Selenium RC – Browser Launch Mode

Page 65 of 68

Page 66: Selenium Student Material

Browser Launch Mode Description Cross Domain

*iexplore, *iehta Internet Explorer in HTA mode Yes

*iexploreproxy Internet Explorer HTML mode No

*firefox, *chrome Firefox in Chrome mode Yes

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

• This command accepts two parameters.

• Both are mandatory parameters.

• First Parameter: Browser Launch mode

– Example: *iexplore, *firefox, etc

• Second Parameter: URL

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

Selenium RC – Interactive mode cmd

• Interactive mode allows you to execute commands using cmd command

• The format of the command is as follows:

Page 66 of 68

Page 67: Selenium Student Material

– cmd={Selenese Command}&1={First Parameter}&2={Second Parameter} &sessionId={sessionID got using getNewBrowserSession}

– Example:

– cmd=type&1=q&2=energy efficient&sessionId=500b9ffb521d4c67b37e649a7bd5e527

– cmd=close&sessionId=500b9ffb521d4c67b37e649a7bd5e527

– cmd=waitForTextPresent&1=energy efficiency&sessionId=500b9ffb521d4c67b37e649a7bd5e527

• The session ID is optional. Use session ID when you have multiple sessions.

• Selenese Command Parameter is mandatory.

• Both &1 and &2 parameters are optional. If the Selenese command contains parameter then you may need it.

Selenium RC – Interactive mode Testing

• Open your Windows explorer go to C:\SeleniumRC\JavaServer

• Goto Start à Run à cmd

• if necessary use cd C:\SeleniumRC\JavaServer, then type

– java -jar selenium-server.jar -interactive

• Copy the first line of the code and paste in the interactive mode (*4)

– cmd=getNewBrowserSession&1=*iexplore&2=http://www.google.com

• Press Enter Key

6.2 Selenium RC – Posting Test Results (firefox)

• Open notepad/wordpad

• Cut and Paste the below code.

• Save the batch file with name “GE Test Case.bat”

• Keep the below files under the following directory:

Page 67 of 68

Page 68: Selenium Student Material

– C:\2009 Selenium\Ex\GE

– TestSuite.html

– GE Test Case1.html

– GE Test Case3.html

– GE Test Case.bat

• Double click on the GE Test Case.bat file

• Command window open and run the test suite

• After completing the test, double click on the “FF GE Test Results.html”

6.3 Selenium RC – Posting Test Results (IE)

• Open the batch file “GE Test Case.bat”

• Change the *chrome into *iehta

• Double click and Run the “GE Test Case.bat” file

• After completion look at the posted results in “IE GE Test Results.html”

• Double click the file, see the results in any browser

Page 68 of 68


Recommended