Automation Using Selenium Webdriver

Friday 14 October 2016

How to Send report through email in Selenium Webdriver

Do you know that we can Send report through email in Selenium Webdriver with small code with help of additional jars?
Today I will show you how you can Send report through email in Selenium Webdriver using simple steps and trust me this is one of the most important features that you should include in your framework as well.
It does not matter which framework you are using it could be Keyword driver, Data driven and Hybrid you should implement email report functionality after test execution.

Step by Step process to Send report through email in Selenium Webdriver

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendMailSSLWithAttachment {
public static void main(String[] args) {
// Create object of Property file
Properties props = new Properties();
// this will set host of server- you can change based on your requirement
props.put("mail.smtp.host", "smtp.gmail.com");
// set the port of socket factory
props.put("mail.smtp.socketFactory.port", "465");
// set socket factory
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
// set the authentication to true
props.put("mail.smtp.auth", "true");
// set the port of SMTP server
props.put("mail.smtp.port", "465");
// This will handle the complete authentication
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("add your email", "add your password");
}
});
try {
// Create object of MimeMessage class
Message message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress("thotajagan63@gmail.com"));
// Set the recipient address
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("jagan@gmail.com"));
            
                        // Add the subject link
message.setSubject("Testing Subject");
// Create object to add multimedia type content
BodyPart messageBodyPart1 = new MimeBodyPart();
// Set the body of email
messageBodyPart1.setText("This is message body");
// Create another object to add another content
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
// Mention the file which you want to send
String filename = "G:\\a.xlsx";
// Create data source and pass the filename
DataSource source = new FileDataSource(filename);
// set the handler
messageBodyPart2.setDataHandler(new DataHandler(source));
// set the file
messageBodyPart2.setFileName(filename);
// Create object of MimeMultipart class
Multipart multipart = new MimeMultipart();
// add body part 1
multipart.addBodyPart(messageBodyPart2);
// add body part 2
multipart.addBodyPart(messageBodyPart1);
// set the content
message.setContent(multipart);
// finally send the email
Transport.send(message);
System.out.println("=====Email Sent=====");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

Thursday 13 October 2016

How To Verify Scroll Present On Browser In Selenium WebDriver Test

How To Verify Scroll Present On Browser In Selenium WebDriver Test

 Full webdriver test example to check horizontal and vertical scroll on page Is as bellow. To re-size window and get scrollbar on page, I have used window().setSize() method. You can read more usage detail on window().setSize() method on THIS PAGE.

Run bellow given example In your eclipse and verify result In console. It will check and print scroll bar status In console as per Its availability on different size of browser window.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ScrollPresence {

 WebDriver driver;

 @BeforeTest
 public void setup() throws Exception {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.get("http://google.com/");
 }

 @Test
 public void getScrollStatus() throws Exception {
  //Initially no scroll present on page.
  //Check and print horizontal and vertical scroll status.
  checkAndPrintScrollStatus();
  Thread.sleep(2000);
 
  //resize window to get horizontal scroll on page.
  driver.manage().window().setSize(new Dimension(400,768));
  //Check and print horizontal and vertical scroll status.
  checkAndPrintScrollStatus();
  Thread.sleep(2000);
 
  //resize window to add vertical scroll on page.
  driver.manage().window().setSize(new Dimension(400,400));
  //Check and print horizontal and vertical scroll status.
  checkAndPrintScrollStatus();
  Thread.sleep(2000);
 
  //resize window to remove horizontal scroll from page.
  driver.manage().window().setSize(new Dimension(1024,400));
  //Check and print horizontal and vertical scroll status.
  checkAndPrintScrollStatus();   
 }

 public void checkAndPrintScrollStatus(){
  JavascriptExecutor javascript = (JavascriptExecutor) driver;
  //Check If horizontal scroll Is present or not.
  Boolean b1 = (Boolean) javascript.executeScript("return document.documentElement.scrollWidth>document.documentElement.clientWidth;");
  //Check If vertical scroll Is present or not.
  Boolean b2 = (Boolean) javascript.executeScript("return document.documentElement.scrollHeight>document.documentElement.clientHeight;");
  if (b1 == true && b2 == true) {
   System.out.println("Horizontal and vertical Scrollbar is present on page.");
  } else if (b1 == false && b2 == true) {
   System.out.println("Horizontal Scrollbar not present on page.");
   System.out.println("Vertical Scrollbar is present on page.");
  }else if (b1 == true && b2 == false) {
   System.out.println("Horizontal Scrollbar Is present on page.");
   System.out.println("Vertical Scrollbar not present on page.");
  }else if (b1 == false && b2 == false) {
   System.out.println("Horizontal and Vertical Scrollbar not present on page.");  
  }
  System.out.println("<----------x--------x--------->");
 }
}

How To Handle Dynamic Web Table In Selenium WebDriver

