Showing posts with label RC. Show all posts
Showing posts with label RC. Show all posts

Wednesday, April 25, 2012

How to Generate Reports using JUnit + Ant


Generating reports using Ant. Follow the below steps

1. Create 2-3 test cases
    Testcase1.java
    Testcase2.java
2. Create a test suite as follows
   
package testcases;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;


@RunWith(Suite.class)
@SuiteClasses({
Testcase1.class,
Testcase2.class,
})
public class FooterLinks_Suite {
}


3. Check whether the above test suite is running successfully. If ran successfully then do the following
   right click on the project root folder --> Export --> General --> Ant Buildfiles --> select the project --> click on Finish
   Below is the image representation for clear understanding.



4. This will create build.xml file
5. right click on build.xml file --> select "2 Ant Build"


Select build, testcases, junitreport checkboxes


6.Click on Run after Editing configuration.
7. Build Successful message as follows





8. After Build is Successfull, then a folder with "junit" will be created under root project.


9. Click on junit folder created, it will show respective html files


10. Double click on index.html file, which will display as below.







Tuesday, April 17, 2012

How to handle logging in Selenium RC


Main thing while automating your application is Logging and Report Generation.
Below is the process how to implement logging with log4j.jar

Follow the steps
1. Go to apache site http://logging.apache.org/log4j/1.2/download.html and download log4j-1.2.16.jar file
2. Under Eclipse create a java class with name Log4jXmlTest
and paste the following code

import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.server.SeleniumServer;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;


public class Log4jXmlTest extends SeleneseTestCase {
SeleniumServer seleniumserver;


   private static Logger Log = Logger.getLogger(Log4jXmlTest.class.getName());

   @Before
public void setUp() throws Exception {
    try{
    seleniumserver = new SeleniumServer();
    seleniumserver.start();
    int i = seleniumserver.getPort();
    System.out.println("Selenium Running on Port:"+i);
   
    }
    catch(Exception e){
    e.printStackTrace();
    }
   
    DOMConfigurator.configure("log4j.xml");
    Log.info("______________________________________________________________");
    Log.info("Initializing Selenium...");
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.google.co.in/");
selenium.start();
Log.info("Selenium instance started");
}

   @Test
public void testAdvancedSearch() throws Exception {
    Log.info("Opening Google Website");
selenium.open("http://www.google.com/");
Log.info("Clicking on advanced search link");
selenium.click("link=Advanced search");
selenium.waitForPageToLoad("30000");
Log.info("Entering search terms");
selenium.type("as_q", "selenium,selftechy");
Log.info("Clicking on Advanced Search button");
selenium.click("//input[@value='Advanced Search']");
selenium.waitForPageToLoad("30000");
}

@After
public void tearDown() throws Exception {
Log.info("Stopping Selenium...");
Log.info("______________________________________________________________");
selenium.stop();
}

}


3. Again Create .xml file with name log4j.xml and paste the following


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="fileAppender" class="org.apache.log4j.FileAppender">
<param name="Threshold" value="INFO" />
<param name="File" value="logfile.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="fileAppender"/>
</root>
</log4j:configuration>


Note:  While doing copy paste, be careful that double quotes will be in some other format. So after pasting the code verify once that it should not throw any error.

4. Place the xml file created above in the project root folder.
    To place the xml file in root folder do the following
     Go to your main project name in eclipse and right click and select --> Properties
     You will see the Location under Resources link from the Properties window
     Go to that folder and paste the xml file
4. Run the Log4jXmlTest java file
5. After successful running of java class, xml file create logfile.log file which will have the logs.



It will create logfile.log  text file under root directory of the project if you manually go to the specified directory. Here is the log file which if you follow the above steps



