Send Automation Reports as Mail Report

screen-shot-2012-11-13-at-11-25-44-pm

    Automation test reports are one of the important deliverable of Automation executions. Getting those automation reports in the mail automatically is the another important concept. Here, I would like to share the information about how to send your automation reports as mail report with attachment while automation of your application with Java or C# languages.

Send automation test reports with Java language:

Prerequisites:

        Need to add javax.mail dependency in pom.xml of your automation project (if it is a Maven project. Otherwise need to add javax.mail jar in your Java Build Path of your Java project). Following is the javax.mail dependency,

<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>

Following sendMailReport() method helps to send test automation reports with attachment,

public static void sendMailReport() throws AddressException, MessagingException {
String subject = “”, message = “”, maillist = “”, EMAIL_REPORT_FOLDER = “”;
subject = “Automation Test Report_”;
message = “Please find the attached report to get details.”;
maillist = “mail_lists_of_recipients”;
EMAIL_REPORT_FOLDER = “path_to_automation_report_folder”;
Properties properties = new Properties();
properties.put(“mail.smtp.host”, “smtp.gmail.com”);
properties.put(“mail.smtp.port”, “587”);
properties.put(“mail.smtp.auth”, “true”);
properties.put(“mail.smtp.starttls.enable”, “true”);
final String userName;
final String password;
userName = “sender_mail_address”;
password = “sender_mail_account_password”;
properties.put(“mail.user”, userName);
properties.put(“mail.password”, password);

Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
DateFormat dff = new SimpleDateFormat(“EEE MMM dd, yyyy HH:mm:ss z”);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(maillist));
msg.setSubject(subject + ” – ” + dff.format(new Date()).toString());
msg.setSentDate(new Date());

// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, “text/html”);

// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

// adds attachments
List<String> filesList = new ArrayList<String>();
File[] files = new File(System.getProperty(“user.dir”) + EMAIL_REPORT_FOLDER).listFiles();
for (File file : files) {
if (file.isFile()) {
filesList.add(System.getProperty(“user.dir”) + EMAIL_REPORT_FOLDER + “/” + file.getName());
}
}
if (filesList != null && filesList.size() > 0) {
for (String filePath : filesList) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail’s content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}

Send automation test reports with C# language:

       The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. Following Send_Report_In_Mail() method helps to send test automation reports with attachment,

public void Send_Report_In_Mail()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(“smtp.gmail.com”);
mail.From = new MailAddress(“sender_mail_address”);
mail.To.Add(“mail_lists_of_recipients”);

StringBuilder TimeAndDate = new StringBuilder(DateTime.Now.ToString());
TimeAndDate.Replace(“/”, “_”);
TimeAndDate.Replace(“:”, “_”);

mail.Subject = “Automation Test Report_”+ TimeAndDate;

mail.Body = “Please find the attached report to get details.”;

string actualPath = AppDomain.CurrentDomain.BaseDirectory.Replace(“\\bin\\Debug”, “\\Test_Execution_Reports”); //Reports should stored in Test_Execution_Reports folder

var mostRecentlyModified = Directory.GetFiles(actualPath, “*.html”)
.Select(f => new FileInfo(f))
.OrderByDescending(fi => fi.LastWriteTime)
.First()
.FullName;

