Monday, 17 August 2015

Creating PDF Report using TestNG with Selenium

There are two steps:
1. First Create JyperionListener.java

2. Then use JyperionListener.java in any TestNG class (like we have developed google.java)

1. Create class JyperionListener.java


package reporting;

import java.awt.Color;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import reusable.Base;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;


public class JyperionListener implements ITestListener {
 /**
  * Document
  */
 private Document document = null;
 
 /**
  * PdfPTables
  */
 PdfPTable successTable = null, failTable = null;
 
 /**
  * throwableMap
  */
 private HashMap<Integer, Throwable> throwableMap = null;
 
 /**
  * nbExceptions
  */
 private int nbExceptions = 0;
 
 
 public JyperionListener() {
  log("JyperionListener()");
  
  this.document = new Document();
  this.throwableMap = new HashMap<Integer, Throwable>();
 }
 
 /**
  * @see com.beust.testng.ITestListener#onTestSuccess(com.beust.testng.ITestResult)
  */
 public void onTestSuccess(ITestResult result) {
  log("onTestSuccess("+result+")");
  
  if (successTable == null) {
   this.successTable = new PdfPTable(new float[]{.3f, .3f, .1f, .3f});
   Paragraph p = new Paragraph("PASSED TESTS", new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.BOLD));
   p.setAlignment(Element.ALIGN_CENTER);
   PdfPCell cell = new PdfPCell(p);
   cell.setColspan(4);
   cell.setBackgroundColor(Color.GREEN);
   this.successTable.addCell(cell);
   
   cell = new PdfPCell(new Paragraph("Class"));
   cell.setBackgroundColor(Color.LIGHT_GRAY);
   this.successTable.addCell(cell);
   cell = new PdfPCell(new Paragraph("Method"));
   cell.setBackgroundColor(Color.LIGHT_GRAY);
   this.successTable.addCell(cell);
   cell = new PdfPCell(new Paragraph("Time (ms)"));
   cell.setBackgroundColor(Color.LIGHT_GRAY);
   this.successTable.addCell(cell);
   cell = new PdfPCell(new Paragraph("Exception"));
   cell.setBackgroundColor(Color.LIGHT_GRAY);
   this.successTable.addCell(cell);
  }
  
  PdfPCell cell = new PdfPCell(new Paragraph(result.getTestClass().toString()));
  this.successTable.addCell(cell);
  cell = new PdfPCell(new Paragraph(result.getMethod().getMethodName().toString()));
  this.successTable.addCell(cell);
  cell = new PdfPCell(new Paragraph("" + (result.getEndMillis()-result.getStartMillis())));
  this.successTable.addCell(cell);