2012-04-17 19:54:43,627 INFO  [Log4jXmlTest] ______________________________________________________________
2012-04-17 19:54:43,627 INFO  [Log4jXmlTest] Initializing Selenium...
2012-04-17 19:54:43,752 INFO  [Credential] Checking Resource aliases
2012-04-17 19:54:43,768 INFO  [SeleniumDriverResourceHandler] Command request: getNewBrowserSession[*chrome, http://www.google.co.in/, ] on session null
2012-04-17 19:54:43,783 INFO  [BrowserSessionFactory] creating new remote session
2012-04-17 19:54:43,971 INFO  [BrowserSessionFactory] Allocated session cc6ea8df996c412e8aca55f3d9d56080 for http://www.google.co.in/, launching...
2012-04-17 19:54:44,221 INFO  [FirefoxChromeLauncher] Preparing Firefox profile...
2012-04-17 19:54:47,377 INFO  [FirefoxChromeLauncher] Launching Firefox...
2012-04-17 19:54:52,299 INFO  [SeleniumDriverResourceHandler] Got result: OK,cc6ea8df996c412e8aca55f3d9d56080 on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:52,299 INFO  [Log4jXmlTest] Selenium instance started
2012-04-17 19:54:52,299 INFO  [Log4jXmlTest] Opening Google Website
2012-04-17 19:54:52,299 INFO  [SeleniumDriverResourceHandler] Command request: open[http://www.google.com/, ] on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:52,299 WARN  [SeleniumDriverResourceHandler] you appear to be changing domains from http://www.google.co.in/ to http://www.google.com/
this may lead to a 'Permission denied' from the browser (unless it is running as *iehta or *chrome,
or alternatively the selenium server is running in proxy injection mode)
2012-04-17 19:54:57,298 INFO  [SeleniumDriverResourceHandler] Got result: OK on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:57,298 INFO  [Log4jXmlTest] Clicking on advanced search link
2012-04-17 19:54:57,298 INFO  [SeleniumDriverResourceHandler] Command request: click[link=Advanced search, ] on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:57,361 INFO  [SeleniumDriverResourceHandler] Got result: OK on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:57,361 INFO  [SeleniumDriverResourceHandler] Command request: waitForPageToLoad[30000, ] on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:59,298 INFO  [SeleniumDriverResourceHandler] Got result: OK on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:59,298 INFO  [Log4jXmlTest] Entering search terms
2012-04-17 19:54:59,298 INFO  [SeleniumDriverResourceHandler] Command request: type[as_q, selenium,selftechy] on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:59,470 INFO  [SeleniumDriverResourceHandler] Got result: OK on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:59,470 INFO  [Log4jXmlTest] Clicking on Advanced Search button
2012-04-17 19:54:59,470 INFO  [SeleniumDriverResourceHandler] Command request: click[//input[@value='Advanced Search'], ] on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:59,580 INFO  [SeleniumDriverResourceHandler] Got result: OK on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:54:59,580 INFO  [SeleniumDriverResourceHandler] Command request: waitForPageToLoad[30000, ] on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:55:02,486 INFO  [SeleniumDriverResourceHandler] Got result: OK on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:55:02,486 INFO  [Log4jXmlTest] Stopping Selenium...
2012-04-17 19:55:02,486 INFO  [Log4jXmlTest] ______________________________________________________________
2012-04-17 19:55:02,486 INFO  [SeleniumDriverResourceHandler] Command request: testComplete[, ] on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:55:02,486 INFO  [FirefoxChromeLauncher] Killing Firefox...
2012-04-17 19:55:02,861 INFO  [SeleniumDriverResourceHandler] Got result: OK on session cc6ea8df996c412e8aca55f3d9d56080
2012-04-17 19:55:02,876 INFO  [SeleniumServer] Shutting down...
2012-04-17 19:55:02,876 INFO  [ThreadedServer] Stopping Acceptor ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=4444]
2012-04-17 19:55:02,986 INFO  [SocketListener] Stopped SocketListener on 0.0.0.0:4444
2012-04-17 19:55:03,033 INFO  [Container] Stopped HttpContext[/selenium-server/driver,/selenium-server/driver]
2012-04-17 19:55:03,095 INFO  [Container] Stopped HttpContext[/selenium-server,/selenium-server]
2012-04-17 19:55:03,142 INFO  [Container] Stopped HttpContext[/,/]
2012-04-17 19:55:03,142 INFO  [Container] Stopped org.openqa.jetty.jetty.servlet.ServletHandler@1befab0
2012-04-17 19:55:03,204 INFO  [Container] Stopped HttpContext[/wd,/wd]
2012-04-17 19:55:03,204 INFO  [Container] Stopped org.openqa.jetty.jetty.Server@1f20eeb

How to Upload / Attach any file or document with Selenium RC



Steps that need to follow
1. In order to upload files we need to have AutoIT (freeware BASIC-like scripting language designed for automating the Windows GUI -- keystrokes, mouse actions ).
2. Download AutoIT software from http://www.autoitscript.com/site/autoit/downloads/
3. Install upon clicking the downloaded AutoIT.exe file
4. If you want to upload a file into your application/system, create a document (Ex: lets say uploadFile.doc )
5. Next step is go to any folder in your drive and right click --> New --> AutoIT v3 Script    and select script.
6. It will open up AutoIT v3 script file, enter the following code at last and save the file as if you save any document with some name (Ex: lets say attachDocScript.au3  )


WinWaitActive("Choose File")
Send("C:\Program Files\AutoIt3\uploadFile.doc")   // specify your own path where attaching document is located.
Send("{ENTER}")


7. Close the AutoIT script file and right click on this, select compile the script -- which generates .exe file of the same. (Ex: attachDocScript.exe )
8. In your selenium program enter the following code after clicking the attach button from your application.


try {
String[] commands = new String[]{};
commands = new String[]{"C:\\Program Files\\AutoIt3\\attachDocScript.exe"}; //location of the autoit executable
Runtime.getRuntime().exec(commands);
    }
catch (IOException e) {}


9. Now run your progam. you Can see that you uploaded the document in your application successfully.

write the selenium output result into a document instead of console


If you want to display all the links into a text file or word document then you can do as follows
1. We have getAllLinks() in selenium which will prints all links to the console output.
     
     selenium.getAllLinks();

2. Instantiate FileWriter and BufferedWriter from java.io package.
4. If need to write the output into a text file then store all links into an String array as follows

     
 String alllinks [] = selenium.getAllLinks();

5. Use "for loop" to write the values into file with help of BufferedWriter object.


System.out.println("Get All Links");
String alllinks [] = selenium.getAllLinks();

FileWriter fileWriter2 = new FileWriter("D:\\allLinks.doc");
BufferedWriter bufferedWriter2 = new BufferedWriter(fileWriter2);
bufferedWriter2.write("Get All Links");
for(int c=0; c<alllinks.length; c++){

        bufferedWriter2.write(alllinks[c]);
        bufferedWriter2.newLine();
    System.out.println("\n");
} bufferedWriter2.close();


Wednesday, October 5, 2011

Selenium PageObject

PageObject

• PageObjects is a design pattern where objects representing your pages are exposed to the
test logic as services providing access to the elements and logic of your page
• The pattern is defined along the following:
o The public methods exposes the services the page offers
o The internals of the page should not be exposed
o Don’t make assertions in the PageObject class, it is the test logic’s work
o Methods return other PageObjects
o You don’t need to represent an entire page, just the services you need to test
o One action can have several methods depending on the result of these actions
• PageObjects' methods exposes actions on the page (a login action for instance) and must return another PageObject:


class LoginPage
@error_message
//Once logged-in, the server redirects to the home page so the login methods should return a PageObject representing the homepage
def loginAs(username, password)
# ...
HomePage.new
end

//We test a failed login gives the correct message. Since it is a failed login, we stay on the login page so we return the same object
def loginAsExpectingError(username, password)
# ...
# error_message = something
self
end
def error_message
@error_message
//We can return here the error message displayed on the page in case of failed login
end



public class LoginPage {
private String errorMessage;
//Once logged-in, the server redirects to the home page so the login methods should return a PageObject representing the homepage

public HomePage loginAs(username, password) {
...
return new HomePage();
}
public LoginPage loginAsExpectingError(username, password) {
//We test a failed login gives the correct message. Since it is a failed login, we stay on the login page so we return the same object

...
errorMessage = something;
return self;
}

public void getErrorMessage() {
return errorMessage;
//We can return here the error message displayed on the page in case of failed login
}
}



• The PageObject pattern is a good practice because:
- It facilitates code reuse: think about inheritance and abstract classes
- It facilitates maintenance: code logic and page are separated



PageObject Pattern
We’re going to transform our tests to follow the PageObject pattern
Java
• You will find in the project in the labs/lab6/java folder a Page class as well as a Lab6 containing the test to run
• The Page class is the class from which all your projects will inherit from
• The Lab6 class contains the test and therefore, the methods to implement in your page objects

Selenium RC

Overview of Selenium RC
While Selenium IDE may seem a productive and efficient tool for writing test-cases, it lacks many essential features of a testing tool:
Conditional statements
Loops
Logging
Exception handling
Reporting
Test fixtures and data-driven tests
Test dependencies
Taking screenshots
Selenium RC is the answer to a more powerful test-suite for your applications.
It follows a client/server model allowing client libraries to execute tests on a browser controlled by the server.



Selenium Server
• Selenium server is the program that drives the browser
• It embeds Selenium Core framework and injects it into the browser
• It communicates with the running test client and drives the browser
• Client tests sends commands that the server interpretes in order to drive the browser
• The server sends back results to the client
• Client and server communicates via HTTP GETs and POSTs so you can easily plug into
• Server is configurable at startup via command-line options. use java -jar selenium-server.jar -h to see the list of options
Client libraries
• Client libraries provides the API to program tests and execute them on the server
• Each implementation provides access to all Selenium commands
• Supported API implementation exists in:
- Java (also accessible via Groovy)
- Net
- PHP
- Python
- Perl
- Ruby


Installation of Selenium RC

Prerequisites
• A JVM installed on the system
• A Ruby distribution with the rspec and selenium-client gems installed if
• you’re working
• The Selenium RC archive


Running The RC Server
• Unzip the Selenium RC archive somewhere on your system
• Go into the selenium-rc, then the selenium-server folder
• Open a terminal in this folder and enter the command java -jar selenium-server.jar
• If there’s no error messages, your Selenium RC server should be running now.



Running A Test (Java)
• Create a new Java project in Eclipse or your Java IDE
• Add the selenium-java-client-driver.jar jar to the project’s classpath
• Add a new JUnit test-case to the project. When asked, select Junit 4
• You should now have an empty .java file
• Open the lab2 test-case on Selenium IDE
• On Selenium IDE, open the Options menu then Format… and click Java (Junit)
• Copy/paste the contents in the JUnit file on Eclipse
• Change the package name at your will
• You may have to fix the imports
o Click on the following icon and choose the most appropriate option to correct the file
o You may also press Ctrl + Shift + O to let Eclipse do it automatically
• At this point you shouldn’t have any more errors and you are ready to run the test
• Selenium RC will open a couple of Firefox windows and run the test


Junit
• Junit is the reference unit-testing framework for Java
• The framework allows you to test your applications using specific classes containing the logic performing actions on the tested classes and checking the results
• Eclipse provides support for Junit, so we’ll be using that
• JUnit 3 uses named methods to detect set-up and test methods

Selenium Locators

Locators
Selenium uses what is called locators to find and match the elements of your page that it needs to interact with.Selenium Locators can be classified into two categories:
Structure-based locators: locators that rely on the structure of the page to find elements.


  • XPath



  • DOM



  • CSS

  • Attributes-based locators: locators that relies on the attributes of the elements to locate them


  • Identifier



  • Id



  • Name



  • Link



  • CSS


  • In General there are 8 locators strategies included in Selenium:
    • Identifier
    • Id
    • Name
    • Link
    • DOM
    • XPath
    • CSS
    • UI-element


    Will look each of the locator in detail:

    1. Identifier:
    works with the id and name attributes of your html tags. Let’s consider the following example:


    <html>
    <body>
    <form id="login">
    <input name="username" type="text"/>
    <input name="password" type="password"/>
    <input name="submit" type="submit" value="Continue!"/>
    </form>
    </body>
    </html>

    Valid locators for this snippet are :
    • identifier=login
    • identifier=username
    • submit


    Id

    The Id strategy looks for an element in the page having an id attribute corresponding to the specified pattern. <label id="my_id" /> will be matched by a locator like id=my_id or just my_id

    Name

    Like the Id strategy, but on the name attribute. You can also specify a filter to refine your locator. Currently, there are two filter types :
    Value : matches elements with a name attribute and where the value follows a pattern. The following example illustrates the interest of filters :
    <html>
    <body>
    <div id="pancakes">
    <button type="button" name="pancake" value="Blueberry">Blueberry</button>
    <button type="button" name="pancake" value="Banana">Banana</button>
    <button type="button" name="pancake" value="Strawberry">Strawberry</button>
    </div>
    </body>
    </html>

    Scenario:
    we just added a strawberry pancake in our application and we want to test that the button that adds it into the cart works. With a locator like name=pancake, Selenium will find 3 elements and return the first one : the test will never fail even if the strawberry button is not here! Use a value filter like name=pancake value=Strawberry and the locator successfully identifies the Strawberry button.
    Index : same as name but works with an index. Using the previous example, the locator name=pancake index=2 will select the Strawberry button.





    Link
    This strategy is intended to select links only and selects the anchor element containing the specified text: link=The text of the link


    DOM
    The DOM strategy works by locating elements that matches the javascript expression refering to an element in the DOM of the page.
    • dom=document.div['pancakes'].button[0]
    • document.div[0].button[2]
    • dom=function foo() { return document.getElementById("pancakes"); }; foo();


    XPath
    While DOM is the recognized standard for navigation through an HTML element tree, XPath is the standard navigation tool for XML; and an HTML document is also an XML document (xHTML). XPath is used everywhere where there is XML. Valid XPath locators can be:
    • xpath=//button[@value="Blueberry"]: matches the Blueberry button
    • //div[@id="pancakes"]/button[0]: same thing


    CSS
    The CSS locator strategy uses CSS selectors to find the elements in the page. Selenium supports CSS 1 through 3 selectors


    UI-Elements
    • UI-element is a rather new locator
    • It was at first a Selenium IDE extension
    • It is now fully integrated into Selenium





    If you are not sure that you didnt got from above, below is reference:

    Element Locators

    Element Locators tell Selenium which HTML element a command refers to. The format of a locator is:
    locatorType=argument
    We support the following strategies for locating elements:
    • identifier=id: Select the element with the specified @id attribute. If no match is found, select the first element whose @name attribute is id. (This is normally the default; see below.)
    • id=id: Select the element with the specified @id attribute.
    • name=name: Select the first element with the specified @name attribute.
      • username
      • name=username
      The name may optionally be followed by one or more element-filters, separated from the name by whitespace. If the filterType is not specified, value is assumed.
      • name=flavour value=chocolate
    • dom=javascriptExpression: Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object Model using JavaScript. Note that you must not return a value in this string; simply make it the last expression in the block.
      • dom=document.forms['myForm'].myDropdown
      • dom=document.images[56]
      • dom=function foo() { return document.links[1]; }; foo();
    • xpath=xpathExpression: Locate an element using an XPath expression.
      • xpath=//img[@alt='The image alt text']
      • xpath=//table[@id='table1']//tr[4]/td[2]
      • xpath=//a[contains(@href,'#id1')]
      • xpath=//a[contains(@href,'#id1')]/@class
      • xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
      • xpath=//input[@name='name2' and @value='yes']
      • xpath=//*[text()="right"]
    • link=textPattern: Select the link (anchor) element which contains text matching the specified pattern.
      • link=The link text
    • css=cssSelectorSyntax: Select the element using css selectors. Please refer to CSS2 selectors, CSS3 selectors for more information. You can also check the TestCssLocators test in the selenium test suite for an example of usage, which is included in the downloaded selenium core package.
      • css=a[href="#id3"]
      • css=span#firstChild + span
      Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after).
    Without an explicit locator prefix, Selenium uses the following default strategies:
    • dom, for locators starting with "document."
    • xpath, for locators starting with "//"
    • identifier, otherwise

    Element Filters

    Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator.
    Filters look much like locators, ie.
    filterType=argument
    Supported element-filters are:
    value=valuePattern
    Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons.
    index=index
    Selects a single element based on its position in the list (offset from zero).

    String-match Patterns

    Various Pattern syntaxes are available for matching string values:
    • glob:pattern: Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a kind of limited regular-expression syntax typically used in command-line shells. In a glob pattern, "*" represents any sequence of characters, and "?" represents any single character. Glob patterns match against the entire string.
    • regexp:regexp: Match a string using a regular-expression. The full power of JavaScript regular-expressions is available.
    • exact:string: Match a string exactly, verbatim, without any of that fancy wildcard stuff.
    If no pattern prefix is specified, Selenium assumes that it's a "glob" pattern.

    Selenium Commands

    Commands
    The Selenium API defines dozens of commands that can be categorized into the following:
    • Actions
    • Accessors
    • Assertions

    Actions
    Actions are commands that change the state of the application like clicking links or buttons, select an option in a <select> or type a character sequence in a given textbox.

    Eg : clickAndWait(locator) command which will trigger a click and stop the test until the browser has finished loading a new page.

    Accessors

    Accessors inspect the state of the application and store values in variables.
    Eg : storeCookies(variableName) stores all the cookies in use in the current page in the variable variableName.

    Assertions
    Assertions are also able to inspect the current page but:

    - They’re made to return a boolean value
    - This boolean represents the conformity of the element to a desired pattern
    - Usually, the pattern represents the state of an element.

    • Assertions come into 3 flavors:
    - assert : if assertion fails, test is aborted and marked as failed : assertTitle(pattern) will fail if the title of the page doesn’t correspond to the pattern argument.
    - verify : if a verification fails, the test doesn’t stop but a trace will be printed in the log.
    - waitFor : these commands pause the test until a condition is satisfied or a timeout is reached.

    Selenium Test Cases And Test Suites

    Selenese
    • Selenium IDE produces tests that are written in a DSL (Domain Specific Language) called Selenese Commands.
    • Selenese tests are simple xHTML tables of 3 columns and as many rows that there are steps in your test.
    The rule for these commands is:
    o A method on the first column: the action to perform
    o A locator on the second column: the subject of the method (ie: what element is acted upon)
    o A value on the third one: the value to be passed to the method (what to type in a text field for instance)




    Pizza Test


    Pizza Test
    open /
    type q pizza
    click btnG
    assertTextPresent regexp:*pizza*



    1. The subject of the command open: the root of the application here
    2. q is the locator referring to the text field in which type will write pizza
    3. click doesn’t need a second argument, we just click on an element (which locator is btnG)
    4. assertTextPresent doesn’t need a locator since it searches on the entire page: we just need what to look for


    And the corresponding source below - usually you don’t have to touch it, Selenium IDE will do it for you:
    Selenese test-case source.






    Test Suites

    You can assemble test-cases into a test-suite
    • They are also expressed as HTML files
    • The test-suite only references test-case files as anchor elements
    • The anchors are nested inside a table of 1 column and as many rows as there are test-cases in the test-suite



    Selenium IDE

    Overview of Selenium IDE

    Selenium IDE features:
    • record/play mechanism: create/edit tests by recording the user actions on the page
    • Debugging feature with step-by-step and breakpoints
    • Page abstraction capabilities
    • Automatic assertions for the page title
    • An extensibility feature allowing the use of plugins or user extensions that extend the capabilities of Selenium IDE

    Presentation: How Selenium IDE look like

    The interface features the following elements:
    • An action bar to control the test (1)

    Action bar has the following:
    1.The base url of the application
    2.Test speed
    3.Run test-suite
    4.Run the selected test case only
    5.Pause the test
    6.Next step (while paused only)
    7.Open Selenium TestRunner
    8.Apply rollups (see Section 9.5, “Rollups”)
    9.Start/Stop recording

    • A test-suite tool (2)
    Shows the tests in the current test-suite along with the results.
    • A test editor (3)


    Test Editor has following sections:
    1.The test steps
    2.The command of the current step
    3.The locator argument
    4.‘Find’ button highlights the target of the locator on the page
    5.The value argument
    • A tool panel (4)


    Tool Panel has following sections:

    1.Log: shows the execution log of the current tests and displays errors
    2.Reference: displays the documentation of the command actually selected
    3.UI-Element: diplays the ui-element mappings actually in use
    4.Rollup: shows rollup rules
    5.Stored-vars : displays current stored variables
    6.Log level (only with log panel): customize the verbosity of the log
    7.Clear log (only with log panel): clears the log


    Export Features


    A most interesting feature of Selenium IDE: export to Selenium RC. Selenium IDE is able to export test cases in the following formats:
    • Java (Junit 3/4 and TestNG)
    • Groovy (Junit)
    • C#
    • Perl
    • Python
    • PHP
    • Ruby (RSpec and Test/Unit)
    You can export test-cases or the entire test-suite.


    Installation
    Selenium IDE is a Firefox extension:
    1. Go to the Selenium website (http://www.seleniumhq.org) or the Firefox add-ons website (http://addons.mozilla.org)
    2. Download the latest release of selenium IDE(1.0.8 at the time of writing)
    3. Follow the instructions and restart Firefox
    4. Selenium IDE is accessible from the ‘Tools’ Menu of Firefox

    Example Excercise

    1. Open Firefox, go to http://www.google.com. Then, open Selenium IDE (‘Tools’ → ‘Selenium IDE’)



    2. Make sure the record button is activated, then type in the search field pizza.


    3. Click anywhere on the page or press tab to validate the entry. The Selenium IDE window now looks like this:



    4. Click the Google Search button. You can see the click command appear in the IDE.
    •On the result page, do a right-click and select the assertTitle command:
    5. The command appears in the IDE window

    Selenium Tutorial

    Selenium Overview
    • One of the most popular testing frameworks for web applications as of today
    • First open-source test framework using an user-centric point of view
    • Supports javascript
    • Unintrusive and doesn’t need any modifications of your app to test it

    Selenium, as of today, is composed of several projects :
    1. Selenium Core The JavaScript framework that provides Selenium the ability to drive the browser and execute the tests
    2. Selenium IDE The Firefox plugin used to build test-cases and test-suites directly on top of your web-app. You can also export your tests to Selenium RC.
    3. Selenium RC A client/server system that allows you to execute tests written in a variety of languages on a local or remote computer and on all major browsers.
    4. Selenium Grid Selenium Grid leverages Selenium RC to provide a test environment that spans on multiple machines at once, reducing the testing time.
    5. Selenium on Rails A framework that is built especially to test applications running on the Rails framework.
    6. CubicTest An Eclipse plugin which purpose is to conceive and execute tests using the pageObjects pattern.
    7. Bromine A simple web-based QA tool targeting the single tester that doesn’t want/can’t invest in complex corporate QA solutions.

    Thursday, December 16, 2010

    Selenium IDE Useful Commands

    Selenium IDE is an integrated development environment for Selenium scripts. It is implemented as a Firefox extension.
    Selenium IDE allows you to record, edit, and debug tests. 


    Selenium IDE can be downloaded from http://seleniumhq.org/download/ 

    Recording any action on a page will be done using commands known as Selenese Commands.

    Most common Commands used as follows:

    verifyTextPresent  
          Verifies that text appears on the page.  It can be dynamic text that was loaded with ajax.  If it’s on the page in the active window at the time this command is called, it’ll find it.

    verifyValue
              Verifies the value of an input field.  Provide the id of the input as the target and the value is the text you’re expecting.

    click 
             Tells the test to click something on the page.  The target can be referenced with the element ID or xPath as with the other commands.

    clickAndWait
          This command is useful for form submissions.  Many times when you’re in record mode and click a submit button, selenium will only record a “click” command.  This will break your test commands following the form submission where you verify the presence of a success message or form values because the next page hasn’t loaded yet.  The “wait” portion will wait to continue the testing when the next page has fully loaded. 

    select
          select an option in a select box by providing the id of the select box and the option value.
       
    verifyAttribute
               Useful for checking the attributes (attributes such as class, style, href and anchor tags)   for specific url.
               To verifyAttribute first thing you need to do is viewXpath by right clicking on particular attribute.

                Xpath catcher is an add-on for firefox to viewXpath. You can download Xpath catcher from https://addons.mozilla.org/en-US/firefox/addon/1095/?id=1095 


    Steps to find Xpath
            1.Right click on attribute and select viewXpath 
            2.Copy the Xpath in target field of the Selenium IDE
            3.Edit the xpath copied as follows
                         For example you have xpath as  id('p_13872472-main_story')/x:div/x:div/x:h3/x:a
                        You have to edit in the following manner for verifying class attribute
                         //div[@id='p_13872472-main_story']/div/div/h3/a/@class