SlideShare une entreprise Scribd logo
1  sur  73
Télécharger pour lire hors ligne
SELENIUM Handbook

                             -a basic referential guide to Selenium




                                     By

                  Sreedhar Reddy (Test Architect)




QA Planet,# 24/3 RT,3rd Floor,SR Nagar,Hyderabad - 500018.
Email :Contact@qaplanet.in || Phone :040-40044448 || Mobile :+91 9966723111
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

1. Introduction:

2. History of Selenium

3. What is Selenium?

4. Selenium Types:

5. Selenium IDE Installation Steps:

6. IDE Features

7. Recording

8. Selenium Commands – “Selenese”

9. Commonly Used Selenium Commands

10. Locating Elements:

11. Basic Examples:

12. Test Suite Creation:

13. Useful Selenium Add-Ons:

14. about User Extensions

15. Selenium Commands for verification

16. Selenium IDE Commands for handling alerts

17. Java Script

18. Example programs:

19. Selenium Core

20. Selenium-RC

21. Selenium Grid:

22. Advantages and Limitations:
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

1. Introduction:

Out of the many open source test automation tools available today, there is one tool that become
very popular in recent times Selenium.

Selenium is a web application test automation tool which provides many features and a wide
range of support which makes it an instant choice for automating most of the web applications.

Selenium provides the automation engineer the choice of running the automation scripts in a
wide range of browsers and with the language support it has, on wide range of operating systems
too.

But there are certain things the automation engineer needs to be aware of before he jumps into
understanding selenium. The automation engineer needs to have a basic knowledge of the
following things:

     1. HTML
     2. XML
     3. Xpaths
     4. Document Object Model(DOM)
     5. JavaScript (only a basic knowledge on how events are triggered etc.)
     6. Any one of the following language to build a full-fledged test suite – Perl, Python, Ruby,
        Java, C#, PHP.
     7. Basic object oriented programming concepts.

Once we are sure that we have the basics of the above mentioned seven points let us move on
into what selenium is all about and various types of selenium.

2. 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+
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------




3. 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 -
              o JavaScript
              o DHTML
              o Frames


4. Selenium Types:
There are 4 types in Selenium, each for a specific purpose. They are as follows:

     1.   Selenium IDE
     2.   Selenium Remote Control
     3.   Selenium Core
     4.   Selenium Grid

The more detail information about these will be given in later in the document. But let us have a
brief introduction about each of these to make ourselves comfortable.

Selenium IDE is a Firefox plugin which is a record replay tool of Selenium. User can record the
actions performed on the browser and replay it. User also has an option to write his own scripts,
save the scripts and develop test suites using Selenium IDE.

Selenium Remote Control on the other hand is used when more robust scripts are to be
developed. Using any of the languages listed previously user can build test suites which are
robust and can run on different platforms, unlike IDE which can run scripts only on Firefox.

Selenium Core usage is similar to Selenium RC except that the scripts which use selenium core
can only be run on the server where the web application is deployed.

Selenium Grid as the name suggests, is used to organize several Selenium RC's and run the
scripts on different machines from a central location where Selenium Grid is available.

Now let us get some hands on on Selenium IDE to understand Selenium better.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------




Working with Selenium IDE:




Above is a snapshot of how Selenium IDE looks.


     5. Selenium IDE Installation Steps:
          •    To install Selenium IDE just goto http://seleniumhq.org/projects/ide/ click on
               download Selenium.
          •    It will be added to your Firefox add-on list.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

          •    Restart Firefox and you should be able to open it from Tools --> Selenium IDE.




     6. IDE Features¶
Menu Bar
The File menu has options for Test Case and Test Suite (suite of Test Cases). Using these you
can add a new Test Case, open a Test Case, save a Test Case, export Test Case in a language of
your choice. You can also open the recent Test Case.
All these options are also available for Test Suite.
The Edit menu allows copy, paste, delete, undo, and select all operations for editing the
commands in your test case. 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. The
Help menu is the standard Firefox Help menu; only one item on this menu–UI-Element
Documentation–pertains to Selenium-IDE.

Toolbar¶
The toolbar contains buttons for controlling the execution of your test cases, including a step
feature for debugging your test cases. The right-most button, the one with the red-dot, is the
record button.



          Speed Control: controls how fast your test case runs.


          Run All: Runs the entire test suite when a test suite with multiple test cases is loaded.


          Run: Runs the currently selected test. When only a single test is loaded this button and
          the Run All button have the same effect.


          Pause/Resume: Allows stopping and re-starting of a running test case.


          Step: Allows you to “step” through a test case by running it one command at a time. Use
          for debugging test cases.


          TestRunner Mode: Allows you to run the test case in a browser loaded with the
          Selenium-Core TestRunner. The TestRunner is not commonly used now and is likely to
          be deprecated. This button is for evaluating test cases for backwards compatibility with
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

          the TestRunner. Most users will probably not need this button.


          Apply Rollup Rules: This advanced feature allows repetitive sequences of Selenium
          commands to be grouped into a single action. Detailed documentation on rollup rules can
          be found in the UI-Element Documentation on the Help menu.


          Record: Records the user’s browser actions.

Test Case Pane

          Your script is displayed in the test case pane. It has two tabs, one for displaying the
          command and their parameters in a readable “table” format.




     7. Recording
     Many first-time users begin by recording a test case from their interactions with a website.
     When Selenium-IDE is first opened, the record button is ON by default. If you do not want
     Selenium-IDE to begin recording automatically you can turn this off by going under Options
     > Options... and deselecting “Start recording immediately on open.”

     During recording, Selenium-IDE will automatically insert commands into your test case
     based on your actions. Typically, this will include:
        • clicking a link - click or clickAndWait commands
        • entering values - type command
        • selecting options from a drop-down listbox - select command
        • clicking checkboxes or radio buttons - click command

     8. Selenium Commands – “Selenese”
          •    Selenium commands, often called selenese, are the set of commands that run your
               tests.
          •    Selenium command are three types as below
                   o Actions,
                   o Accessory
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

                  o Assertions
          •    Actions: user actions on application / Command the browser to do something.
               Actions are commands that generally manipulate the state of the application.
                 1. Click / Clickandwait
                 2. Selecting items

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

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

             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

     9. 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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------


          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.

Note: To execute many Selenium commands, Selenium required a target often called it as
Element Locators (or calls it as object identification).