  Throwable throwable = result.getThrowable();
  if (throwable != null) {
   this.throwableMap.put(new Integer(throwable.hashCode()), throwable);
   this.nbExceptions++;
   Paragraph excep = new Paragraph(
     new Chunk(throwable.toString(), 
       new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.UNDERLINE)).
       setLocalGoto("" + throwable.hashCode()));
   cell = new PdfPCell(excep);
   this.successTable.addCell(cell);
  } else {
   this.successTable.addCell(new PdfPCell(new Paragraph("")));
  }
 }

 /**
  * @see com.beust.testng.ITestListener#onTestFailure(com.beust.testng.ITestResult)
  */
 public void onTestFailure(ITestResult result) {
  log("onTestFailure("+result+")");
  String file = System.getProperty("user.dir")+"\\Test Results\\Screenshots\\"+"screenshot"+(new Random().nextInt())+".png";
  try {
   Base.takeSnapShot(Base.getDriver(), file);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  if (this.failTable == null) {
   this.failTable = new PdfPTable(new float[]{.3f, .3f, .1f, .3f});
   this.failTable.setTotalWidth(20f);
   Paragraph p = new Paragraph("FAILED TESTS", new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.BOLD));
   p.setAlignment(Element.ALIGN_CENTER);
   PdfPCell cell = new PdfPCell(p);
   cell.setColspan(4);
   cell.setBackgroundColor(Color.RED);
   this.failTable.addCell(cell);
   
   cell = new PdfPCell(new Paragraph("Class"));
   cell.setBackgroundColor(Color.LIGHT_GRAY);
   this.failTable.addCell(cell);
   cell = new PdfPCell(new Paragraph("Method"));
   cell.setBackgroundColor(Color.LIGHT_GRAY);
   this.failTable.addCell(cell);
   cell = new PdfPCell(new Paragraph("Time (ms)"));
   cell.setBackgroundColor(Color.LIGHT_GRAY);
   this.failTable.addCell(cell);
   cell = new PdfPCell(new Paragraph("Exception"));
   cell.setBackgroundColor(Color.LIGHT_GRAY);
   this.failTable.addCell(cell);
  }
  
  PdfPCell cell = new PdfPCell(new Paragraph(result.getTestClass().toString()));
  this.failTable.addCell(cell);
  cell = new PdfPCell(new Paragraph(result.getMethod().getMethodName().toString()));
  this.failTable.addCell(cell);
  cell = new PdfPCell(new Paragraph("" + (result.getEndMillis()-result.getStartMillis())));
  this.failTable.addCell(cell);
  //String exception = result.getThrowable() == null ? "" : result.getThrowable().toString();
  //cell = new PdfPCell(new Paragraph(exception));
  //this.failTable.addCell(cell);
  
  Throwable throwable = result.getThrowable();
  if (throwable != null) {
   this.throwableMap.put(new Integer(throwable.hashCode()), throwable);
   this.nbExceptions++;
   
    Chunk imdb = new Chunk("[SCREEN SHOT]", new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.UNDERLINE));
          imdb.setAction(new PdfAction("file:///"+file));
          Paragraph  excep = new Paragraph(
              throwable.toString());
          excep.add(imdb);
         
   
   
   
  
   //Paragraph excep = new Paragraph(ck.setLocalGoto("" + throwable.hashCode()));
   cell = new PdfPCell(excep);
   this.failTable.addCell(cell);
  } else {
   this.failTable.addCell(new PdfPCell(new Paragraph("")));
  }
 }

 /**
  * @see com.beust.testng.ITestListener#onTestSkipped(com.beust.testng.ITestResult)
  */
 public void onTestSkipped(ITestResult result) {
  log("onTestSkipped("+result+")");
 }

 /**
  * @see com.beust.testng.ITestListener#onStart(com.beust.testng.ITestContext)
  */
 public void onStart(ITestContext context) {
  log("onStart("+context+")");
  try {
   PdfWriter.getInstance(this.document, new FileOutputStream(System.getProperty("user.dir")+"\\Test Results\\Automation Test Report"+".pdf"));
  } catch (Exception e) {
   e.printStackTrace();
  }
  this.document.open();
  
  Paragraph p = new Paragraph(context.getName() + " TESTNG RESULTS",
    FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD, new Color(0, 0, 255)));
  
  try {
   this.document.add(p);
   this.document.add(new Paragraph(new Date().toString()));
  } catch (DocumentException e1) {
   e1.printStackTrace();
  }
 }

 /**
  * @see com.beust.testng.ITestListener#onFinish(com.beust.testng.ITestContext)
  */
 public void onFinish(ITestContext context) {
  log("onFinish("+context+")");
  
  try {
   if (this.failTable != null) {
    log("Added fail table");
    this.failTable.setSpacingBefore(15f);
    this.document.add(this.failTable);
    this.failTable.setSpacingAfter(15f);
   }
   
   if (this.successTable != null) {
    log("Added success table");
    this.successTable.setSpacingBefore(15f);
    this.document.add(this.successTable);
    this.successTable.setSpacingBefore(15f);
   }
  } catch (DocumentException e) {
   e.printStackTrace();
  }
  
  Paragraph p = new Paragraph("EXCEPTIONS SUMMARY",
    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0)));
  try {
   this.document.add(p);
  } catch (DocumentException e1) {
   e1.printStackTrace();
  }
  
  Set<Integer> keys = this.throwableMap.keySet();
  
  assert keys.size() == this.nbExceptions;
  
  for(Integer key : keys) {
   Throwable throwable = this.throwableMap.get(key);
   
   Chunk chunk = new Chunk(throwable.toString(),
     FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(255, 0, 0)));
   chunk.setLocalDestination("" + key);
   Paragraph throwTitlePara = new Paragraph(chunk);
   try {
    this.document.add(throwTitlePara);
   } catch (DocumentException e3) {
    e3.printStackTrace();
   }
   
   StackTraceElement[] elems = throwable.getStackTrace();
   String exception = "";
   for(StackTraceElement ste : elems) {
    Paragraph throwParagraph = new Paragraph(ste.toString());
    try {
     this.document.add(throwParagraph);
    } catch (DocumentException e2) {
     e2.printStackTrace();
    }
   }
  }
  
  this.document.close();
 }
 
 /**
  * log
  * @param o
  */
 public static void log(Object o) {
  //System.out.println("[JyperionListener] " + o);
 }

 public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
  // TODO Auto-generated method stub
  
 }

 public void onTestStart(ITestResult arg0) {
  // TODO Auto-generated method stub
  
 }
}

