Thursday 1 August 2013

Grid with SeleniumWebdriver


import java.io.File;
 import java.net.MalformedURLException;
 import java.net.URL;

import org.junit.AfterClass;
 import org.openqa.selenium.*;
 import org.openqa.selenium.chrome.ChromeDriver;
 import org.openqa.selenium.ie.InternetExplorerDriver;
 import org.openqa.selenium.remote.DesiredCapabilities;
 import org.openqa.selenium.remote.RemoteWebDriver;
 import org.testng.annotations.*;

public class GridWithWebdriver {

 public WebDriver driver;

 @Parameters({"browser"})
 @BeforeClass
 public void setup(String browser) throws MalformedURLException {

 DesiredCapabilities capability=null;
 //setting Chrome driver location
 System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\lib\\chromedriver.exe");
if(browser.equalsIgnoreCase("firefox")){
 System.out.println("firefox");
 capability= DesiredCapabilities.firefox();
 capability.setBrowserName("firefox");
capability.setPlatform(org.openqa.selenium.Platform.ANY);
 //capability.setVersion("");
 }

 if(browser.equalsIgnoreCase("chrome")){
 System.out.println("chrome");
 capability= DesiredCapabilities.chrome();
 capability.setBrowserName("chrome");
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
 //capability.setVersion("");
 }

 driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
 driver.manage().window().maximize();
 driver.navigate().to("http://google.com");

 }

 @Test
 public void test_first() throws InterruptedException{
 Thread.sleep(3000);
 WebElement search_editbox = driver.findElement(By.name("q"));
 WebElement search_button = driver.findElement(By.name("btnG"));
 search_editbox.clear();
 search_editbox.sendKeys("first");
 search_button.click();
 driver.navigate().to("http://yahoo.com");
 String MYURL=driver.getCurrentUrl();
 System.out.println(MYURL);
 Thread.sleep(3000);
 }

 @Test
 public void test_second() throws InterruptedException{
 driver.navigate().to("http://CNN.com");
 String MYA=driver.getCurrentUrl();
 System.out.println(MYA);
 Thread.sleep(3000);
 driver.navigate().to("http://google.com");
 WebElement search_editbox=driver.findElement(By.name("q"));
 WebElement search_button=driver.findElement(By.name("btnG"));
 search_editbox.clear();
 search_editbox.sendKeys("second");
 search_button.click();
 }

 @AfterClass
 public void tearDown(){
 driver.close();
 }
 }
 //-Then started the selenium grid as per the below.

java -jar selenium-server-standalone-2.32.0.jar -role hub
 java -jar selenium-server-standalone-2.32.0.jar -role webdriver -hub http://localhost:4444/grid/register -browser browserName=firefox,platform=WINDOWS
 java -jar selenium-server-standalone-2.32.0.jar -role webdriver -hub http://localhost:4444/grid/register -browser browserName=chrome,platform=WINDOWS -port 5556

//My testng.XML file as per the below.

<suite name="Same TestCases on Different Browser" verbose="3" parallel="tests" thread-count="2">
<test name="Run on Mozilla Firefox">
 <parameter name="browser" value="firefox"/>
 <classes>
 <class name="GridWithWebdriver"/>
 </classes>
 <test name="Run on goolge Chrome">
 <parameter name="browser" value="chrome"/>
 <classes>
 <class name="GridWithWebdriver"/>
 </classes>
 </test>
</test>
</suite>


When i ran the XML file as testng suite below error occurred.Hope any one may able to help.



Friday 26 July 2013

Upload Files in Selenium Webdriver

Please go through below code ......


package Sample;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class uploadfile {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.files.com/");
driver.manage().window().maximize();
WebElement uploadElement = driver.findElement(By.xpath(".//*[@id='uploadFields']/input"));
//WebElement uploadElement = driver.findElement(By.id("uploadfile_0"));
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
uploadElement.sendKeys("C:\\Users\\shivap\\Desktop\\24-1374658179-13.jpg");
driver.close();

}
}

Happy Testing 

Sauce Labs With Selenium Webdriver



Overview

Ø  Sauce on Demand is a cloud-based service that allows you to run 
automated cross- browser functional tests at high speeds in parallel, 
so you   don’t need to maintain testing infrastructure.

Ø  Easy-to-use tools let you build both manual and automated tests 
that produce media-rich results, including screen shots and videos 
of bugs that can be added to any bug tracking system.

Ø  Sauce Support 65+browser and OS combination.

Ø  Operating Systems like Windows, Linux, Mac,

Ø  Browsers like Internet Explorer, Chrome, Firefox, Safari, Opera,
 I Phone, IPod, Android.

Ø  All latest browsers versions are available.

Ø  It has commercial support for selenium.

SAUCE CONNECT