To get Target element Please install below plug – INS
 1. For Firefox browser – Firebug
 2. For IE browser – IE Developer Tool bar.

How Selenium is Identifying the Objects?:

     10.             Locating Elements:
Selenium is identifying the objects by using following Locator strategies.

     1.   Id = @Id
     2.   Name = @name
     3.   Identifier = @id
     4.   Dom = JavaScript expression
     5.   Xpath = Xpath expression
     6.   Link =Text pattern
     7.   css = css Selector Index

Locating by ID:
For instance, 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" />
7 </form>
8 </body>
9 <html>
The following locator strategies would return the elements from the HTML snippet above
indicated by line number:
       • id=loginForm (3)
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------




Locating by Name¶
     • 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>
 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)


Locating by XPath¶
     • XPath is the language used for locating nodes in an XML document.
     • We are using XPath is when you don’t have a suitable id or name attribute for the
       element you wish to locate.

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>
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

10 <html>
     •    xpath=/html/body/form[1] (3) - Absolute path (would break if the HTML was changed only
          slightly)
     •    //form[1] (3) - First form element in the HTML
     •    xpath=//form[@id='loginForm'] (3) - The form element with attribute named ‘id’ and the value
          ‘loginForm’
     •    xpath=//form[input/@name='username'] (4) - First form element with an input child element
          with attribute named ‘name’ and the value ‘username’
     •    //input[@name='username'] (4) - First input element with attribute named ‘name’ and the
          value ‘username’
     •    //form[@id='loginForm']/input[1] (4) - First input child element of the form element with
          attribute named ‘id’ and the value ‘loginForm’
     •    //input[@name='continue'][@type='button'] (7) - Input with attribute named ‘name’ and the
          value ‘continue’ and attribute named ‘type’ and the value ‘button’
     •    //form[@id='loginForm']/input[4] (7) - Fourth input child element of the form element with
          attribute named ‘id’ and value ‘loginForm’


Example for Xpath:

     • Let us take the source of google.com to make our task simpler.

     • The first three locator strategies state that, if any element having the name, id or identifier
       attribute
     • Observe the source code of below. After we click on the Google Search button we move
       to the results page, now let us understand how the first link is identified from the below
       source code.

<div id="res" class="med">
 <h2 class="hd">Search Results</h2>
 <div>
  <ol>
  <div/>
  <div/>
  <li class="g w0">
   <h3 class="r">
    <a class="l" onmousedown="return rwt(this,'','','res','1','AFQjCNFp1UrvQWdtIVY_6kO-
kEDVmdSnig','&sig2=HRDAzRP8Pz96kL3VNCyX1A')" href="http://www.testinggeek.com/in
dex.php/testing-tools/test-execution/97-selenium-ide-introduction">
    <em>Selenium IDE</em>
- Introduction
    </a>
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

   </h3>

     • As you see above the anchor tag does not have anything that can identify the element
       uniquely, hence we take the Xpath here.
     • For that we need to see which tag of the upper hierarchy of the element has a unique
       attribute to identify it uniquely. We deduct the Xpath as



//div[@id='res']/div[1]/ol/li[1]/h3/a

The Xpath should always start from a hierarchy from where the element can be identified
uniquely.

For example there is an element which has the attributes as follows

<input class=”username” type=””> and say the class attribute is unique to this tag then the
element locator would be //input[@class=”username”].This is also Xpath but it is at the same
level.


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 two links 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 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 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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------


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



Locating by CSS¶
     • CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and
       XML documents.
     • CSS uses Selectors for binding style properties to elements in the document.

 1   <html>
 2   <body>
 3    <form id="loginForm">
 4     <input class="required" name="username" type="text" />
 5     <input class="required passfield" 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>
     •    css=form#loginForm (3)
     •    css=input[name="username"] (4)
     •    css=input.required[type="text"] (4)
     •    css=input.passfield (5)
     •    css=#loginForm input[type="button"] (4)
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

     •    css=#loginForm input:nth-child(2) (5)




11. Basic Examples:
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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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 xxx@yyyy.com)
  • 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”
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------




12. Test Suite Creation:
     • 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
       file system path to each test.

Steps for creating test suite:
   • Create more Tc’s save each Test Case with <.html> extension.
   • Open Firefox
   • Open Tools Selenium IDE
   • File Open new Test Suite
   • File Open Add Test cases
   • Add more test cases
   • Save Suite with <.Html> extensions.

Test Suite Syntax:
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------


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


13. Useful Selenium Add-Ons:
     •    Chris Pederick's Web Developer toolbar
     •    XPather
     •    Firebug
     •    Xpath Checker
     •    Regular Expressions Tester
     •    JavaScript Debugger
     •    Web Developer
     •    HTML Validator
     •    ColorZilla
     •    DOM Inspector


14. About User Extensions
     • User extensions are JavaScript files that allow one to create our own customizations and
       features to add additional functionality.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

   • 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:
        •     Download goto_sel_ide.js file.
        •     Save into selenium core extensions folder
        •     Selenium-IDE’s Options=>Options=>General tab
        •     Browse extension file




        • Click on OK Button

        •     Restart selenium and fire fox




15. Selenium Commands for verification:

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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------




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.




storeElementPresent
This corresponds to verifyElementPresent. It simply stores a boolean value–“true” or “false”–
depending on whether the UI element is found.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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.


JavaScript and Selenese Parameters
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’].



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.




JavaScript Usage with Non-Script Parameters
JavaScript can also be used to help generate values for parameters, even when the parameter is
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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:




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


echo - The Selenese Print Command
Selenese 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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

     •    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 )
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------




To Handle Alerts:

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:
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------




goBack:
   • goBack and goBackAndWait are the two commands simulates a user clicking on the
          “back” button of the browser.
waitForPopup
   • 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:
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------




16. Selenium IDE Commands for handling alerts

     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()].
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------


     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
        Returns 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 otherwise
          Verifies that the specified element is somewhere on the page.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

Similarly some other commands: assertElementNotPresent
assertEval(script, pattern)
Generated from getEval(script)
       Arguments:
                •    script - the JavaScript snippet to run
          Returns:
          the results of evaluating the snippet
          Gets 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 source
       Returns the entire HTML source between the opening and closing "html" tags.