2. Use JyperionListener.java in TestNG class, find below code of TestNG class:


import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import reporting.JyperionListener;
import reusable.Base;

@Listeners(JyperionListener.class)
public class google {
 static Logger log = Logger.getLogger(NewTest.class);
 static Logger elog = Logger.getLogger("errorLog");
 WebDriver driver;
  
  @Test
  public void google1() {
    PropertyConfigurator.configure("src/main/resources/utilities/log4j.properties");
    log.info("Starting first test case");
    driver = Base.getDriver();
    driver.get("http://www.google.com/");
    Assert.assertTrue(false);
    elog.error("Test Case Fail");      
  }
}

Create HTML, Error and Execution logs using log4j -Create more than 2 log files (Core JAVA)

It will create 3 files:

1. HtmlLogReport.html
2. Logfile.log
3. ErrorLog.log

Implement the logger as per your requirement.

Below is the code for log4j.property

# Define the root logger with appender file
log4j.rootLogger = INFO, FILE, rfile
 

# Define the file appender-Logfile.log
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.logfile.File=./TestLogs/Logfile.log

# Define the layout for file appender-Logfile.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.File=./TestLogs/Logfile.log
log4j.appender.FILE.layout.ConversionPattern=%d [%25F:%t:%L] - %m%n

# Define the layout for RollingFileAppender-HtmlLogReport.html
log4j.appender.rfile=org.apache.log4j.RollingFileAppender
log4j.appender.rfile.File=./TestLogs/HtmlLogReport.html
log4j.appender.rfile.MaxFileSize=1000MB
log4j.appender.rfile.Append=true
log4j.appender.rfile.layout=org.apache.log4j.HTMLLayout
log4j.appender.rfile.layout.Title=HTML Log Report
log4j.appender.rfile.layout.LocationInfo=true
# For Second Log File i.e ErrorLog.log
log4j.appender.errorLog=org.apache.log4j.FileAppender
log4j.appender.errorLog.File=./TestLogs/ErrorLog.log
log4j.appender.errorLog.layout=org.apache.log4j.PatternLayout
log4j.appender.errorLog.layout.ConversionPattern=%d [%25F:%t:%L] - %m%n
log4j.logger.errorLog=TRACE,errorLog

JAVA program to implement above log4j.properties


import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import reusable.Base;

public class google {
 static Logger log = Logger.getLogger(google.class);
 static Logger elog = Logger.getLogger("errorLog");
 WebDriver driver;
  
  @Test
  public void google1() {
    PropertyConfigurator.configure("src/main/resources/utilities/log4j.properties");
    log.info("Starting first test case");
    driver = Base.getDriver();
    driver.get("http://www.google.com/");
    elog.error("Test Case Fail");      
  }
}

Wednesday, 12 August 2015

Sending Email using gmail with Attachment and Text (Core JAVA)

If you want to use this function with testNG then use as below under AfterSuite annotation of TestNG:


//After complete execution send pdf report by email
    
    @AfterSuite
 
    public void tearDown(){
 
        sendPDFReportByGMail("FROM@gmail.com", "PASSWORD", "TO@zellax.com", "PDF Report", "");

 
        }