How To Handle Dynamic Web Table  Country Names and Currency List in money.rediff.com

package com.Test.web;
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.chrome.ChromeDriver;

public class TableList {

public static void main(String[] args) {

 /*
* ##########################################################
* ComponentName : Getting Option
* Description   : It is Web Tables Getting List
*  Created By   : Team
* Creation Date : 10th May 2016
* Author        : T Jagan
* ##########################################################
    */

/*I have write to best scenario display all country name and currency list on rediff.com
 * this is easy way  find web tables list on web page
 */
System.out.println("*************************************************");
    System.out.println("Execution is started");

List<WebElement>currencyList;
List<WebElement>rows;
List<WebElement>cells;
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://money.rediff.com/tools/forex");

        rows=driver.findElements(By.xpath("html/body/div[1]/div[5]/div[2]/div[2]/table/tbody/tr"));
    for (int i = 1; i < rows.size(); i++) {
    
     cells=driver.findElements(By.xpath("html/body/div[1]/div[5]/div[2]/div[2]/table/tbody/tr["+i+"]/td"));
     System.out.println("Country Name ::" +cells.get(0).getText());
    
     System.out.println("country Currency Rate::" +cells.get(1).getText());

}


}

}
                               OUTPUT

NameRate
Australian Dollar (AUD)50.27
Bahraini Dinar (BHD)177.63
British Pound (GBP)81.36
Canadian Dollar (CAD)50.32
Chinese Yuan (CNY)9.95
Danish Krone (DKK)9.90
Euro (EUR)73.64
Hong Kong Dollar (HKD)8.63
Iraqi Dinar (IQD)0.06
Japanese Yen (JPY)0.64
Kuwaiti Dinar (KWD)221.59
Omani Rial (OMR)173.21
Pakistani Rupee (PKR)0.64
Qatar Rial (QAR)18.38
Saudi Arabian Riyal (SAR)17.84
Singapore Dollar (SGD)48.28
South African Rand (ZAR)4.66
Swedish Krona (SEK)7.55
Swiss Franc (CHF)67.71
UAE Dirham (AED)18.14
US Dollar (USD)66.92




Wednesday 12 October 2016

Download And Save Image Using Selenium WebDriver + Actions + Robot

Interaction API tutorial section. For downloading Image, We will use same WebDriver Actions class with java robot class.
For saving Image from web page In selenium webdriver, We have to perform bellow given actions.

    Right click on Image
    Select "Save Image As" option from mouse right click context menu.
    Enter file name In save Image dialog
    Press Save button.

Right click on Image using contextClick() method of Actions class
As you know, "Save Image As" option will display when you right click on any Image. We will use contextClick() method of WebDriver Actions class to right click on Image as shown In bellow Image.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Actions_Test {

 WebDriver driver;
 @BeforeTest
 public void setup() throws Exception {
  driver =new FirefoxDriver();    
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.get("http://any website");
 }

 @Test
 public void Save_Image() throws IOException, InterruptedException, AWTException {
  //Locate Image
  WebElement Image =driver.findElement(By.xpath("//img[@border='0']"));
  //Rihgt click on Image using contextClick() method.
  Actions action= new Actions(driver);
  action.contextClick(Image).build().perform();
 
  //To perform press Ctrl + v keyboard button action.
  action.sendKeys(Keys.CONTROL, "v").build().perform();

  Thread.sleep(3000);
  Robot robot = new Robot();
  // To press D key.
  robot.keyPress(KeyEvent.VK_D);
  // To press : key.
  robot.keyPress(KeyEvent.VK_SHIFT);
  robot.keyPress(KeyEvent.VK_SEMICOLON);
  robot.keyRelease(KeyEvent.VK_SHIFT);
  // To press \ key.
  robot.keyPress(KeyEvent.VK_BACK_SLASH);
  // To press "test" key one by one.
  robot.keyPress(KeyEvent.VK_T);
  robot.keyPress(KeyEvent.VK_E);
  robot.keyPress(KeyEvent.VK_S);
  robot.keyPress(KeyEvent.VK_T);
  // To press Save button.
  robot.keyPress(KeyEvent.VK_ENTER); 
 }
}
}

How to verify a Text present in the loaded page through Web Driver

       How to verify a Text present in the loaded page through Web Driver
   
Verify  "Flights"  a text present in a goibibo.com

package exmp;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class VerifyTextWebpage {

public static void main(String[] args) {
// TODO Auto-generated method s
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.goibibo.com/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();

String expText="Flights";
//verify flights text Available are not
String actText=driver.findElement(By.xpath("html/body/div[1]/div[1]/ul/li[1]/a/span")).getText();
if(actText.contains(expText)){
System.out.println("1)Expected Text"+expText+"Preent in the page");
}else{
System.out.println("1)Expected Text"+expText+" not Preent in the page");
}

}

}

//OutPut:1)Expected TextFlightsPreent in the page