assertLocation(pattern)
Generated from getLocation()
       Returns:
       the absolute URL of the current page
       Gets 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 xpath
       Returns 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 element
       Gets 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)
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

          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.

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:
                  background
          the 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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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
          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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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.
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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------


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.
          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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

      Returns:
      the number of nodes that match the specified xpath
      Returns the number of nodes that match the specified xpath, eg. "//table" would give the
      number of tables.
submit(formLocator)
      Arguments:
                •    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 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:
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

                •    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()
Generated from isConfirmationPresent()
      Returns:
      true if there is a pending confirmation
      Has confirm() been called?
Similarly: waitForCondition
waitForTitle(pattern)
Generated from getTitle()
      Returns:
      the title of the current page
      Gets the title of the current page.
Similary: waitForTable etc……

17. Java Script

What is the use of java script?
     1. Java script can be used by for printing some dynamic html contents
     2. For validating the forms in the web page
     3. 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:-
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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

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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

                     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.”);
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: (=,+=,-=,*=,/=,%=)
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

          Arthemetic operators: (+,-,*,/,%)
          Relational operators: (<,>,<=,>=)
          Comparision operators: (==,===,!=,!==)
          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
  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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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,
     2.   IF –else
     3.   IF-else IF ladder
     4.   Nested if and
     5.   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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

}
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)
         {
         d.w(“A is greater<br>”);
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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

Arrays:-
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

          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];//sree
users[1];//siva

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

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

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



Loops:-
          While

          While(condition)
          {
           Code
          }

Ex:1
           i=1;
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

          while(i<=3)
          {
          d.w(i);
          i++;
          }
Ex:-2
Mon=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=0
       Do
       {
       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:-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)
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

{
Array-name[index]
}
Ex:-
       x=new Array(11,31,94);
       For(i in x)
       {
       d.w(i+’=’+x[i]+’<br>’);
       }

Functions:-
TYPE                                           Arg                                            Return
I                                              *                                              *
II                                             yes                                            *
III                                            *                                              yes
IV                                             yes                                            yes



Two types of functions

     1. User defined functions
     2. 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 1
                 Function welcome()
                 {
                 document.write(“welcome to the site%”);
                 }
                 Welcome();
                 X=welcome();//user define
                 Document write(‘x=’+x+’,<br>’);

For Type 2 category:-
Function bold(text)
{
document.write(‘<b>’+text+”<br>”);
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

ex:- for type 2
function 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 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);
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

