Tuesday 15 March 2016

How to take screenshots@remote in selenium

How to take screenshots@remote in selenium :
===================================
package com.rameshselenium.remotescreenshot
import java.io.File;
import java.net.URL;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {
   
    public void myTest() throws Exception {
        WebDriver driver = new RemoteWebDriver(
                                new URL("http://localhost:4444/wd/hub"),
                                DesiredCapabilities.firefox());
       
        driver.get("http://rameshselenium.blogspot.in/");
       
        // RemoteWebDriver does not implement the TakesScreenshot class
        // if the driver does have the Capabilities to take a screenshot
        // then Augmenter will add the TakesScreenshot methods to the instance
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshot = ((TakesScreenshot)augmentedDriver).
                            getScreenshotAs(OutputType.FILE);
    }
}

How to take screenshots on failure in selenium webdriver

How to take screenshots on failure in selenium webdriver:
============================================
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import org.apache.commons.io.FileUtils;

import org.testng.annotations.Test;         

public class webDriverTakeScreenshot {
   public WebDriver driver;               

   @Test
   public void runDummyTest() throws Exception {    
      driver = new FirefoxDriver();
      driver.get("http://rameshselenium.blogspot.in/");

      try {               
         driver.findElement(By.id("")).click();
      }
      catch(Exception e) {    
         System.out.println("Element Not Found");   
         takeScreenshot();     
      }     
   }

   public void takeScreenshot() throws Exception {             
      File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(scrFile, new File(C:\\test\\failed-test.png));     
   }
}

How to Create, Update and Delete Cookies in Seleniu WebDriver

How to Create, Update and Delete Cookies in Seleniu WebDriver:
==================================================
Almost all websites use cookies in one form or another. Cookies are a way of remembering users and their interaction with the site by storing information in the cookie file as key value pairs.

When testing a website with Selenium WebDriver, sometimes it is necessary to handle cookies, such as creating new cookies, updating existing cookies with new information or deleting cookies.

In this webdriver tutorial we look at handling cookies in webdriver. Java code examples of how to create, update and delete cookies using selenium webdriver.

To use any of the cookie handling methods in webdriver, we first need to import the Cookie class. To do that, we use

Java

import org.openqa.selenium.Cookie;

Retrieve All Cookies:
-----------------------
//This method gets all the cookies
public Set<Cookie> getAllCookies() {
   return driver.manage().getCookies();
}

Retrieve a named cookie:
--------------------------
//This method gets a specified cookie
public Cookie getCookieNamed(String name) {
   return driver.manage().getCookieNamed(name);
}

Retrieve the value of a cookie:
-----------------------------------
//This method gets the value of a specified cookie
public String getValueOfCookieNamed(String name) {
   return driver.manage().getCookieNamed(name).getValue();
}

Add a Cookie
--------------
//This method adds or creates a cookie
public void addCookie(String name, String value, String domain, String path, Date expiry) {
   driver.manage().addCookie(
   new Cookie(name, value, domain, path, expiry));
}

Add a set of cookies:
----------------------
//This method adds set of cookies for a domain
public void addCookiesToBrowser(Set<Cookie> cookies, String domain) {
   for (Cookie c : cookies) {
      if (c != null) {
         if (c.getDomain().contains(domain)){
            driver.manage().addCookie(
            new Cookie(name, value, domain, path, expiry));
         }
      }
   }
   driver.navigate().refresh();
}

Delete a specific Cookie:
-------------------------
//This method deletes a specific cookie
public void deleteCookieNamed(String name) {
   driver.manage().deleteCookieNamed(name);
}

Delete all Cookies
----------------------
//This method deletes all cookies
public void deleteAllCookies() {
   driver.manage().deleteAllCookies();
}

How to Restore Cookies in New Browser Window in selenium webdriver

How to Restore Cookies in New Browser Window in selenium webdriver:
=======================================================
Suppose we have to test for the following scenario:

1. Go to login page and login to the application
2. Close the browser
3. Open the browser and go to login page – the user should not see login form and should be already logged in.

On first login, cookies are stored in the browser. In WebDriver, when the browser window is closed, all session data and cookies are deleted, so the testing of the above scenario becomes impossible.

Luckily, WebDriver has functionality to read the cookies from the browser before closing it and then restore the cookies in the new browser window.

Restore Cookies in New BrowserJava

package com.testingexcellence.webdriver
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
<div style="clear:both; margin-top:0em; margin-bottom:1em;"><a href="http://www.testingexcellence.com/how-to-resize-browser-window-in-webdriver/" target="_blank" rel="nofollow" class="udf9e9f4d3032696469537e117b295605"><div style="padding-left:1em; padding-right:1em;"><span class="ctaText"></span>  <span class="postTitle">How to Resize Browser Window in WebDriver</span></div></a></div>
import java.util.Set;

public class CookieTest {
    WebDriver driver;

    @Test
    public void login_state_should_be_restored() {
        driver = new FirefoxDriver();

        driver.get("http://www.example.com/login");
        driver.findElement(By.id("username")).sendKeys("admin");
        driver.findElement(By.id("password")).sendKeys("12345");
        driver.findElement(By.id("login")).click();

        Assert.assertTrue(
              driver.findElement(By.id("welcome")).isDisplayed());

        //Before closing the browser, read the cookies
        Set<Cookie> allCookies = driver.manage().getCookies();

        driver.close();

        //open a new browser window
        driver = new FirefoxDriver();

        //restore all cookies from previous session
        for(Cookie cookie : allCookies) {
            driver.manage().addCookie(cookie);
        }

        driver.get("http://www.example.com/login");
       
        //Login page should not be disaplyed
        Assert.assertTrue(
              driver.findElement(By.id("welcome")).isDisplayed());
       
        driver.close();
    }
}

Selenium: start selenium server code with java

Selenium: start selenium server code with java:
====================================
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.Selenium;
import java.net.BindException;
import java.net.ServerSocket;

public class Server {
    public static SeleniumServer server;
    public static void startSeleniumServer() throws Exception {

       try {
        ServerSocket serverSocket = new ServerSocket(RemoteControlConfiguration.DEFAULT_PORT);
        serverSocket.close();
                //Server not up, start it
                try {
                 RemoteControlConfiguration rcc = new RemoteControlConfiguration();
                 rcc.setPort(RemoteControlConfiguration.DEFAULT_PORT);
                 server = new SeleniumServer(false, rcc);
<div style="clear:both; margin-top:0em; margin-bottom:1em;"><a href="http://www.testingexcellence.com/functional-automated-testing-best-practices-with-selenium-webdriver/" target="_blank" rel="nofollow" class="u9564324059517523bc81d41b5e23dad7"><div style="padding-left:1em; padding-right:1em;"><span class="ctaText"></span>  <span class="postTitle">Functional Automated Testing Best Practices with Selenium WebDriver</span></div></a></div>
                } catch (Exception e) {
                    System.err.println("Could not create Selenium Server because of: "
                            + e.getMessage());
                    e.printStackTrace();
                }
                try {
                    server.start();
                    System.out.println("Server started");
                } catch (Exception e) {
                    System.err.println("Could not start Selenium Server because of: "
                            + e.getMessage());
                    e.printStackTrace();
                }
            } catch (BindException e) {
                System.out.println("Selenium server already up, will reuse...");
            }
    }