Ø  Sauce Connect securely proxies browser traffic between Sauce 
Labscloud-based 
VMs and your local servers. Connect uses ports 443 and 80for communication
 with Sauces cloud.

Ø  Sauce Connect helps to do HTML Layout Testing.

Ø  This can be used by both Front End designers and Testers for performing manual compatibility testing.

Configure Sauce Connect

Ø   First we need to register in https://saucelabs.com/ website.

Ø  Download Sauce Connect.jar file from the Sauce labs site.

Ø  Run the Jar as below 
java -jar Sauce-Connect.jar YOUR-SAUCE-USERNAME(sivaprasadk) 
YOUR- SAUCE-API-KEY(d75aaba0-ed9c-4ec8-aa35-17c5ed17b402)

Ø  Login to the Sauce Labs web site using valid user credentials.( Here I have given my        credentials mentioned in previous point)

Ø  Select “New Interactive Session”
Ø  Browse the url`s (we can use the localhost url`s as well).

Screenshot of configured sauce Connect:

 Example Script for Sauce:

package sample;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;

public class Test2 {
private WebDriver driver;
@Test

public void setUp() throws Exception {
  DesiredCapabilities capabilities = DesiredCapabilities.firefox();
  capabilities.setCapability("version", "5");
  capabilities.setCapability("platform", Platform.windows);

  this.driver = new RemoteWebDriver(new URL
("http://sivaprasadk:d75aaba0-ed9c-4ec8-aa35-17c5ed17b402@ondemand.saucelabs.com:80/wd/hub"),
                capabilities);
    }

   
@Test
    public void Login_Paytm() throws Exception {
   
driver.get("https://www.paytm.com/");
driver.findElement(By.cssSelector("span")).click();
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys("9880070959");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("Proceed")).click();
driver.findElement(By.id("opns")).click();
driver.findElement(By.id("loggedout")).click();
driver.quit();
}}

 Integration of Web driver and Sauce Services Sauce support Web 
driver scripts and can compatible with multiple programming languages 
like Java, Python, NodeJs, Perl. Here,

We are using java language for Integration and Functional Test Automation 
    (Selenium2 with java bindings).

Steps to Follow:

Ø    A Java File is written, which will take browsers Name, OS and browser 
    version as run time arguments.

Ø   The Script reads the inputs and invokes the Sauce browser with the given
    OS and browser combination in Sauce Cloud.

Ø   On invoking the Selenium functional script the tests will get executed in
    the Sauce Cloud.

Ø   Here we used HtmlTestRunner(unit test module for python) for maintaining
    test suite.

Ø   The test results can be captured from Sauce or from Html Test Report 
    (which will be generated using HtmlTestRunner).

 Dashboard – Sauce

    Like below we can find the results after completing test scripts.



Features of Sauce Cloud:

·       Developer Tools in Every Browser
·       Selenium RC & WebDriver Compatible
·       Video Recordings of Every Test
·       Test Local and Firewalled Servers
·       Any Programming Language
·       Browsers and Mobile Emulators

Advantages:

·       Easy to Integrate with Continuous Integration and Selenium2 test scripts.
·       Able to run the Parallel functional tests, which helps to optimize the 
    test execution Time.
·       Supports multiple browsers and OS combination including mobile browsers.
·       By using this approach, we can perform Functional, Layout, Compatibility 
    testing.
·       Sauce, in built support of Video recording and Screenshot capturing is very
    helpful and good.
·       Availability of updated Browsers and Versions.
·       Secure Tunnel system.

Dis Advantages:

·       Issues with Corporate Proxy environment.
·       As this tool works over cloud script runs very slowly.

References:

    http://saucelabs.com/features 

Thursday 18 July 2013

Selenium grid Configuration With Screenshots


  Selenium grid Configuration With Screenshots


Overview:

Selenium Grid is a tool that dramatically speeds up functional testing of web-apps by leveraging your existing computing infrastructure. It allows you to easily run multiple tests in parallel, on multiple machines, in a heterogeneous environment. 
Based on the excellent Selenium web testing tool, Selenium Grid allows you to run multiple instances of Selenium Remote Control in parallel. Selenium Grid cuts down on the time required to run a Selenium test suite to a fraction of the time that a single instance of Selenium instance would take to run.

Selenium Grid Architecture




  Prerequisites:


1.      Need to download and install the latest Java JRE on system. JRE file can find at http://www.oracle.com/technetwork/java/index-jsp-141438.html

2.      Set the environment variables for java.

3.      Once environment setup is completed, open up a command prompt and run the command java -version. It should look something like the image below.



4.      Need to download Apache Ant and expand the archive to a folder on hard drive. Set the environment variables for Ant. Once setup is completed open up a terminal\
             Command prompt and type ant -version.

 It should look something like the image below



5.      Download latest version of selenium grid from

The folders structure should look like:         





    Running the sample test script:


