Friday, 8 July 2016

How to get list of elements from drop down

How to get list of elements from drop down:
==================================


package com.rameshsoft.draganddrops;;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class TotalElementsWebList {
public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.facebook.com");
WebElement element_day = driver.findElement(By.id("day"));
Select select = new Select(element_day);
// getting all elements from droip down
List<WebElement> totalWebListElements = select.getOptions();
// removing duplicate elements from list if any
HashSet<WebElement> hashSet = new HashSet<WebElement>(totalWebListElements);
// iterating the elements from collection object
Iterator<WebElement> iterator = totalWebListElements.iterator();
while (iterator.hasNext()) {
WebElement webElement = (WebElement) iterator.next();
if (webElement.getText().equalsIgnoreCase("15")) {
webElement.click();

}
}

}
}

Multiple ways of performing Drag and drop operations

1.Way:
=======
package com.rameshsoft.draganddrrop;

import java.awt.AWTException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class DragDropOne {
public static void main(String[] args) throws InterruptedException, AWTException {
        WebDriver driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("http://www.jqueryui.com");
        Actions actions=new Actions(driver);
        WebElement draggable=driver.findElement(By.linkText("Droppable"));
        draggable.click();  
        driver.switchTo().frame(0);      
        WebElement source = driver.findElement(By.id("draggable"));      
        WebElement target = driver.findElement(By.id("droppable"));        
        actions.dragAndDrop(source, target).build().perform();    
        driver.quit();
     
}
}

2.Way:
=======
package com.rameshsoft.draganddrrop;

import java.awt.AWTException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class DragAndDropTwo {

public static void main(String[] args) throws InterruptedException, AWTException {
        WebDriver driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("http://www.jqueryui.com");
        Actions actions=new Actions(driver); 
        WebElement draggable=driver.findElement(By.linkText("Droppable"));
        draggable.click();       
        driver.switchTo().frame(0);
        WebElement source = driver.findElement(By.id("draggable"));       
        WebElement target = driver.findElement(By.id("droppable"));
        Actions builder = new Actions(driver);
        Action dragAndDrop = builder.clickAndHold(source).moveToElement(target).release(target).build();
        dragAndDrop.perform();      
        Thread.sleep(5000);
        driver.quit();
        
}
}

3.Way:
=======
package com.rameshsoft.draganddrrop;

import java.awt.AWTException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class DragAndDropThree {

public static void main(String[] args) throws InterruptedException, AWTException {
        WebDriver driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("http://www.jqueryui.com");
        Actions actions=new Actions(driver); 
        WebElement draggable=driver.findElement(By.linkText("Droppable"));
        draggable.click();       
        driver.switchTo().frame(0);
        WebElement source = driver.findElement(By.id("draggable"));       
        WebElement target = driver.findElement(By.id("droppable"));        
        Actions builder = new Actions(driver);
        Action dragAndDrop =  builder.clickAndHold(source).moveToElement(target, 2, 2).release(target).build();
        dragAndDrop.perform();      
        Thread.sleep(5000);
        driver.quit();
        
}
}

4. Way:
=======
package com.rameshsoft.draganddrrop;

import java.awt.AWTException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class DragAndDropFour {

public static void main(String[] args) throws InterruptedException, AWTException {
        WebDriver driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("http://www.jqueryui.com");
        Actions actions=new Actions(driver); 
        WebElement draggable=driver.findElement(By.linkText("Droppable"));
        draggable.click();       
        driver.switchTo().frame(0);
        WebElement source = driver.findElement(By.id("draggable"));       
        WebElement target = driver.findElement(By.id("droppable"));      
        Actions builder = new Actions(driver);
        builder.clickAndHold(source).moveToElement(target).perform();
        Thread.sleep(2000);
        builder.release(target).build().perform();      
        Thread.sleep(5000);
        driver.quit();
}
}

Wednesday, 6 July 2016

What is javascript executor?



Javascript Executor:
=============
javascriptexecutor is an interface. and which is available in org.openqa.selenium.JavascriptExecutor;
which provides mechanism to execute Javascript through selenium driver. It provides “executescript” & "executeAsyncScript" methods, to run JavaScript in the context of the currently selected frame or window. 
We can use Javascript to perform actions Using selenium Webdriver. By using ‘JavascriptExecutor’ we can perform these actions


Why we use it?
==========
To enhance the capabilities of the existing scripts by performing javascript injection into our application under test.


In simple words  “Javascript can be executed within the browser with the help of JavaScript Executor.”

Mousehover:
=========
WebElement element = driver.findElement(By.xpath("//a"));
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("arguments[0].onmouseover()", element);

Click():
=====
WebElement element = driver.findElement(By.id(“Email”));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(“arguments[0].click();”, element);

WebElement element = driver.findElement(By.className(“”));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(“arguments[0].click();”, element);


OR:
===
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(“window.document.getElementById(‘Email).click()”);


How to refresh the browser window using Javascript:
===================================
JavascriptExecutor js = (JavascriptExecutor)driver;
driver.executeScript("history.go(0)");

Get Title:
=======
driver.get("https://www.google.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript(“return document.title”);
System.out.println(“title : ” + title);
OUTPUT | title : Google

or
JavascriptExecutor js = (JavascriptExecutor)driver;
string sText =  js.executeScript("return document.title;").toString();
Scroll bar operations:
  JavascriptExecutor js = (JavascriptExecutor)driver;
  //Vertical scroll - down by 50  pixels
  js.executeScript("window.scrollBy(0,50)");

Get Domain name:
============
driver.get(“https://www.google.com);
JavascriptExecutor js = (JavascriptExecutor) driver;
String domain = (String) js.executeScript(“return document.domain”);
System.out.println(“domain : ” + domain);
OUTPUT | domain :
http://www.google.co.in

Get URL:
======
driver.get(“http://google.co.in/&#8221;);
JavascriptExecutor js = (JavascriptExecutor) driver;
String URL = (String) js.executeScript(“return document.URL”);
System.out.println(“Full URL : ” + URL);
OUTPUT | Full URL :
https://www.google.co.in/

Get Attribute | Text:
==============
driver.get(“http://google.co.in/&#8221;);
Object exampleDiv = ((JavascriptExecutor) driver).executeScript(“return document.getElementById(‘main’);”);
String name = ((WebElement) exampleDiv).getAttribute(“class”);
System.out.println(name);
OUTPUT | content


Last Modified:
=========
driver.get(“http://google.co.in/&#8221;);
JavascriptExecutor js = (JavascriptExecutor) driver;
String lastModified = (String) js.executeScript(“return document.lastModified”);
System.out.println(“lastModified : ” + lastModified);
OUTPUT | lastModified : 01/29/2014 14:56:46





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(&quot;Element Not Found&quot;);   
         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();
    }
}