{
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
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:-
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------


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”));
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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

          [] 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)
{
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)
{
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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




18. Example programs:
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:
GE Test Case2
open                            http://www.ge.com/
assertTitle                     GE : imagination at work
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

GE Test Case2
clickAndWait                    //div[@id='ge_footer']/ul/li[2]/a
                                GE Contact Information: Web Questions, Online Help,
assertTitle
                                Press Contacts
clickAndWait                    link=Feedback and Inquiries
assertTitle                     Feedback & Inquiries : Contact Information : GE
pause                           3000
select                          contact_subject                                                                  label=Other
                                                                                                                 label=United
select                          contact_country
                                                                                                                 States
type                            contact_email                                                                    testing@test.com
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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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
                 //div[@id='bs-center-
storeText                                                                                                                    T1
                 col']/div[3]/div[1]/div[2]/div/div/div/ul[1]/li[2]/strong
echo             ${T1}
                 xpath=id('bs-center-
storeText                                                                                                                    T2
                 col')/div[3]/div[3]/div[2]/div/div/div/ul[1]/li[1]/strong
echo             ${T2}
                 //div[@id='bs-center-
storeText                                                                                                                    T3
                 col']/div[3]/div[5]/div[2]/div/div/div/ul[1]/li[1]/strong
echo             ${T3}
                 var A= new Number("${T1}".substr(1));var B=new
storeEval        Number("${T2}".substr(1)); var Result1=false; if (A<=B)                                                     T4
                 Result1=true;Result1
echo             ${T4}
                 var B= new Number("${T2}".substr(1));var C=new
storeEval        Number("${T3}".substr(1)); var Result2=false; if (B<=C)                                                     T5
                 Result2=true;Result2
echo             ${T5}
storeEval        var Result1= new Boolean("${T4}");Result1                                                                   R1
echo             ${R1}
storeEval        var Result2= new Boolean("${T5}");Result2                                                                   R2
echo             ${R2}
                 var Result1= new Boolean("${T4}");var Result2=new
storeEval                                                                                                                    T6
                 Boolean("${T5}"); Result1 && Result2
store            true                                                                                                        T7
echo             ${T6}
verifyExpression ${T6}                                                                                                       ${T7}
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

Reviewed Test Case Barnes and Noble Sorted Order
echo            ${T7}
                var isSorted = new Boolean("${T6}"); var strResult ='Not in Sorted
storeEval                                                                          vSorted
                Order'; if (isSorted) strResult='Ascending Order'; strResult
echo            ${vSorted}


Tc# 7: Example For Alert Massege
Test Case Alert Button Click

open                  file:C:2009 SeleniumDay 3ExClickAlert.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 SeleniumDay 3ExSelectAWebSite.html
select          OptWeb                                                                                              label=Google
clickAndWait btnGo
assertTitle     Google
goBackAndWait
select          OptWeb                                                                                              label=Portnov
clickAndWait btnGo
                Career Training & Career Change: Software Testing and
assertTitle     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!
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------



Tc#9: Example for Alert conformation

Reviewed Test Case Popup

open                             file:C:2009 SeleniumDay 3ExCreatePopUps.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
                    regex:Ex1.html
assertAlert
                    win1
                    regex:Ex2.html
assertAlert
                    win2
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

Reviewed Test Case Window Name Check
                    regex:Ex3.html
assertAlert
                    win3
Tc#11: Regular Expression
Reviewed Test Case RegEx Email Check
open        file:///C:/2009%20Selenium/Day%204/Ex/UserInputForm.html
type        txtName                                                                                          kangs p
type        txtEmail                                                                                         KANGS@YAHOO.COM
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+sw+
                                                                                                             regex:^[a-z0-9_-]+(.[_a-z0-9-]+)*
assertEval javascript:jStr=storedVars['selEmail']; jStr.toLowerCase()
                                                                                                             z]{2}|aero|arpa|biz|com|coop|edu|go




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
            file:///C:/2009%20Selenium/Day%204/Ex/Narrating Test
open
            Cases.html
type        txtName                                              kangs p
type        txtEmail                                             KANGS@YAHOO.COM
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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+sw+
     •    Email is first converted into lower case then tested using regex.
assertEval storedVars['selName']                   regex:w+sw+
           javascript:jStr=storedVars['selEmail']; regex:^[a-z0-9_-]+(.[_a-z0-9-]+)*@([_a-z0-9-]+.)+([a-
assertEval
           jStr.toLowerCase()                      z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|
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
Tc#11:
Test Case DevryPopupWindows Close
              http://www.devry-
open          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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

Test Case DevryPopupWindows Close
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
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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

Test Case for PageLoadTime_Simple
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

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
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------


Test Case for PageLoadTime

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

Test Case for PageLoadTime_MilliSeconds
storeEval var d=(new Date().getTime()); d;                                                                         timeBeforeLoad
echo      ${timeBeforeLoad}
          open("http://www.ge.com/");var
storeEval win=this.browserbot.getCurrentWindow();                                                                  timeAfterLoad
          if(win)win.onload=(window.status=(new Date().getTime()));
echo      ${timeAfterLoad}
storeEval ${timeAfterLoad}-${timeBeforeLoad}                                                                       loadTimeMSecs
echo      ${loadTimeMSecs}


Tc#15: Get Xpathcount, rows count and Tablecount
XXX
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#
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

Test Case Xpath
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}



19. Selenium Core
Introduction:
    • 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.
QAPlanet                                                 SELENIUM Handbook - -a basic referential guide to Selenium
------------------------------------------------------------------------------------------------------------------------------------------

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

     •     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 FilesApache Software FoundationApache2.2htdocs
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook
Selenium Handbook

Contenu connexe

Tendances

Web application testing with Selenium
Web application testing with SeleniumWeb application testing with Selenium
Web application testing with SeleniumKerry Buckley
 
Selenium Presentation at Engineering Colleges
Selenium Presentation at Engineering CollegesSelenium Presentation at Engineering Colleges
Selenium Presentation at Engineering CollegesVijay Rangaiah
 
Automated Web Testing Using Selenium
Automated Web Testing Using SeleniumAutomated Web Testing Using Selenium
Automated Web Testing Using SeleniumWeifeng Zhang
 
Selenium Interview Questions and Answers For Freshers And Experienced | Edureka
Selenium Interview Questions and Answers For Freshers And Experienced | EdurekaSelenium Interview Questions and Answers For Freshers And Experienced | Edureka
Selenium Interview Questions and Answers For Freshers And Experienced | EdurekaEdureka!
 
Test Automation and Selenium
Test Automation and SeleniumTest Automation and Selenium
Test Automation and SeleniumKarapet Sarkisyan
 
Test automation
Test automationTest automation
Test automationXavier Yin
 
Selenium introduction
Selenium introductionSelenium introduction
Selenium introductionPankaj Dubey
 
Test Automation Framework Designs
Test Automation Framework DesignsTest Automation Framework Designs
Test Automation Framework DesignsSauce Labs
 
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...Simplilearn
 
Selenium test automation
Selenium test automationSelenium test automation
Selenium test automationSrikanth Vuriti
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriverAnuraj S.L
 
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Edureka!
 

Tendances (20)

SELENIUM PPT.pdf
SELENIUM PPT.pdfSELENIUM PPT.pdf
SELENIUM PPT.pdf
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
 
Test automation process
Test automation processTest automation process
Test automation process
 
Web application testing with Selenium
Web application testing with SeleniumWeb application testing with Selenium
Web application testing with Selenium
 
Selenium Presentation at Engineering Colleges
Selenium Presentation at Engineering CollegesSelenium Presentation at Engineering Colleges
Selenium Presentation at Engineering Colleges
 
Automated Web Testing Using Selenium
Automated Web Testing Using SeleniumAutomated Web Testing Using Selenium
Automated Web Testing Using Selenium
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
 
Selenium Interview Questions and Answers For Freshers And Experienced | Edureka
Selenium Interview Questions and Answers For Freshers And Experienced | EdurekaSelenium Interview Questions and Answers For Freshers And Experienced | Edureka
Selenium Interview Questions and Answers For Freshers And Experienced | Edureka
 
Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Test Automation and Selenium
Test Automation and SeleniumTest Automation and Selenium
Test Automation and Selenium
 
Test automation
Test automationTest automation
Test automation
 
Selenium introduction
Selenium introductionSelenium introduction
Selenium introduction
 
Test Automation Framework Designs
Test Automation Framework DesignsTest Automation Framework Designs
Test Automation Framework Designs
 
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
 
Selenium test automation
Selenium test automationSelenium test automation
Selenium test automation
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
 
Serenity-BDD training
Serenity-BDD trainingSerenity-BDD training
Serenity-BDD training
 
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
 
Selenium
SeleniumSelenium
Selenium
 
Selenium Concepts
Selenium ConceptsSelenium Concepts
Selenium Concepts
 

En vedette

Manual Testing Material by Durgasoft
Manual Testing Material by DurgasoftManual Testing Material by Durgasoft
Manual Testing Material by DurgasoftDurga Prasad
 
Software testing Training Syllabus Course
Software testing Training Syllabus CourseSoftware testing Training Syllabus Course
Software testing Training Syllabus CourseTOPS Technologies
 
Automation testing material by Durgasoft,hyderabad
Automation testing material by Durgasoft,hyderabadAutomation testing material by Durgasoft,hyderabad
Automation testing material by Durgasoft,hyderabadDurga Prasad
 
Manual Testing Notes
Manual Testing NotesManual Testing Notes
Manual Testing Notesguest208aa1
 
Complete guide to manual testing@uma
Complete guide to manual  testing@umaComplete guide to manual  testing@uma
Complete guide to manual testing@umaUma Sapireddy
 
Manual Testing
Manual TestingManual Testing
Manual TestingG.C Reddy
 
Manual testing interview question by INFOTECH
Manual testing interview question by INFOTECHManual testing interview question by INFOTECH
Manual testing interview question by INFOTECHPravinsinh
 
Selenium by using JAVA
Selenium by using JAVASelenium by using JAVA
Selenium by using JAVAmahirayavarapu
 
Qtp training in hyderabad
Qtp training in hyderabadQtp training in hyderabad
Qtp training in hyderabadG.C Reddy
 
Qtp commands
Qtp commandsQtp commands
Qtp commandsG.C Reddy
 
QTP 10 00 Guide
QTP 10 00 GuideQTP 10 00 Guide
QTP 10 00 GuideG.C Reddy
 
A Buffer's Guide to Selenium 2
A Buffer's Guide to Selenium 2A Buffer's Guide to Selenium 2
A Buffer's Guide to Selenium 2onlinemindq
 
Automated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationAutomated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationBarbara Jones
 
Selenium testing
Selenium testingSelenium testing
Selenium testingJason Myers
 

En vedette (20)

Manual Testing Material by Durgasoft
Manual Testing Material by DurgasoftManual Testing Material by Durgasoft
Manual Testing Material by Durgasoft
 
Software testing Training Syllabus Course
Software testing Training Syllabus CourseSoftware testing Training Syllabus Course
Software testing Training Syllabus Course
 
Automation testing material by Durgasoft,hyderabad
Automation testing material by Durgasoft,hyderabadAutomation testing material by Durgasoft,hyderabad
Automation testing material by Durgasoft,hyderabad
 
Manual Testing Notes
Manual Testing NotesManual Testing Notes
Manual Testing Notes
 
Complete guide to manual testing@uma
Complete guide to manual  testing@umaComplete guide to manual  testing@uma
Complete guide to manual testing@uma
 
Manual Testing
Manual TestingManual Testing
Manual Testing
 
Manual testing interview question by INFOTECH
Manual testing interview question by INFOTECHManual testing interview question by INFOTECH
Manual testing interview question by INFOTECH
 
Selenium by using JAVA
Selenium by using JAVASelenium by using JAVA
Selenium by using JAVA
 
Qtp training in hyderabad
Qtp training in hyderabadQtp training in hyderabad
Qtp training in hyderabad
 
Qtp commands
Qtp commandsQtp commands
Qtp commands
 
QTP 10 00 Guide
QTP 10 00 GuideQTP 10 00 Guide
QTP 10 00 Guide
 
Qtp test
Qtp testQtp test
Qtp test
 
A Buffer's Guide to Selenium 2
A Buffer's Guide to Selenium 2A Buffer's Guide to Selenium 2
A Buffer's Guide to Selenium 2
 
Functions
FunctionsFunctions
Functions
 
Selenium
SeleniumSelenium
Selenium
 
Python in Test automation
Python in Test automationPython in Test automation
Python in Test automation
 
Automated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationAutomated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and Validation
 
Embedded System Test Automation
Embedded System Test AutomationEmbedded System Test Automation
Embedded System Test Automation
 
Selenium testing
Selenium testingSelenium testing
Selenium testing
 
Basic Selenium Training
Basic Selenium TrainingBasic Selenium Training
Basic Selenium Training
 

Similaire à Selenium Handbook

Selenium institute in bangalore
Selenium institute in bangaloreSelenium institute in bangalore
Selenium institute in bangaloreTIB Academy
 
Selenium Installation
Selenium InstallationSelenium Installation
Selenium InstallationSachin-QA
 
Selenium Installation
Selenium  InstallationSelenium  Installation
Selenium InstallationANKUR-BA
 
Selenium - Installation
Selenium - InstallationSelenium - Installation
Selenium - InstallationRajesh-QA
 
Selenium Tutorial
Selenium TutorialSelenium Tutorial
Selenium Tutorialprad_123
 
Smarter ways to do selenium automation @ work, Selenium, automation
Smarter ways to do selenium automation @ work, Selenium, automationSmarter ways to do selenium automation @ work, Selenium, automation
Smarter ways to do selenium automation @ work, Selenium, automationRIA RUI Society
 
Python selenium
Python seleniumPython selenium
Python seleniumDucat
 
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...Simplilearn
 
Basics of Selenium IDE,Core, Remote Control
Basics of Selenium IDE,Core, Remote ControlBasics of Selenium IDE,Core, Remote Control
Basics of Selenium IDE,Core, Remote Controlusha kannappan
 

Similaire à Selenium Handbook (20)

Selenium (1)
Selenium (1)Selenium (1)
Selenium (1)
 
Selenium
SeleniumSelenium
Selenium
 
Selenium Introduction
Selenium IntroductionSelenium Introduction
Selenium Introduction
 
Sel
SelSel
Sel
 
Selenium Primer
Selenium PrimerSelenium Primer
Selenium Primer
 
Selenium
SeleniumSelenium
Selenium
 
Selenium institute in bangalore
Selenium institute in bangaloreSelenium institute in bangalore
Selenium institute in bangalore
 
Selenium Installation
Selenium InstallationSelenium Installation
Selenium Installation
 
Selenium Installation
Selenium  InstallationSelenium  Installation
Selenium Installation
 
Selenium - Installation
Selenium - InstallationSelenium - Installation
Selenium - Installation
 
Selenium Tutorial
Selenium TutorialSelenium Tutorial
Selenium Tutorial
 
Selenium Testing
Selenium Testing Selenium Testing
Selenium Testing
 
Selenium Testing
Selenium TestingSelenium Testing
Selenium Testing
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
 
Selenium
SeleniumSelenium
Selenium
 
Smarter ways to do selenium automation @ work, Selenium, automation
Smarter ways to do selenium automation @ work, Selenium, automationSmarter ways to do selenium automation @ work, Selenium, automation
Smarter ways to do selenium automation @ work, Selenium, automation
 
Selenium
SeleniumSelenium
Selenium
 
Python selenium
Python seleniumPython selenium
Python selenium
 
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
 
Basics of Selenium IDE,Core, Remote Control
Basics of Selenium IDE,Core, Remote ControlBasics of Selenium IDE,Core, Remote Control
Basics of Selenium IDE,Core, Remote Control
 

Dernier

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

Selenium Handbook

  • 1. SELENIUM Handbook -a basic referential guide to Selenium By Sreedhar Reddy (Test Architect) QA Planet,# 24/3 RT,3rd Floor,SR Nagar,Hyderabad - 500018. Email :Contact@qaplanet.in || Phone :040-40044448 || Mobile :+91 9966723111
  • 2. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 1. Introduction: 2. History of Selenium 3. What is Selenium? 4. Selenium Types: 5. Selenium IDE Installation Steps: 6. IDE Features 7. Recording 8. Selenium Commands – “Selenese” 9. Commonly Used Selenium Commands 10. Locating Elements: 11. Basic Examples: 12. Test Suite Creation: 13. Useful Selenium Add-Ons: 14. about User Extensions 15. Selenium Commands for verification 16. Selenium IDE Commands for handling alerts 17. Java Script 18. Example programs: 19. Selenium Core 20. Selenium-RC 21. Selenium Grid: 22. Advantages and Limitations:
  • 3. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 1. Introduction: Out of the many open source test automation tools available today, there is one tool that become very popular in recent times Selenium. Selenium is a web application test automation tool which provides many features and a wide range of support which makes it an instant choice for automating most of the web applications. Selenium provides the automation engineer the choice of running the automation scripts in a wide range of browsers and with the language support it has, on wide range of operating systems too. But there are certain things the automation engineer needs to be aware of before he jumps into understanding selenium. The automation engineer needs to have a basic knowledge of the following things: 1. HTML 2. XML 3. Xpaths 4. Document Object Model(DOM) 5. JavaScript (only a basic knowledge on how events are triggered etc.) 6. Any one of the following language to build a full-fledged test suite – Perl, Python, Ruby, Java, C#, PHP. 7. Basic object oriented programming concepts. Once we are sure that we have the basics of the above mentioned seven points let us move on into what selenium is all about and various types of selenium. 2. 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+
  • 4. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 3. 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 - o JavaScript o DHTML o Frames 4. Selenium Types: There are 4 types in Selenium, each for a specific purpose. They are as follows: 1. Selenium IDE 2. Selenium Remote Control 3. Selenium Core 4. Selenium Grid The more detail information about these will be given in later in the document. But let us have a brief introduction about each of these to make ourselves comfortable. Selenium IDE is a Firefox plugin which is a record replay tool of Selenium. User can record the actions performed on the browser and replay it. User also has an option to write his own scripts, save the scripts and develop test suites using Selenium IDE. Selenium Remote Control on the other hand is used when more robust scripts are to be developed. Using any of the languages listed previously user can build test suites which are robust and can run on different platforms, unlike IDE which can run scripts only on Firefox. Selenium Core usage is similar to Selenium RC except that the scripts which use selenium core can only be run on the server where the web application is deployed. Selenium Grid as the name suggests, is used to organize several Selenium RC's and run the scripts on different machines from a central location where Selenium Grid is available. Now let us get some hands on on Selenium IDE to understand Selenium better.
  • 5. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Working with Selenium IDE: Above is a snapshot of how Selenium IDE looks. 5. Selenium IDE Installation Steps: • To install Selenium IDE just goto http://seleniumhq.org/projects/ide/ click on download Selenium. • It will be added to your Firefox add-on list.
  • 6. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ • Restart Firefox and you should be able to open it from Tools --> Selenium IDE. 6. IDE Features¶ Menu Bar The File menu has options for Test Case and Test Suite (suite of Test Cases). Using these you can add a new Test Case, open a Test Case, save a Test Case, export Test Case in a language of your choice. You can also open the recent Test Case. All these options are also available for Test Suite. The Edit menu allows copy, paste, delete, undo, and select all operations for editing the commands in your test case. 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. The Help menu is the standard Firefox Help menu; only one item on this menu–UI-Element Documentation–pertains to Selenium-IDE. Toolbar¶ The toolbar contains buttons for controlling the execution of your test cases, including a step feature for debugging your test cases. The right-most button, the one with the red-dot, is the record button. Speed Control: controls how fast your test case runs. Run All: Runs the entire test suite when a test suite with multiple test cases is loaded. Run: Runs the currently selected test. When only a single test is loaded this button and the Run All button have the same effect. Pause/Resume: Allows stopping and re-starting of a running test case. Step: Allows you to “step” through a test case by running it one command at a time. Use for debugging test cases. TestRunner Mode: Allows you to run the test case in a browser loaded with the Selenium-Core TestRunner. The TestRunner is not commonly used now and is likely to be deprecated. This button is for evaluating test cases for backwards compatibility with
  • 7. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ the TestRunner. Most users will probably not need this button. Apply Rollup Rules: This advanced feature allows repetitive sequences of Selenium commands to be grouped into a single action. Detailed documentation on rollup rules can be found in the UI-Element Documentation on the Help menu. Record: Records the user’s browser actions. Test Case Pane Your script is displayed in the test case pane. It has two tabs, one for displaying the command and their parameters in a readable “table” format. 7. Recording Many first-time users begin by recording a test case from their interactions with a website. When Selenium-IDE is first opened, the record button is ON by default. If you do not want Selenium-IDE to begin recording automatically you can turn this off by going under Options > Options... and deselecting “Start recording immediately on open.” During recording, Selenium-IDE will automatically insert commands into your test case based on your actions. Typically, this will include: • clicking a link - click or clickAndWait commands • entering values - type command • selecting options from a drop-down listbox - select command • clicking checkboxes or radio buttons - click command 8. Selenium Commands – “Selenese” • Selenium commands, often called selenese, are the set of commands that run your tests. • Selenium command are three types as below o Actions, o Accessory
  • 8. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ o Assertions • Actions: user actions on application / Command the browser to do something. Actions are commands that generally manipulate the state of the application. 1. Click / Clickandwait 2. Selecting items a. Assessors: Accessors examine the state of the application and store the results in variables, e.g. "storeTitle". b. Assertions: For validating the application we are using Assertions 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 9. 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.
  • 9. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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. Note: To execute many Selenium commands, Selenium required a target often called it as Element Locators (or calls it as object identification). To get Target element Please install below plug – INS 1. For Firefox browser – Firebug 2. For IE browser – IE Developer Tool bar. How Selenium is Identifying the Objects?: 10. Locating Elements: Selenium is identifying the objects by using following Locator strategies. 1. Id = @Id 2. Name = @name 3. Identifier = @id 4. Dom = JavaScript expression 5. Xpath = Xpath expression 6. Link =Text pattern 7. css = css Selector Index Locating by ID: For instance, 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" /> 7 </form> 8 </body> 9 <html> The following locator strategies would return the elements from the HTML snippet above indicated by line number: • id=loginForm (3)
  • 10. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Locating by Name¶ • 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> 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) Locating by XPath¶ • XPath is the language used for locating nodes in an XML document. • We are using XPath is when you don’t have a suitable id or name attribute for the element you wish to locate. 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>
  • 11. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 10 <html> • xpath=/html/body/form[1] (3) - Absolute path (would break if the HTML was changed only slightly) • //form[1] (3) - First form element in the HTML • xpath=//form[@id='loginForm'] (3) - The form element with attribute named ‘id’ and the value ‘loginForm’ • xpath=//form[input/@name='username'] (4) - First form element with an input child element with attribute named ‘name’ and the value ‘username’ • //input[@name='username'] (4) - First input element with attribute named ‘name’ and the value ‘username’ • //form[@id='loginForm']/input[1] (4) - First input child element of the form element with attribute named ‘id’ and the value ‘loginForm’ • //input[@name='continue'][@type='button'] (7) - Input with attribute named ‘name’ and the value ‘continue’ and attribute named ‘type’ and the value ‘button’ • //form[@id='loginForm']/input[4] (7) - Fourth input child element of the form element with attribute named ‘id’ and value ‘loginForm’ Example for Xpath: • Let us take the source of google.com to make our task simpler. • The first three locator strategies state that, if any element having the name, id or identifier attribute • Observe the source code of below. After we click on the Google Search button we move to the results page, now let us understand how the first link is identified from the below source code. <div id="res" class="med"> <h2 class="hd">Search Results</h2> <div> <ol> <div/> <div/> <li class="g w0"> <h3 class="r"> <a class="l" onmousedown="return rwt(this,'','','res','1','AFQjCNFp1UrvQWdtIVY_6kO- kEDVmdSnig','&sig2=HRDAzRP8Pz96kL3VNCyX1A')" href="http://www.testinggeek.com/in dex.php/testing-tools/test-execution/97-selenium-ide-introduction"> <em>Selenium IDE</em> - Introduction </a>
  • 12. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ </h3> • As you see above the anchor tag does not have anything that can identify the element uniquely, hence we take the Xpath here. • For that we need to see which tag of the upper hierarchy of the element has a unique attribute to identify it uniquely. We deduct the Xpath as //div[@id='res']/div[1]/ol/li[1]/h3/a The Xpath should always start from a hierarchy from where the element can be identified uniquely. For example there is an element which has the attributes as follows <input class=”username” type=””> and say the class attribute is unique to this tag then the element locator would be //input[@class=”username”].This is also Xpath but it is at the same level. 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 two links 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 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 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.
  • 13. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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) • 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) Locating by CSS¶ • CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents. • CSS uses Selectors for binding style properties to elements in the document. 1 <html> 2 <body> 3 <form id="loginForm"> 4 <input class="required" name="username" type="text" /> 5 <input class="required passfield" 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> • css=form#loginForm (3) • css=input[name="username"] (4) • css=input.required[type="text"] (4) • css=input.passfield (5) • css=#loginForm input[type="button"] (4)
  • 14. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ • css=#loginForm input:nth-child(2) (5) 11. Basic Examples: 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.
  • 15. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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 xxx@yyyy.com) • 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”
  • 16. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 12. Test Suite Creation: • 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 file system path to each test. Steps for creating test suite: • Create more Tc’s save each Test Case with <.html> extension. • Open Firefox • Open Tools Selenium IDE • File Open new Test Suite • File Open Add Test cases • Add more test cases • Save Suite with <.Html> extensions. Test Suite Syntax:
  • 17. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ <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. 13. Useful Selenium Add-Ons: • Chris Pederick's Web Developer toolbar • XPather • Firebug • Xpath Checker • Regular Expressions Tester • JavaScript Debugger • Web Developer • HTML Validator • ColorZilla • DOM Inspector 14. About User Extensions • User extensions are JavaScript files that allow one to create our own customizations and features to add additional functionality.
  • 18. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ • 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: • Download goto_sel_ide.js file. • Save into selenium core extensions folder • Selenium-IDE’s Options=>Options=>General tab • Browse extension file • Click on OK Button • Restart selenium and fire fox 15. Selenium Commands for verification: 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.
  • 19. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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. storeElementPresent This corresponds to verifyElementPresent. It simply stores a boolean value–“true” or “false”– depending on whether the UI element is found.
  • 20. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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. JavaScript and Selenese Parameters 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’]. 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. JavaScript Usage with Non-Script Parameters JavaScript can also be used to help generate values for parameters, even when the parameter is
  • 21. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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: 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 echo - The Selenese Print Command Selenese 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
  • 22. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ • 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 )
  • 23. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ To Handle Alerts: 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:
  • 24. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ goBack: • goBack and goBackAndWait are the two commands simulates a user clicking on the “back” button of the browser. waitForPopup • 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:
  • 25. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 16. Selenium IDE Commands for handling alerts 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()].
  • 26. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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 Returns 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 otherwise Verifies that the specified element is somewhere on the page.
  • 27. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Similarly some other commands: assertElementNotPresent assertEval(script, pattern) Generated from getEval(script) Arguments: • script - the JavaScript snippet to run Returns: the results of evaluating the snippet Gets 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 source Returns the entire HTML source between the opening and closing "html" tags. assertLocation(pattern) Generated from getLocation() Returns: the absolute URL of the current page Gets 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 xpath Returns 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 element Gets 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)
  • 28. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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. 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: background the 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.
  • 29. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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 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.
  • 30. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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. 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
  • 31. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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. 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.
  • 32. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Returns: the number of nodes that match the specified xpath Returns the number of nodes that match the specified xpath, eg. "//table" would give the number of tables. submit(formLocator) Arguments: • 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 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:
  • 33. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ • 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() Generated from isConfirmationPresent() Returns: true if there is a pending confirmation Has confirm() been called? Similarly: waitForCondition waitForTitle(pattern) Generated from getTitle() Returns: the title of the current page Gets the title of the current page. Similary: waitForTable etc…… 17. Java Script What is the use of java script? 1. Java script can be used by for printing some dynamic html contents 2. For validating the forms in the web page 3. 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:-
  • 34. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ <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 */ 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
  • 35. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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.”); 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: (=,+=,-=,*=,/=,%=)
  • 36. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Arthemetic operators: (+,-,*,/,%) Relational operators: (<,>,<=,>=) Comparision operators: (==,===,!=,!==) 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 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
  • 37. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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, 2. IF –else 3. IF-else IF ladder 4. Nested if and 5. 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
  • 38. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ } 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) { d.w(“A is greater<br>”);
  • 39. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ } 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; } Arrays:-
  • 40. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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];//sree users[1];//siva we can replace value of array users[1]=”ram”; we can add one more field to the array users[3]=”rama”; To get array count users[users.length]=’mary’; [Appending]. Ex:- Tags=new Array(‘barbie’,’Teddy’,’mickey’,’donald’); d.w(‘toys.length=’+toys.length+’<br>);//4 d.w[‘toys[2]=’’+toys [2]+’<br>’);//mickey d.w[‘toys=’+toys+’<br>’);//B,T,M,D. toys[3]+=’Duck’; d.w(‘toys=’+toys+’<br>’);// B,T,M,D,D toys[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>’); Loops:- While While(condition) { Code } Ex:1 i=1;
  • 41. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ while(i<=3) { d.w(i); i++; } Ex:-2 Mon=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=0 Do { 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:-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)
  • 42. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ { Array-name[index] } Ex:- x=new Array(11,31,94); For(i in x) { d.w(i+’=’+x[i]+’<br>’); } Functions:- TYPE Arg Return I * * II yes * III * yes IV yes yes Two types of functions 1. User defined functions 2. 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 1 Function welcome() { document.write(“welcome to the site%”); } Welcome(); X=welcome();//user define Document write(‘x=’+x+’,<br>’); For Type 2 category:- Function bold(text) { document.write(‘<b>’+text+”<br>”);
  • 43. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ ex:- for type 2 function 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 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);
  • 44. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ { 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 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:-
  • 45. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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”)); 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
  • 46. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ [] 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) { 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) {
  • 47. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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’); 18. Example programs: 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: GE Test Case2 open http://www.ge.com/ assertTitle GE : imagination at work
  • 48. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ GE Test Case2 clickAndWait //div[@id='ge_footer']/ul/li[2]/a GE Contact Information: Web Questions, Online Help, assertTitle Press Contacts clickAndWait link=Feedback and Inquiries assertTitle Feedback & Inquiries : Contact Information : GE pause 3000 select contact_subject label=Other label=United select contact_country States type contact_email testing@test.com 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
  • 49. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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.
  • 50. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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 //div[@id='bs-center- storeText T1 col']/div[3]/div[1]/div[2]/div/div/div/ul[1]/li[2]/strong echo ${T1} xpath=id('bs-center- storeText T2 col')/div[3]/div[3]/div[2]/div/div/div/ul[1]/li[1]/strong echo ${T2} //div[@id='bs-center- storeText T3 col']/div[3]/div[5]/div[2]/div/div/div/ul[1]/li[1]/strong echo ${T3} var A= new Number("${T1}".substr(1));var B=new storeEval Number("${T2}".substr(1)); var Result1=false; if (A<=B) T4 Result1=true;Result1 echo ${T4} var B= new Number("${T2}".substr(1));var C=new storeEval Number("${T3}".substr(1)); var Result2=false; if (B<=C) T5 Result2=true;Result2 echo ${T5} storeEval var Result1= new Boolean("${T4}");Result1 R1 echo ${R1} storeEval var Result2= new Boolean("${T5}");Result2 R2 echo ${R2} var Result1= new Boolean("${T4}");var Result2=new storeEval T6 Boolean("${T5}"); Result1 && Result2 store true T7 echo ${T6} verifyExpression ${T6} ${T7}
  • 51. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Reviewed Test Case Barnes and Noble Sorted Order echo ${T7} var isSorted = new Boolean("${T6}"); var strResult ='Not in Sorted storeEval vSorted Order'; if (isSorted) strResult='Ascending Order'; strResult echo ${vSorted} Tc# 7: Example For Alert Massege Test Case Alert Button Click open file:C:2009 SeleniumDay 3ExClickAlert.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 SeleniumDay 3ExSelectAWebSite.html select OptWeb label=Google clickAndWait btnGo assertTitle Google goBackAndWait select OptWeb label=Portnov clickAndWait btnGo Career Training & Career Change: Software Testing and assertTitle 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!
  • 52. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Tc#9: Example for Alert conformation Reviewed Test Case Popup open file:C:2009 SeleniumDay 3ExCreatePopUps.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 regex:Ex1.html assertAlert win1 regex:Ex2.html assertAlert win2
  • 53. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Reviewed Test Case Window Name Check regex:Ex3.html assertAlert win3 Tc#11: Regular Expression Reviewed Test Case RegEx Email Check open file:///C:/2009%20Selenium/Day%204/Ex/UserInputForm.html type txtName kangs p type txtEmail KANGS@YAHOO.COM 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+sw+ regex:^[a-z0-9_-]+(.[_a-z0-9-]+)* assertEval javascript:jStr=storedVars['selEmail']; jStr.toLowerCase() z]{2}|aero|arpa|biz|com|coop|edu|go 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 file:///C:/2009%20Selenium/Day%204/Ex/Narrating Test open Cases.html type txtName kangs p type txtEmail KANGS@YAHOO.COM
  • 54. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ 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+sw+ • Email is first converted into lower case then tested using regex. assertEval storedVars['selName'] regex:w+sw+ javascript:jStr=storedVars['selEmail']; regex:^[a-z0-9_-]+(.[_a-z0-9-]+)*@([_a-z0-9-]+.)+([a- assertEval jStr.toLowerCase() z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum| 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 Tc#11: Test Case DevryPopupWindows Close http://www.devry- open 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
  • 55. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Test Case DevryPopupWindows Close 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 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
  • 56. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Test Case for PageLoadTime_Simple 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 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
  • 57. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Test Case for PageLoadTime 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 mille Seconds Test Case for PageLoadTime_MilliSeconds storeEval var d=(new Date().getTime()); d; timeBeforeLoad echo ${timeBeforeLoad} open("http://www.ge.com/");var storeEval win=this.browserbot.getCurrentWindow(); timeAfterLoad if(win)win.onload=(window.status=(new Date().getTime())); echo ${timeAfterLoad} storeEval ${timeAfterLoad}-${timeBeforeLoad} loadTimeMSecs echo ${loadTimeMSecs} Tc#15: Get Xpathcount, rows count and Tablecount XXX 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#
  • 58. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ Test Case Xpath 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} 19. Selenium Core Introduction: • 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.
  • 59. QAPlanet SELENIUM Handbook - -a basic referential guide to Selenium ------------------------------------------------------------------------------------------------------------------------------------------ • 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." • 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 FilesApache Software FoundationApache2.2htdocs