Thursday, August 29, 2013

Delete Cookies



// Go to the correct domain
     driver.get("http://www.example.com");

     // Now set the cookie. This one's valid for the entire domain
     Cookie cookie = new Cookie("key", "value");
     driver.manage().addCookie(cookie);

     // And now output all the available cookies for the current URL
            Set allCookies = driver.manage().getCookies();
     for (Cookie loadedCookie : allCookies) {
       System.out.println(String.format("%s -> %s", loadedCookie.getName(), loadedCookie.getValue()));
     }

     // You can delete cookies in 3 ways
     // By name
     driver.manage().deleteCookieNamed("CookieName");
     // By Cookie
     driver.manage().deleteCookie(loadedCookie);
     // Or all of them
     driver.manage().deleteAllCookies();

Handling Windows and Frames


Windows:
If your site opens a new tab or window, Selenium will let you work with it using a window handle. Each window has a unique identifier which remains persistent in a single session.  
  1. getWindowhandle(): This method helps to get the window handle of the current window.
  2. getWindowhandles(): This method helps to get the handles of all the windows opened.
  3. set: This method helps to set the window handles in the form of a string.
    set<string> set= driver.getWindowhandles()
  4. switch to: This method helps to switch between the windows. 
Syntax:driver.switchTo().window("windowName");
 
 (OR)
 
//Store the ID of the original window
String originalWindow = driver.getWindowHandle();

//Click the link which opens in a new window
driver.findElement(By.linkText("new window")).click();

//Wait for the new window or tab
wait.until(numberOfWindowsToBe(2));

//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
    if(!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break;
    }
}

 
/**
* To close all the other windows except the main window.
*
* @param openWindowHandle
* @return
*/
public static boolean closeAllOtherWindows(WebDriver driver, String openWindowHandle) {
Set allWindowHandles = driver.getWindowHandles();
for (String windowHandle : allWindowHandles) {
if (!windowHandle.equals(openWindowHandle)) {
driver.switchTo().window(windowHandle);
driver.close();
}
}
driver.switchTo().window(openWindowHandle);
if (driver.getWindowHandles().size() == 1)
return true;
else
return false;
}
 

iFrames:

iFrame is basically a tag used in HTML5 like <iframe></iframe>To identify whether an element is on an iframe or not? You just have to right click on the suspected element and check whether you are getting an option such as : ‘This Frame’, ‘View Frame Source’ or ‘Reload Frame’. After right clicking on an element, if you get an option related to frames, that simply means, the element you are trying to locate is aligned on an iframe.
 
To get the count of iframes on a particular web page.
int iFrameSize = driver.findElements(By.tagName("iframe")).size();
Switch To iFrame By Index : Switching to iframe using index is probably used when there are multiple iframes present on a single web page. Index of iframe starts with 0 and the index gets increasing with the number of iframes embedded.
driver.switchTo().frame(0);
driver.switchTo().frame(1);

Switch To iFrame By Name or ID : Name and ID attribute is the most common way of switching to iframe using Selenium.
driver.switchTo().frame("iFrameID");
driver.switchTo().frame("frameName");
 
//To move back to the parent frame
driver.switchTo().defaultContent(); 
//T get back to the main (or most parent) frame
driver.switchTo().parentFrame();
// to access subframes
driver.switchTo().frame("frameName.0.child");

Select a Value from Drop Down Box



List options = driver.findElements(By.xpath(""));
          for (WebElement option : options) {
              if(option.getText().equals("value")){
                   option.click();
              }
          }
(OR)
Select list = new Select(driver.findElement(By.id("selection")));  
       list.selectByVisibleText("value");
(OR)
Select list = new Select(driver.findElement(By.id("selection")));  
       list.selectByIndex("value");
 
(OR)
Select the all options 

Select select = new Select(driver.findElement(By.tagName("select")));
     select.deselectAll();        select.selectByVisibleText("Text");// Based on text
     deselectByVisibleText("Text"); // Based on text
     select.selectByIndex(0); // Based on Index value
     selectByValue("Value"); // Based on Attribute Value
     deselectByValue("Value");// Based on Attribute Value
     isMultiple();// Returns TRUE if the drop-down element allows multiple selections at a time; FALSE if otherwise.
Ex:if( select.isMultiple()){
// Do some operation
}
          (OR)

Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();       
select.selectByText("Value");

                       (OR)