Now that the environment and test data are set up, you can run two different scenarios of parallel testing:

1.      Test script run in different browsers on a server.

2.  Test script run in parallel on remote machines in different browsers.                                                                                                                                                                                                                    

1.Test script run in different browsers on a server


First we have to start our server. Fallow this commands using command prompt
Launching the Hub:
C:\>cd Program Files
C:\> Program Files\> cd java
C:\> Program Files\> java\> cd selenium-grid-1.0.8
C :\> Program Files\> java\> selenium-grid-1.0.8\> ant launch-hub

This will launch the Selenium Hub on 4444 port. It should look something like the image below.


Now we need to register 2 remote controls to Grid Hub. One is RC running for Firefox tests and the other for Google chrome tests.


               Open the new command prompt from the Grid directory and run the following
             Command.


C:\>cd Program Files
C:\> Program Files\> cd java
C:\> Program Files\> java\> cd selenium-grid-1.0.8
C :\> Program Files\> java\> selenium-grid-1.0.8\>ant -Dport=5556 -Denvironment=*firefox launch-remote-control  


 This will start Remote Control instance on 5556 and will be listening to Grid Hub.
Open another command prompt from the Grid directory and run the following command

C:\>cd Program Files
C:\> Program Files\> cd java
C:\> Program Files\> java\> cd selenium-grid-1.0.8
C :\> Program Files\> java\> selenium-grid-1.0.8\>ant -Dport=5556 -Denvironment=*firefox launch-remote-control 

This will start Remote Control instance on 5557 and will be listening to Grid Hub.

Open the browser and launching following URL http://localhost:4444/console

So far configured details can be seen by clicking above URL.


This is to make sure RCs registered to Grid Hub

 Selenium Grid Hub console













Available Remote Controls
     All the remote controls which we have launched above will be listed in Grid console window.

Active Remote Controls
              Remote Control to which scripts are currently running are called as active RC’S.
Executing Script on multiple browsers:

This script launches instances of Google chrome, Firefox browsers. It will open the www.gifts.com website and clicks on “birthday as occasion” link. It asserts whether the landing page displays the birthday gifts in all the two browsers as expected.


Test script:

     package gift Shop;
     import org.testng.annotations.Test;
     import org.testng.Assert;
     import org.testng.annotations.AfterClass;
     import org.testng.annotations.BeforeClass;
     import org.testng.annotations.Parameters;
     import com.thoughtworks.selenium.DefaultSelenium;
     import com.thoughtworks.selenium.Selenium;
    public class giftBox
    {
    Selenium selenium;
                //Declaration of variables used in this program
               String strTimeout="30000";
               String bdayTitle="Birthday Gifts - Birthday Gift Ideas from Gifts.com";
              int intsleepTime=15000;
               @BeforeClass

  //Reads the values of host, port, browser and url "www.gifts.com" from testng.xml

  @Parameters({ "selenium.host", "selenium.port", "selenium.browser",     "selenium.url" })



 public void beforeClass(String host, String port, String browser, String url)
               {
        selenium = new DefaultSelenium(host, Integer.parseInt(port),browser, url);
        selenium.start();
        selenium.open("");
        selenium.windowMaximize();
        selenium.windowFocus();
        selenium.deleteAllVisibleCookies();
        }
        @Test
        @Parameters({ "bdayLink" })
        public void testB(String bDayGift)
        {
        try
         {
         //Click on birthday as occasion on www.gifts.com website
         selenium.click(bDayGift);
         selenium.waitForPageToLoad(strTimeout);

         //Verify that the birthday gift items page is displayed

         Assert.assertEquals(bdayTitle, selenium.getTitle());
         Thread.sleep(intsleepTime);
         }
         catch (Exception e)
         {
          e.printStackTrace();
         }
         }
         @AfterClass
         public void afterClass()
         {
         selenium.close();
         selenium.stop();}}


.XML file :
As we are going to use multiple sets of data, XML file will help us to maintain data and it will be easy to understand and modify.

Create an xml file (ex: testng.xml) and specify the browser and port names with which we have configured our selenium remote control as in the below piece of code.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests">

            <test name="Firefox">
                        <parameter name="selenium.host" value="localhost"/>
                        <parameter name="selenium.port" value="5556"/>
                        <parameter name="selenium.browser" value="*firefox"/>
                        <parameter name="selenium.url" value="http://www.gifts.com/"/>
                        <parameter name="bdayLink" value="//li[@id='nav-oc']/div/ul[3]/li[3]/a/b"/>
                        <classes>
                                    <class name="giftShop.giftBox" />
                        </classes>
            </test>
           