package reporting;

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.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class PDEmail{
 
 public static void main(String[] args){
  sendPDFReportByGMail("FROM@gmail.com", "PASSWORD", "TO@zellax.com", "PDF Report", "");
 }
 
 public static void sendPDFReportByGMail(String from, String pass, String to, String subject, String body) {
   
  Properties props = System.getProperties();
   
  String host = "smtp.gmail.com";
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.user", from);
  props.put("mail.smtp.password", pass);
  props.put("mail.smtp.port", "587");
  props.put("mail.smtp.auth", "true");
  
  Session session = Session.getDefaultInstance(props);
  
  MimeMessage message = new MimeMessage(session);
  try {
      //Set from address
   
   message.setFrom(new InternetAddress(from));
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
   //Set subject
   message.setSubject(subject);
   message.setText(body);
   
   BodyPart objMessageBodyPart = new MimeBodyPart();
   objMessageBodyPart.setText("Dear Customer,\n\nPlease Find the attached Automation Report File!\n\nThanks and Regards\nZellax Solutions");
   
   Multipart multipart = new MimeMultipart();
   multipart.addBodyPart(objMessageBodyPart);
   objMessageBodyPart = new MimeBodyPart();
   
   //Set path to the pdf report file
   
   String filename = System.getProperty("user.dir")+"\\Default test.pdf";
   
   //Create data source to attach the file in mail
   
   DataSource source = new FileDataSource(filename);
   objMessageBodyPart.setDataHandler(new DataHandler(source));
   objMessageBodyPart.setFileName("Automation Testing Report");
   multipart.addBodyPart(objMessageBodyPart);
   message.setContent(multipart);
   Transport transport = session.getTransport("smtp");
   transport.connect(host, from, pass);
   transport.sendMessage(message, message.getAllRecipients());
   transport.close();
   }
   
  catch (AddressException ae) {
   ae.printStackTrace();   
  }
   
  catch (MessagingException me) {
   me.printStackTrace();   
  } 
}
}
 

Friday, 7 August 2015

Common Functions Used for Selenium Framework