    public static void stopSeleniumServer(Selenium selenium){
        selenium.stop();
        if (server != null)
          {
             try
             {
                 selenium.shutDownSeleniumServer();
                 server.stop();

                server = null;
             }
             catch (Exception e)
             {
                e.printStackTrace();
             }
          }
    }

broken links based on response code using selenium webdriver

Broken links based on response code using selenium webdriver:
=================================================
import com.jayway.restassured.response.Response;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.List;

import static com.jayway.restassured.RestAssured.given;

public class HttpResponseCode {
<div style="clear:both; margin-top:0em; margin-bottom:1em;"><a href="http://www.testingexcellence.com/how-to-create-update-and-delete-cookies-in-webdriver/" target="_blank" rel="nofollow" class="u0b585470f054c23045cf8ba03aa2e6e5"><div style="padding-left:1em; padding-right:1em;"><span class="ctaText"></span>  <span class="postTitle">How to Create, Update and Delete Cookies in WebDriver</span></div></a></div>
    WebDriver driver;
    Response response;

    public void checkBrokenLinks() {
        driver = new FirefoxDriver();
        driver.get("http://rameshselenium.blogspot.in/");

        //Get all the links on the page
        List<WebElement> links = driver.findElements(By.cssSelector("a"));

        String href;
       
        for(WebElement link : links) {
            href = link.getAttribute("href");
            response = given().get(href).then().extract().response();

            if(200 != response.getStatusCode()) {
                System.out.println(href + " gave a response code of " + response.getStatusCode());
            }
        }
    }

    public static void main(String args[]) {
        new HttpResponseCode().checkBrokenLinks();
    }
}

How to get Response Status Code with Selenium WebDriver

How to get Response Status Code with Selenium WebDriver:
==============================================

Quite often when you are running automated checks with Selenium WebDriver, you also want to check the response status code for a resource, such as a web service or other webpages on the site. You can also check for broken links on the site as you are executing Selenium WebDriver scripts.

Let’s review the different http status codes:

2xx – OK
3xx – Redirection
4xx – Resource not found
5xx – Server error

In Selenium WebDriver there is no direct method to check the response status code, so we have to use another library for this. We can use Apache HttpClient or I prefer to use REST-assured library from Jayway

To get the response code using REST-assured we can use:

import com.jayway.restassured.response.Response;
import static com.jayway.restassured.RestAssured.given;

public class HttpResponseCode {

    public void checkHttpResponseCode(String url) {
        Response response =
                given().get(url)
                        .then().extract().response();

        System.out.println(response.getStatusCode());
    }

    public static void main(String args[]) {
        new HttpResponseCode().checkHttpResponseCode("http://www.google.com");
    }
}

How to Capture Network Traffic and Http Requests From WebDriver

How to Capture Network Traffic and Http Requests From WebDriver:
===================================================

Selenium 1 has a built-in mechanism to record network traffic and http requests by setting the selenium.start(“captureNetworkTraffic=true”);

Unfortunately this solution is not available “out of the box” in Selenium 2 or WebDriver.

You can capture network traffic using a proxy, such as the BrowserMob Proxy (http://proxy.browsermob.com)

To configure the use of the proxy with a webdriver instance, set the CapabilityName.PROXY value to a org.openqa.selenium.Proxy instance:



package com.rameshselenium.blogspot;

     Proxy proxy = new Proxy();
     // The URL here is the URL that the browsermob proxy is using
     proxy.setHttpProxy("localhost:9100");

     DesiredCapabilities capabilities = DesiredCapabilities.firefox();
     capabilities.setCapability(CapabilityType.PROXY, proxy);

     WebDriver driver = new FirefoxDriver(capabilities);

Monday 14 March 2016

How to perform internationalization through selenium webdriver

How to perform internationalization through selenium webdriver:
==================================================
package enhancements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class InternationDemo {

    public static void main(String[] args) {
       
        FirefoxProfile profile = new FirefoxProfile();
       
        profile.setPreference("intl.accept_languages","sl");


        WebDriver driver = new FirefoxDriver(profile); driver.get("http://www.google.com/");
       
        driver.findElement(By.name("q")).sendKeys("selenium");
       
        driver.findElement(By.name("btnG")).click();
       
       
    }
   
}