<test name=" GoogleChrome ">
                        <parameter name="selenium.host" value="localhost"/>
                        <parameter name="selenium.port" value="5557"/>
                        <parameter name="selenium.browser" value="*googlechrome"/>
                        <parameter name="selenium.url" value="http://www.gifts.com/"/>
                        <parameter name="bdayLink" value="//li[@id='nav-oc']/div/ul[3]/li[3]/a/b"/>
                        <classes>
                                    <class name="giftShop.giftBox" />
                        </classes>
            </test>
</suite>



 2.  Test script run in parallel on remote machines in different browsers:

First we have to start our Grid Hub in one machine. Follow these commands using command prompt
Launching the Hub:

C:\>cd Program Files
C :\> Program Files\> cd java
C :\> Program Files\> java\> cd selenium-grid-1.0.8
C :\> Program Files\> java\> selenium-grid-1.0.8\> ant launch-hub

Start the nodes:

Now we need to register remote controls from first machine to hub.  now RC is running on Firefox browser.

             Open the command prompt from the Grid directory and run the following command.


C:\>cd Program Files
C :\> Program Files\> cd java
C :\> Program Files\> java\> cd selenium-grid-1.0.8
C :\> Program Files\> java\> selenium-grid-1.0.8\>ant -Dport=5555 –   Dhost=192.168.101.10 -DhubURL=http://192.168.101.10:4444 –Denvironment=*firefox launch-remote-control 


 This will start Remote Control instance on 5555 and will be listening to Grid hub which is launched in other system.
Now we need to register remote controls from second machine to hub.  Now RC is running on Google chrome.

C:\>cd Program Files
C :\> Program Files\> cd java
C :\> Program Files\> java\> cd selenium-grid-1.0.8
C :\> Program Files\> java\> selenium-grid-1.0.8\> ant -Dport=5557 –Dhost=<192.168.101.3> -DhubURL=http://localhost:4444        -Denvironment=*googlechrome launch-remote-control

This will start Remote Control instance on 5557 and will be listening to hub.

Open the browser and launch the following URL http://localhost:4444/console

So far configured details can be seen by clicking above URL.

This is to make sure RCs registered to hub.                                 

                                      Selenium Grid Hub console


Executing Sample Script in Multiple machines Using Grid:

This script launches Google chrome, Firefox browsers in multiple machines. It will open the www.gifts.com website and clicks on “birthday as occasion” link. It asserts whether the landing page displays the birthday gifts in all the two browsers in different machines as expected.


Test script:

package gift Shop;
import org.testng.annotations.Test;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class giftBox
{
Selenium selenium;
            //Declaration of variables used in this program
            String strTimeout="30000";
            String bdayTitle="Birthday Gifts - Birthday Gift Ideas from Gifts.com";
            int intsleepTime=15000;
             @BeforeClass

 //Reads the values of host, port, browser and url "www.gifts.com" from testng.xml

 @Parameters({ "selenium.host", "selenium.port", "selenium.browser",    "selenium.url" })



 public void beforeClass(String host, String port, String browser, String url)
               {
        selenium = new DefaultSelenium(host, Integer.parseInt(port),browser, url);
        selenium.start();
        selenium.open("");
        selenium.windowMaximize();
        selenium.windowFocus();
        selenium.deleteAllVisibleCookies();
        }
        @Test
        @Parameters({ "bdayLink" })
        public void testB(String bDayGift)
        {
        try
         {
         //Click on birthday as occasion on www.gifts.com website
         selenium.click(bDayGift);
         selenium.waitForPageToLoad(strTimeout);
         //Verify that the birthday gift items page is displayed
         Assert.assertEquals(bdayTitle, selenium.getTitle());
         Thread.sleep(intsleepTime);
         }
         catch (Exception e)
         {
          e.printStackTrace();
         }
         }
         @AfterClass
         public void afterClass()
         {
         selenium.close();
         selenium.stop();}}



.XML file:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests">

            <test name="Opera">
                        <parameter name="selenium.host" value="192.168.101.10"/>
                        <parameter name="selenium.port" value="5557"/>
                        <parameter name="selenium.browser" value="*opera"/>
                        <parameter name="selenium.url" value="http://www.gifts.com/"/>
                        <parameter name="bdayLink" value="//li[@id='nav-oc']/div/ul[3]/li[3]/a/b"/>
                        <classes>
                                    <class name="giftShop.giftBox" />
                        </classes>
            </test>
           
<test name="GoogleChrome">
                        <parameter name="selenium.host" value="192.168.101.12"/>
                        <parameter name="selenium.port" value="5555"/>
                        <parameter name="selenium.browser" value="*googlechrome"/>
                        <parameter name="selenium.url" value="http://www.gifts.com/"/>
                        <parameter name="bdayLink" value="//li[@id='nav-oc']/div/ul[3]/li[3]/a/b"/>
                        <classes>
                                    <class name="giftShop.giftBox" />
                        </classes>
            </test>
</suite>