package testing.MavenTestNG;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Set;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class CommonFunctions { 

 static Logger log = Logger.getLogger(CommonFunctions.class.getName());

 static char specialCharacters[] = { '!', '@', '#', '$', '%', '^', '&', '*',
  '(', ')', '?', '/', '"', '|', '{', '[', '<', '>', ';', '`', ',',
  '_', '-' };

 /**
  * Retrieve popup text message.
  * 
  * @param WebDriver
  *            driver
  * @return
  */
 public static String getPopupMessage(final WebDriver driver) {
  String message = null;
  try {
   Alert alert = driver.switchTo().alert();

   message = alert.getText();
   alert.accept();
  } catch (Exception e) {
   // Sometimes the text exist, but not the accept button.
   // this means the popup wasn't displayed and therefore
   // really never existed.
   //
   message = null;
  }
  System.out.println("message"+message);
  return message;
 }

 public static String cancelPopupMessageBox(final WebDriver driver) {
  String message = null;
  try {
   Alert alert = driver.switchTo().alert();

   message = alert.getText();
   alert.dismiss();
  } catch (Exception e) {
   // Sometimes the text exist, but not the accept button.
   // this means the popup wasn't displayed and therefore
   // really never existed.
   //
   message = null;
  }

  return message;
 }

 private static SecureRandom random = new SecureRandom();

 /**
  * Generate random string of special characters of length x
  * 
  * @return
  */
 public String getRandomSpecialString(int length) {
  int len = specialCharacters.length;
  String str = "";
  Random randomGenerator = new Random();
  int index;

  for (int i = 0; i < length; i++) {
   index = randomGenerator.nextInt(len - 1);
   str = str + specialCharacters[index];
  }
  return str;
 }

 /**
  * Generate random string of length x
  * 
  * @return
  */
 public static String getRandomString(int length) {
  String result = new BigInteger(Long.SIZE * length, random).toString(32);
  return result.substring(0, length);
 }

 /**
  * Generate random string of length x
  * 
  * @return
  */
 public static void populateField(WebDriver driver, By locator, String value) {
  WebElement field = driver.findElement(locator);
  field.clear();
  field.sendKeys(value);

 }

 /**
  * Check hover message text
  * 
  * @param driver
  * @param by
  * 
  * @return string
  */
 public static String checkHoverMessage(WebDriver driver, By locator){
  String tooltip = driver.findElement(locator).getAttribute("title");
  return tooltip;
 }

 /**
  * Select radio button
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void selectRadioButton(WebDriver driver, By locator, String value){
  List<WebElement> select = driver.findElements(locator);

  for (WebElement radio : select){
   if (radio.getAttribute("value").equalsIgnoreCase(value)){
    radio.click();               

   }}}

 /**
  * Select multiple check boxes
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void selectCheckboxes(WebDriver driver, By locator, String value){

  List<WebElement> abc = driver.findElements(locator);
  List<String> list = new ArrayList<String>(Arrays.asList(value.split(",")));

  for (String check : list){
   for (WebElement chk : abc){         
    if(chk.getAttribute("value").equalsIgnoreCase(check)){          
     chk.click();                   
    }                               
   }
  }
 }


 /**
  * Select drop down
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void selectDropdown(WebDriver driver, By locator, String value){
  new Select (driver.findElement(locator)).selectByVisibleText(value); }


 /**
  * Select auto-suggest search drop down
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void selectSearchDropdown(WebDriver driver, By locator, String value){
  driver.findElement(locator).click();
  driver.findElement(locator).sendKeys(value);
  driver.findElement(locator).sendKeys(Keys.TAB);  
 }


 /**
  * Upload file
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void uploadFile(WebDriver driver, By locator, String value){
  driver.findElement(locator).sendKeys(value);    
 }


 /**
  * Takes controls on new tab
  * 
  * @param driver
  * 
  */
 public static void handleNewTab(WebDriver driver)
 {
  Set<String> allWindowHandles = driver.getWindowHandles();
  String window0 = (String) allWindowHandles.toArray()[1];
  driver.switchTo().window(window0);
 }


 /**
  * Helper method: looks through a list of WebElements, to find the first WebElement with matching text
  * 
  * @param elements
  * @param text
  * 
  * @return WebElement or null
  */
 public static WebElement findElementByText(List<WebElement> elements, String text) {
  WebElement result = null;
  for (WebElement element : elements) {
   element.getText().trim();
   if (text.equalsIgnoreCase(element.getText().trim())) {
    result = element;
    break;
   }
  }
  return result;
 }


 /**
  * Compact way to verify if an element is on the page
  * 
  * @param driver
  * @param by
  * @return
  */
 public static boolean isElementPresent(final WebDriver driver, By by) {


  try {
   driver.findElement(by);

   return true;
  } catch (NoSuchElementException e) {
   return false;
  }
 }


 /**
  * Downloads a file from the defined url, and saves it into the
  * OutputDatafolder, using the filename defined
  * 
  * @param href
  * @param fileName
  */
 public static void downloadFile(String href, String fileName) throws Exception{

  PropertyConfigurator.configure("config/log4j.properties");

  URL url = null;
  URLConnection con = null;
  int i;

  url = new URL(href);

  con = url.openConnection();
  File file = new File(".//OutputData//" + fileName);
  BufferedInputStream bis = new BufferedInputStream(con.getInputStream());

  BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(file));
  while ((i = bis.read()) != -1) {
   bos.write(i);
  }
  bos.flush();
  bis.close();

 }


 /**
  * Writes content to the excel sheet
  * 
  * @param text
  * @param fileName
  */
 public static void writeExcel(String text,String fileName) throws Exception 
 { 
  FileOutputStream file = new FileOutputStream(".//OutputData//" + fileName+".csv",true);
  WritableWorkbook book = Workbook.createWorkbook(file); 
  WritableSheet sheet = book.createSheet("output", 0);
  Label l = new Label(0, 0, text);
  sheet.addCell(l);
  book.write(); 
  book.close(); 
 }

}