Attachment attachment;
attachment = new Attachment(mostRecentlyModified);
mail.Attachments.Add(attachment);

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(“sender_mail_address”, “sender_mail_account_password”);
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);

}

     You can use those method in @AfterSuite if you are using TestNG. In case of NUnit(C#), you can use those method in [OneTimeTearDown]. Try to use above code snippet in your automation scripts to send your automation test report as mail report automatically.

make it perfect !

Parallel Test Executions in Automation – TestNG and NUnit

cross_platform

      One day I got an opportunity to automate an application using both Selenium Java and Selenium C#, that was the specific requirement of the customer to do it on both Java and C#. Later customer said to execute different test cases from different class in different browsers in parallel mode. Their aim was to complete the execution of all test cases in a minimum amount of time. Here, I would like to share how I achieved the parallel execution in both Selenium Java and Selenium C#.

Parallel Execution in Selenium Java Automation:

       In case of Selenium Java, I used TestNG’s parallel execution capability with support of attribute parallel=”tests” along with the tag in TestNG XML. I have created two tags to launch two different driver instances. Following is the sample testng.xml which I used for parallel execution:

<suite name=”TestSuite” parallel=”tests” preserve-order=”true”>
<test name=”Test In Google Chrome”>
<parameter name=”browserName” value=”Chrome”/>
<classes>
<class name=”com.test.TestSuiteClassSmoke”/>
</classes>
</test>
<test name=”Test In Firefox”>
<parameter name=”browserName” value=”Firefox”/>
<classes>
<class name=”com.test.TestSuiteClassSanity”/>
</classes>
</test>
</suite>

      In the above testng.xml file, contains one test to run all the test cases of the Smoke Suite in Google Chrome browser and the second test to run all the test cases of the Sanity Suite in Firefox. Both browser instances are start same time and execute in parallel. TestSuiteClassSanity and TestSuiteClassSmoke classes extends AutomationBase class to get the driver instances for execution. Following is the actual implementation of AutomationBase class:

@BeforeClass()
@Parameters({“browserName”})
public void SetUp(String browserName) throws IOException, InterruptedException
{
try {
if(browserName.equalsIgnoreCase(“chrome”)){
// implement code to start chrome driver session
}
else if(browserName.equalsIgnoreCase(“firefox”)){
// implement code to start firefox driver session
}
}catch (Exception e) {
e.printStackTrace();
}
}

Parallel Execution in Selenium C# Automation:

      In case of Selenium C#, there is no direct capability like TestNG to achieve the parallel execution of test cases in different instances of browsers. I used NUnit attributes just above in all test classes and that test class extends AutomationBase class. Used following NUnit attributes:

  • [TestFixture(“chrome”)]
  • [TestFixture(“firefox”)]
  • [Parallelizable]

        Added a parameterized constructor (the parameter should be browserName) and call StartBrowser(browserName) method inside the constructor. StartBrowser (browserName) method is implemented in AutomationBase class. Following is the sample implementation that I have done in the test class:

using NUnit.Framework;
namespace com.test.testcases
{
[TestFixture(“chrome”)]
[TestFixture(“firefox”)]
[Parallelizable]
public class TestModuleClass: AutomationBase
{
public TestModuleClass(string browserName)
{
StartBrowser(browserName);
}

[Test, Order(1)]
public void TC_001_SampleTest()
{
//Your test steps
}
}
}

    In AutomationBase class, I have added new method StartBrowser(String browserName) to identify the requested browser for execution and implemented the logic to drive chrome and firefox drivers. Following is the implementation of StartBrowser,

public IWebDriver StartBrowser(String browserName)
{
try
{
if (browserName.ToLower().Equals(“”))
{
throw (new Exception(“BROWSER_NAME is not specified”));
}
if (browserName.ToLower().Equals(“chrome”))
{
// implement code to start chrome driver session
}
if (browserName.ToLower().Equals(“firefox”))
{
// implement code to start firefox driver session
}
}
catch (Exception e)
{
throw (e);
}
return driver;
}

     You can try above mechanisms of parallel executions in automation for both Selenium Java and Selenium C#.

make it perfect !

Extent Reports in Automation – TestNG

maxresdefault

     TestNG itself, providing an HTML report in test-output folder. I had a thought of building custom report for automation, after that I built one PDF customized report using iText PDF Java library and took more effort to build it. Later I thought to build a custom beautiful high rich HTML reports with minimum effort; that time Extent Report comes into my mind. Here, I would like to share the details on the integration and implementation of Extent Report utility in Automation test classes that built with TestNG.

Prerequisites to Generate Extent Reports:

  1. Java should be installed and setup Java
  2. TestNG maven dependency should be available
  3. Selenium maven dependency should be available
  4. Extent Report Maven dependency should be available
  5. extent-config.xml – It allows to configure HTML Report

Steps To Generate Extent Reports:

  1. Firstly, create a maven project.
  2. Add TestNG dependency to pom.xml of project in eclipse.
  3. Add selenium-java and selenium-server dependencies to pom.xml of  project in eclipse
  4. Extent Report Maven dependency (version: 2.41.2) should available and added in pom.xml project in eclipse.
  5. Create a java class say ‘SeleniumExtentReport’ and add following code to it,

package com.journeyofquality.test;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class SeleniumExtentReport {
ExtentReports extentReport;
ExtentTest extentTest;
WebDriver driver;

@BeforeSuite
public void beforeSuite() {
//In before suite we are creating HTML report template, adding basic information to it and load the extent-config.xml file

extentReport = new ExtentReports(System.getProperty(“user.dir”) + “/test-output/SeleniumExtentReport.html”,
true);
extentReport.addSystemInfo(“Host Name”, “JourneyofQuality”).addSystemInfo(“Environment”, “Automation Testing”)
.addSystemInfo(“User Name”, “Sanoj”);
extentReport.loadConfig(new File(System.getProperty(“user.dir”) + “\\extent-config.xml”));
}

@BeforeClass
public void beforeClass() {
System.setProperty(“webdriver.chrome.driver”, );
driver = new ChromeDriver();
}

@BeforeMethod
public void beforeMethod(Method method) {
//In before method we are collecting the current running test case name
String className = this.getClass().getSimpleName();
extentTest = extentReport.startTest(className + “-” + method.getName());
}

@Test
public void passTest() {
Assert.assertTrue(true);
}

@Test
public void failTest() {
driver.get(“http://google.com&#8221;);
Assert.assertEquals(driver.getTitle().toString(), “Journey”);
}

@Test
public void skipTest() {
throw new SkipException(“Skipping – This is not ready for testing “);
}

@AfterMethod
public void getResult(ITestResult result, Method method) throws Exception {
//In after method we are collecting the test execution status and based on that the information writing to HTML report
if (result.getStatus() == ITestResult.FAILURE) {
extentTest.log(LogStatus.FAIL, “Test Case Failed is ” + result.getName());
String screenshotPath = SeleniumExtentReport.capture(driver, result.getName());
extentTest.log(LogStatus.FAIL, “Error Details :- \n” + result.getThrowable().getMessage()
+ extentTest.addScreenCapture(screenshotPath));
}
if (result.getStatus() == ITestResult.SKIP) {
extentTest.log(LogStatus.SKIP, “Test Case Skipped is ” + result.getName());
}
if (result.getStatus() == ITestResult.SUCCESS) {
extentTest.log(LogStatus.PASS, “Test Case Passed is ” + result.getName());
}
}

@AfterSuite
public void endReport() {
//In after suite stopping the object of ExtentReports and ExtentTest
extentReport.endTest(extentTest);
extentReport.flush();
driver.quit();
}

/**

* To Capture the Screenshot and return the file path to extent report fail
* cases
*
* @param driver
* @param screenShotName
* @return
* @throws IOException
*/
private static String capture(WebDriver driver, String screenShotName) throws IOException {
String dest = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(“dd-mm-yyyy h-m-s”);
Date date = new Date();
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
dest = System.getProperty(“user.dir”) + “\\ErrorScreenshots\\” + screenShotName + dateFormat.format(date)
+ “.png”;
File destination = new File(dest);
FileUtils.copyFile(source, destination);
} catch (Exception e) {
e.getMessage();
System.out.println(e.getMessage());
}
return dest;
}
}

Code Explanation:

  • Imported two classes ExtentReports and ExtentTest.
    • ExtentReportsBy using this class we set the path where our reports need to generate.
    • ExtentTestBy using this class we could generate the logs in the report.
  • Took three methods with @Test annotation such as passTest, failTest and skipTest and a method beforeSuite with @BeforeSuite annotation, beforeMethod with @BeforeMetod annotation, another method getResult with @AfterMethod annotation and finally, endReport with @AfterSuite annotation.
  • Here my intention is to generate a report with all the three types of results such as Pass, Fail and Skip.
  • Used object of ExtentReports class (i.e., extentReport) in the beforeSuite method which was assigned to @BeforeSuite annotation to generate the HTML report in the required path.
  • Used object of ExtentTest class (i.e., extentTest) in beforeMethod to get the name of currently executing test case. Also, extentTest object used in getResult method which was assigned to @AfterMethod annotation to write logs in the report.
  • Used ITestResult class in the @AfterMethod to describe the result of a test.

extent-config.xml: 

     By using this external XML file (extent-config.xml), we could change the details such as Report Theme (either standard or dark), Report Title, Document Title etc., We use extent object and use loadConfig() method to load this XML file.

<?xml version=”1.0″ encoding=”UTF-8″?>
<extentreports>
<configuration>
<!– report theme –>
<!– standard, dark –>
<theme>standard</theme>
<!– document encoding –>
<!– defaults to UTF-8 –>
<encoding>UTF-8</encoding>
<!– protocol for script and stylesheets –>
<!– defaults to https –>
<protocol>https</protocol>
<!– title of the document –>
<documentTitle>JourneyOfQuality</documentTitle>
<!– report name – displayed at top-nav –>
<reportName>JourneyOfQuality</reportName>
<!– report headline – displayed at top-nav, after reportHeadline –>
<reportHeadline>Automation Report</reportHeadline>
<!– global date format override –>
<!– defaults to yyyy-MM-dd –>
<dateFormat>yyyy-MM-dd</dateFormat>
<!– global time format override –>
<!– defaults to HH:mm:ss –>
<timeFormat>HH:mm:ss</timeFormat>
<!– default style override –>
<theme></theme>
<!– custom javascript –>
<scripts>
<![CDATA[
$(document).ready(function() {
$(“.logo-content”).hide();
$(“.logo-container”).html(“JourneyOfQuality”);
$(‘#parentNodes’).prop(“checked”, true).click();
$(‘#test-count-setting > div.modal-footer > a’)[0].click();
});
]]>
</scripts>
<!– custom styles –>
<styles>
<![CDATA[
]]>
</styles>
</configuration>
</extentreports>

     Refresh the project after execution of above SeleniumExtentReport.java file. You could find an HTML file named “SeleniumExtentReport.html” in your test-output folder. Copy the location of the “SeleniumExtentReport.html” file and open it by using any browser. You could see beautiful high rich HTML reports as shown below.

Capture

Capture1

Try to implement the above mentioned custom report mechanism in your Selenium – Java -TestNG and enjoy automation.

make it perfect !

Selenium Automation using C# (NUnit)

DYLSVhtWAAA5qn9seleniumwithC

     In the previous post, we discussed about Selenium C# and MSTest framework. Another day, I got an opportunity to write selenium automation using C# language and NUnit framework. Prior to scripting, I started the configuration from the scratch to achieve my selenium scripting using C# and NUnit. Here I would like to share my experience with configuration and scripting part,

Steps for install and configure Visual Studio:

Step 1: Navigate to the URL https://www.visualstudio.com/downloads/ and Click on the ‘Free download’ button displayed on Visual Studio Community 2017 tab.
Step 2: Open the exe downloaded. Click on ‘Yes’ if asked for Admin Rights.
Step 3: A popup will appear. Click on ‘Continue’ button.
Step 4: In the next screen, select the check-boxes for

  • Universal Windows Platform development
  • .Net desktop development

Click on ‘Install.’ Wait for installation of each component to complete. Files are 16GB in size and will take time.
Step 5: A pop up will be displayed. Click on ‘Restart’ button (if required).
Step 6: Once the machine is restarted, search for “Visual Studio 2017” on the start menu and click on the search result. In the next screen, Click on “Not now, maybe later” link if you do not have an existing account.
Step 7: In the next screen,

  • Select color theme of your liking
  • Click the button “Start Visual Studio'”

Step 8: Visual Studio ‘Get Started’ screen will appear.

Set up Visual Studio with Selenium WebDriver:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “Selenium”.
  2. Select the first search result “Selenium.WebDriver”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click on ‘Install’.
  6. Select second search result “Selenium.Support”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Set up Visual Studio with NUnit Framework:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “NUnit”
  2. Select the search result “NUnit”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click Install.
  6. In the same window, select search result “NUnit3TestAdapter”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Create a new project in Visual Studio:

Step 1: In the File Menu, Click New > Project
Step 2: In the next screen,

  1. Select the option ‘Visual C#’
  2. Click on Console App (.Net Framework)
  3. Enter project name.
  4. Click OK

Step 3: You will be able to see the created project.

     Now the configurations and project is ready, next you can add one C# class file to project and start writing your first script for automation as below. I used this class file to start my C# scripting for selenium automation,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using System.Threading;

namespace seleniumTestProject
{
[TestFixture]
public class SeleniumTest
{
public IWebDriver driver; //declare the driver object

[OneTimeSetUp]
public void BeforeClass()
{
driver = new ChromeDriver(“path_to_chromedriver.exe”); //initialize the ChromeDriver instance
driver.Url = “https://www.google.co.in/&#8221;; //load application URL
}

[SetUp]
public void BeforeTest()
{
//You can write any precondition to perform prior to each test cases
}

[Test]
public void GoogleSearchTest()
{
driver.FindElement(By.Id(“lst-ib”)).SendKeys(“Journey of Quality”);
}

[TearDown]
public void AfterTest()
{
driver.Close();
}

[OneTimeTearDown]
public void AfterClass()
{
driver.Quit();
}
}
}

     Try the above configuration and scripting using C# for Selenium Automation from your end. I recommend everyone to use NUnit framework than MSTest framework for Selenium C# scripting. NUnit provides straight-froward scripting when use their annotations. In case of MSTest, we must declare the method as static and should possess one parameter when use [AssemblyInitialize] or [ClassInitialize]. In case of NUnit, no need to declare the method as static when uses [OneTimeSetUp] or [SetUp].

make it perfect !

 

Selenium Automation using C# (MSTest)

downloadseleniumwithC

     One day, I got an opportunity to write selenium automation using C# language and MSTest framework. Prior to scripting, I started the configuration from the scratch to achieve my selenium scripting using C# and MSTest. Here I would like to share my experience with configuration and scripting part,

Steps for install and configure Visual Studio:

Step 1: Navigate to the URL https://www.visualstudio.com/downloads/ and Click on the ‘Free download’ button displayed on Visual Studio Community 2017 tab.
Step 2: Open the exe downloaded. Click on ‘Yes’ if asked for Admin Rights.
Step 3: A popup will appear. Click on ‘Continue’ button.
Step 4: In the next screen, select the check-boxes for

  • Universal Windows Platform development
  • .Net desktop development

Click on ‘Install.’ Wait for installation of each component to complete. Files are 16GB in size and will take time.
Step 5: A pop up will be displayed. Click on ‘Restart’ button (if required).
Step 6: Once the machine is restarted, search for “Visual Studio 2017” on the start menu and click on the search result. In the next screen, Click on “Not now, maybe later” link if you do not have an existing account.
Step 7: In the next screen,

  • Select color theme of your liking
  • Click the button “Start Visual Studio'”

Step 8: Visual Studio ‘Get Started’ screen will appear.

Set up Visual Studio with Selenium WebDriver:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “Selenium”.
  2. Select the first search result “Selenium.WebDriver”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click on ‘Install’.
  6. Select second search result “Selenium.Support”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Set up Visual Studio with MSTest Framework:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “MSTest”
  2. Select the search result “MSTest.TestFramework”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click Install.
  6. In the same window, select search result “MSTest.TestAdapter”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Create a new project in Visual Studio:

Step 1: In the File Menu, Click New > Project
Step 2: In the next screen,

  1. Select the option ‘Visual C#’
  2. Click on Console App (.Net Framework)
  3. Enter project name.
  4. Click OK

Step 3: You will be able to see the created project.

     Now the configurations and project is ready, next you can add one C# class file to project and start writing your first script for automation as below. I used this class file to start my C# scripting for selenium automation,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;

namespace seleniumTestProject
{
[TestClass]
public class SeleniumTest
{
public IWebDriver driver; //declare the driver object
[TestInitialize]
public void BeforeTest()
{
driver = new ChromeDriver(“path_to_chromedriver.exe”); //initialize the ChromeDriver instance
driver.Url = “https://www.google.co.in/&#8221;; //load application URL
}

[TestMethod]
public void GoogleSearchTest()
{
driver.FindElement(By.Id(“lst-ib”)).SendKeys(“Journey of Quality”);
}

[TestCleanup]
public void AfterTest()
{
driver.Close();
}
}
}

     Try the above configuration and scripting using C# for Selenium Automation from your end.

make it perfect !