//Select element in multi select box in selenium webdriver

/**
* Select multiple options from a list box
*
* @param driver
* @param objectLocator
* @param values
* -Values by comma separated
* @throws Exception
 */
public void SelectMultiplesFromListBox(WebDriver driver, String values) throws Exception {

try {
if (values != "") {
Select sel = new Select(driver.findElement(By.id("someId"));
List options = sel.getOptions();
boolean isMultiple = sel.isMultiple();
Actions builder = new Actions(driver);
String data[] = values.split(",");
if (isMultiple) {
sel.deselectAll();
}
builder.keyDown(Keys.CONTROL);

// For loop to split and take single data from input data
for (String inputValue : data) {
System.out.println("Value From the inputlist is: " + inputValue);
// For loop to select a data from listbox
for (WebElement option : options) {
System.out.println("Total No of values in the listbox is : " + options.size());
String optionValue = option.getText().trim();
if (optionValue.equalsIgnoreCase(inputValue)) {
if (isMultiple) {
if (!option.isSelected()) {
builder.click(option);
}
}
break;
}
}
}
builder.keyUp(Keys.CONTROL).build().perform();

} else {
System.out.println("Please give some input data to select from the dropdown");
}
} catch (Exception e) {
}
}

 

Take a screenshot with Selenium WebDriver


It is advisable to take screenshots of failed test cases for further analysis and proof of failure.
 
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Copy screenshot to somewhere 
FileUtils.copyFile(screenshot , new File("c:\\tmp\\screenshot.png"));
 
(OR)
public static void takeScreenShot(WebDriver driver, String screenshotPath) throws Exception {
try {
// Convert web driver object to TakeScreenshot TakesScreenshot scrShot = ((TakesScreenshot) driver); // Call getScreenshotAs method to create image file File screenShotImage = scrShot.getScreenshotAs(OutputType.FILE); // Move image file to new destination File destFile = new File(screenshotPath); // Copy file to Destination FileUtils.copyFile(screenShotImage, destFile); } catch (Exception e) { APP_LOGS.error(">>>Error while Taking ScreenShot :<<<" + e.getMessage()); } }

Full Page Screenshot

private void takeFullPageScreenshotZoom(String outputFileName) {
((JavascriptExecutor) driver).executeScript("document.body.style.zoom=(top.window.screen.height-70)/Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);");
takeScreenShot(driver,outputFileName); // declared above
}
Take a screenshot with Selenium RemoteWebDriver:
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot)augmentedDriver).
getScreenshotAs(OutputType.FILE);

Take a partial Screenshot:

public void takePartialScreenShot(WebElement element) throws IOException {

String screenShot = System.getProperty("user.dir") + \\screenShot.png;

File screen = ((TakesScreenshot) this.driver).getScreenshotAs(OutputType.FILE);
Point p = element.getLocation();
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
BufferedImage img = ImageIO.read(screen);
BufferedImage dest = img.getSubimage(p.getX(), p.getY(), width,
height);
ImageIO.write(dest, "png", screen);
FileUtils.copyFile(screen, new File(screenShot));

}
 
Take a screenshot in after method annotation
@AfterMethod
public void takeScreenShotOnFailure(ITestResult testResult) throws IOException {
    if (testResult.getStatus() == ITestResult.FAILURE) {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("errorScreenshots\\" + testResult.getName() + "-"
                + Arrays.toString(testResult.getParameters()) +  ".jpg"));
    }

Take a screenshot for a webelement:
public void captureElementScreenshot(WebElement element) throws IOException{
        //Capture entire page screenshot as buffer.
        File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        //Used selenium getSize() method to get height and width of element.
        int ImageWidth = element.getSize().getWidth();
        int ImageHeight = element.getSize().getHeight();
        //Used selenium Point class to get x y coordinates of Image element.
        //get location(x y coordinates) of the element.
        Point point = element.getLocation();
        int xcord = point.getX();
        int ycord = point.getY();
        //Reading full image screenshot.
        BufferedImage img = ImageIO.read(screen);
        //cut Image using height, width and x y coordinates parameters.
        BufferedImage dest = img.getSubimage(xcord, ycord, ImageWidth, ImageHeight);
        ImageIO.write(dest, "png", screen);
        //Used FileUtils class of apache.commons.io.
        //save Image screenshot In D: drive.
        FileUtils.copyFile(screen, new File("D:\\screenshot.png"));
}