Take Screenshots on Test Fails - java

I'm trying to take screenshots when a test fails and then add them to my report. Currently it takes a screenshot when it opens up the application again to do the extent.flush(); in my afterMethod().
My screenshot class is here:
public class CaptureScreenShot {
private static final DateFormat dateFormat = new SimpleDateFormat("yyy_MM_dd SSS");
public static String captureScreen(WebDriver driver, String screenName) throws IOException {
TakesScreenshot screen = (TakesScreenshot) driver;
File src = screen.getScreenshotAs(OutputType.FILE);
String dest = System.getProperty("user.dir") + "Test-ScreenShots" + screenName + ".png";
File target = new File(dest);
FileUtils.copyFile(src, target);
return dest;
}
public static String generateFileName(ITestResult results) {
Date date = new Date();
return results.getName() + "_" + dateFormat.format(date);
}
}
The report building class is here:
public class ExtentTestNGReportBuilder {
public static ExtentReports extent;
public static ThreadLocal<ExtentTest> parentTest = new ThreadLocal<>();
public static ThreadLocal<ExtentTest> test = new ThreadLocal<>();
private String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm").format(new Date());
#BeforeSuite
public void beforeSuite() {
extent = ExtentManager.createInstance("MobileCustomerCare " + fileName + ".html");
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("C:\\Users\\tom.cockram\\Documents");
extent.attachReporter(htmlReporter);
}
#BeforeClass
public synchronized void beforeClass() {
ExtentTest parent = extent.createTest(getClass().getName());
parentTest.set(parent);
}
#BeforeMethod
public synchronized void beforeMethod(Method method) {
ExtentTest child = parentTest.get().createNode(method.getName());
test.set(child);
}
#AfterMethod
public synchronized void afterMethod(ITestResult result) throws IOException {
AppiumDriver<MobileElement> driver = MetricellTest.setupTests();
String screenShot = CaptureScreenShot.captureScreen(driver, CaptureScreenShot.generateFileName(result));
if (result.getStatus() == ITestResult.FAILURE) {
test.get().log(Status.FAIL, result.getName());
test.get().log(Status.FAIL, result.getThrowable());
test.get().fail("Screen Shot : " + test.get().addScreenCaptureFromPath(screenShot));
test.get().fail(result.getThrowable());
} else if (result.getStatus() == ITestResult.SKIP) {
test.get().skip(result.getThrowable());
} else
test.get().pass("Test passed");
extent.flush();
}

I'm not sure what your question is, but as per my understanding you are just not able to attach the screenshot.Assuming you have to attach it in case of test failures only. Put it in the method onTestFailure.
For screenshots name to append the date and time:
public static String getCurrentDateAndTime(String format) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
LocalDateTime now = LocalDateTime.now();
return dtf.format(now).toString();
}

Related

Saving unique log for each test class using TestNG framework and Log4J

I have an automation project (Java, Maven with TestNG, log4j).
I am trying to create log file foreach test class (LoginTest would create LoginTest.log, HomeTest would create HomeTest.log , etc), I have implemeneted my own logger mechanism for this purpose but at the end of the run I am getting only the last class test log file (for the last test class that ran).
This is my logic:
public class TestLogger extends LoggerFormat {
private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of(EnvConf.getDefaultTimeZone());
private final ThreadLocal<Map<String, List<String>>> testsLogMap = new ThreadLocal<>();
public void info(ITestContext context, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.info(msg);
log(Level.INFO, context, msg);
}
public void error(ITestContext context, Throwable t, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.error(msg, t);
log(Level.ERROR, context, msg, t);
}
public void error(ITestContext context, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.error(msg);
log(Level.ERROR, context, msg);
}
public void warn(ITestContext context, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.warn(msg);
log(Level.WARN, context, msg);
}
public void warn(ITestContext context, Throwable t, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.warn(msg, t);
log(Level.WARN, context, msg, t);
}
public void debug(ITestContext context, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.debug(msg);
if (LoggerFactory.isDebug()) {
log(Level.DEBUG, context, msg);
}
}
public void debug(ITestContext context, Throwable t, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.debug(msg, t);
if (LoggerFactory.isDebug()) {
log(Level.DEBUG, context, msg, t);
}
}
private void log(Level level, ITestContext context, Object message, Throwable t) {
message = String.format("%s\n%s", message, throwableToString(t));
log(level, context, message);
}
private void log(Level level, ITestContext context, Object message) {
Map<String, List<String>> logsMap = getLogsMap();
if (!logsMap.containsKey(context.getName())) {
logsMap.put(context.getName(), new ArrayList<>());
}
logsMap.get(context.getName()).add(formatMsg(message, level));
if (level.toInt() != Level.DEBUG.toInt()) {
Reporter.log((String) message, 0);
}
}
private static String formatMsg(Object message, Level level) {
LocalDateTime dateTime = LocalDateTime.now(DEFAULT_ZONE_ID);
return String.format("[%s][%s]%s",
TIMESTAMP_FORMAT.format(dateTime),
level, message);
}
public List<String> getAndDeleteLogsByTest(String testName) {
return getLogsMap().remove(testName);
}
private Map<String, List<String>> getLogsMap() {
if (testsLogMap.get() == null) {
testsLogMap.set(new HashMap<>());
}
return testsLogMap.get();
}
private static String throwableToString(Throwable t) {
StringBuilder builder = new StringBuilder();
for (StackTraceElement traceElement : t.getStackTrace()) {
builder.append(traceElement.toString()).append('\n');
}
return builder.toString();
}
private static String handleFormatMsg(String message, Object... args) {
if (args.length == 0 && message.contains("%")) {
message = message.replaceAll("%", "%%");
}
return String.format(message, args);
}
}
this is my BaseTest Class:
#Listeners({NeoTestListener.class})
public class BaseTest {
private static final Browser BROWSER = Browser.valueOf(EnvConf.getProperty("ui.browser.type"));
private static final File SCREENSHOTS_FOLDER = new File(EnvConf.getProperty("test_output.screenshots.folder"));
// private static final File DOWNLOADS_FOLDER = new File(EnvConf.getProperty("workspace.tests.downloads"));
private static final File DOWNLOADS_FOLDER = new File(EnvConf.getProperty("test_output.logs.folder"));
private static final String ADMIN_USERNAME = EnvConf.getProperty("hackeruso.admin.user.email");
private static final String ADMIN_PASSWORD = EnvConf.getProperty("hackeruso.admin.user.password");
protected static DriverWrapper driver;
protected LoginPage loginPage;
protected Date testStartTime;
protected ITestContext context;
protected TopBar topBar;
protected final File testTempFolder;
static {
if (!SCREENSHOTS_FOLDER.exists()) {
FileUtil.createFolder(SCREENSHOTS_FOLDER, true);
}
if(!DOWNLOADS_FOLDER.exists()) {
FileUtil.createFolder(DOWNLOADS_FOLDER, false);
}
}
protected static String randSuffix(String prefix){
return prefix + "_" + String.valueOf(System.nanoTime()).substring(9);
}
public BaseTest() {
this.testTempFolder = new File(DOWNLOADS_FOLDER, randSuffix(getClass().getSimpleName()));
FileUtil.createFolder(testTempFolder, false);
// testTempFolder.deleteOnExit();
}
#BeforeClass
public final void baseSetup(ITestContext context) throws IOException {
this.context = context;
driver = DriverWrapper.open(BROWSER, DOWNLOADS_FOLDER);
loginPage = new LoginPage(driver);
info("<!!! '%s' START !!!>" , context.getName());
testStartTime = new Date();
this.context.setAttribute("test_start_time", testStartTime);
info("testStartTime=[%s]" , testStartTime);
}
private void printBrowserLog() {
List<LogEntry> serverLogLines = driver.manage().logs().get(LogType.BROWSER).getAll();
if (serverLogLines.size() > 0) {
Log.i("<---------Browser [SERVER] log start--------->");
for (LogEntry entry : serverLogLines) {
Log.e(entry.toString());
}
Log.i("<---------Browser [SERVER] log end------------>");
}
}
#AfterClass
public final void baseTeardown(ITestContext context) {
Date testEndTime = new Date();
if (driver != null) {
printBrowserLog();
driver.quit();
}
info("<!!! '%s' END !!!>" , context.getName());
info("testEndTime=[%s]" , testEndTime);
}
public static DriverWrapper getDriver() {
return driver;
}
protected void info(String message , Object...args){
TESTS_LOG.info(context , message , args);
}
public void error(Throwable t , String messageFormat , Object...args) {
TESTS_LOG.error(context , t , messageFormat , args);
}
public void error(String messageFormat , Object...args) {
TESTS_LOG.error(context , messageFormat , args);
}
protected void warn(String messageFormat , Object...args) {
TESTS_LOG.warn(context , messageFormat , args);
}
public void warn(Throwable t ,String messageFormat , Object...args) {
TESTS_LOG.warn(context , t , messageFormat , args);
}
protected void debug(String messageFormat , Object...args) {
TESTS_LOG.debug(context , messageFormat , args);
}
public void debug(Throwable t , String messageFormat , Object...args) {
TESTS_LOG.debug(context , t , messageFormat , args);
}
}
And this is my listener:
public class NeoTestListener implements ITestListener {
private final File SCREENSHOTS_FOLDER = new File(EnvConf.getProperty("test_output.screenshots.folder"));
private static final SimpleDateFormat FOLDER_NAME_FORMAT = new SimpleDateFormat("dd_MM_HH_mm_ss");
private static final SimpleDateFormat LOG_NAME_FORMAT = new SimpleDateFormat("dd_MM_HH_mm_ss");
private static final File TESTS_LOGS_FOLDER = new File(EnvConf.getProperty("test_output.logs.folder"));
static {
if (!TESTS_LOGS_FOLDER.exists()) {
FileUtil.createFolder(TESTS_LOGS_FOLDER, true);
}
}
private static String getTestMethodName(ITestResult iTestResult){
return iTestResult.getMethod().getConstructorOrMethod().getName();
}
#Attachment
public byte[] saveFailureScreenShot(DriverWrapper driver){
return driver.getScreenshotAsByte();
}
#Attachment(value = "{0}", type = "text/plain")
public static String saveTextLog(String message){
return message;
}
#Override
public void onStart(ITestContext context) {
context.setAttribute("WebDriver", getDriver());
}
#Override
public void onFinish(ITestContext context) {
}
#Override
public void onTestStart(ITestResult result) {
TESTS_LOG.info(result.getName() +" " + result.getTestClass() );
// TESTS_LOG.info("[Test: " + getTestClassName(result.getTestContext())+ " Started]");
}
#Override
public void onTestSuccess(ITestResult result) {
}
#Override
public void onTestFailure(ITestResult result) {
TESTS_LOG.error(String.format("I am in onTestFailure method:=[%s] failed", getTestMethodName(result)));
Object testClass = result.getInstance();
DriverWrapper driver = getDriver();
takeScreenshot(getTestMethodName(result));
//Allure ScreenShot and SaveTestLog
TESTS_LOG.info(String.format("Screenshot for class=[%s], method=[%s]", getTestClassName(result.getTestContext()), getTestMethodName(result)));
saveFailureScreenShot(driver);
try {
saveLogTextFile(result);
} catch (IOException e) {
e.printStackTrace();
}
saveTextLog(getTestMethodName(result) + " failed and screenshot taken!");
}
#Attachment
private byte[] saveLogTextFile(ITestResult result) throws IOException {
return saveToLogFile(result.getTestContext());
}
#Override
public void onTestSkipped(ITestResult result) {
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
#Override
public void onTestFailedWithTimeout(ITestResult result) {
}
private void takeScreenshot(String filePrefix){
File dest = new File(SCREENSHOTS_FOLDER , filePrefix + "_" + FOLDER_NAME_FORMAT.format(new Date()) + ".png");
takeScreenshot(dest, getDriver());
}
private void takeScreenshot(File destFile, DriverWrapper driver){
File scrFile = driver.getScreenshotAsFile();
Path src = Paths.get(scrFile.toURI());
Path dest = Paths.get(destFile.toURI());
try {
Files.copy(src, dest , StandardCopyOption.REPLACE_EXISTING);
TESTS_LOG.info("[[ATTACHMENT|" + destFile.getAbsolutePath() + "]]");
} catch (IOException e) {
TESTS_LOG.error("Failed to save screen shot at file: " + destFile.getName());
TESTS_LOG.error(e.getMessage());
}
}
private byte[] saveToLogFile(ITestContext context) throws IOException {
File logFile = createLogFile(context);
boolean created = FileUtil.createNewFile(logFile);
if(created){
List<String> testLogLines = TESTS_LOG.getAndDeleteLogsByTest(context.getName());
if(testLogLines == null){
TESTS_LOG.error(context, "test=[%s] don't have any log lines!" , context.getName());
}else{
FileUtil.writeToFile(logFile.getAbsolutePath(), testLogLines);
}
}else{
TESTS_LOG.error(context, " failed to create test log file=[%s]", logFile.getAbsolutePath());
}
return FileUtils.readFileToByteArray(logFile);
}
private static File createLogFile(ITestContext context){
return new File(TESTS_LOGS_FOLDER, String.format("%s_%s.log",getTestClassName(context), LOG_NAME_FORMAT.format(context.getStartDate())));
}
private static String getTestClassName(ITestContext context){
return context.getAllTestMethods()[0].getInstance().getClass().getSimpleName();
}
}
This is a sample of class test in my environment:
public class ForgotPasswordTest extends BaseTest {
private String verifyEmailURL = "";
private static final String AUTOMATION_EMAIL= EnvConf.getProperty("automation.email.user");
private static final String AUTOMATION_EMAIL_PASSWORD=EnvConf.getProperty("automation.email.password");
private static final String AUTOMATION_WEBAPP_USER = "AUTOMATION_TESTER";
private ResetPasswordPage rpp;
private final static String NEW_PASSWORD = "1Qaz2wsx3edc";
private final static String ENVIRONMENT_BASE_URL = EnvConf.getProperty("base.url");
#BeforeClass
public void setup() {
topBar = new TopBar(driver);
rpp = new ResetPasswordPage(driver);
}
#Test(priority = 1)
public void navigateToLoginPage(){
loginPage.navigateAndVerify();
}
#Test(priority=2)
public void sendChangePasswordInstructions() {
ForgotPasswordPage fpp = loginPage.clickAndVerifyForgotPasswordButtonAction();
fpp.sendForgotPasswordInstructions(AUTOMATION_EMAIL);
Assert.assertTrue(loginPage.getForgotMsgAlertText().contains("Thank You, An Email Has Been Send"));
info("Sending forget password instructions phase is successful!");
}
#Test(priority=3)
public void verifyEmail(){
verifyEmailURL = "";
String regex = "href=\"([^\"]*)" ;
String from = "<SOME_URL>";
String subject = getSubject();
String msg = MailHelper.getMessagesFromGmail( AUTOMATION_EMAIL, AUTOMATION_EMAIL_PASSWORD, from, subject, testStartTime);
Pattern linkPattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher pageMatcher = linkPattern.matcher(msg);
while (pageMatcher.find()) {
if (pageMatcher.group(1).contains("reset-password")) {
verifyEmailURL = pageMatcher.group(1);
verifyEmailURL = ENVIRONMENT_BASE_URL.concat("/").concat(verifyEmailURL.split("/")[3]);
info("Verify URL: " + verifyEmailURL);
}
}
info("Verifying email address is successful!");
}
#Test(priority = 4)
public void navigateToResetPasswordScreen(){
navigateTo(verifyEmailURL);
}
#Test(priority=5)
public void connectToUpdateNewPassword() {
rpp.changeNewPassword(NEW_PASSWORD);
info("Changing password is successful!");
}
#Test(priority=6)
public void verifyPasswordChanged() {
signIn(AUTOMATION_EMAIL, NEW_PASSWORD, true);
assertTrue(topBar.verifyExistenceTopBarNavigationItem(TopRightNavBarItem.SUPPORT));
info(String.format("Password for user=[%s] changed successfully", AUTOMATION_WEBAPP_USER));
}
private String getSubject(){
return "Reset Password";
}
}
Every time I run my program using mvn clean test I am not able to save the log for each test class it always saves me the last test class that was run and other log files not saved as expected.
what is missing ? I tried to search for a solution and tried various actions but I did not get the expected result.
The Maven Surefire plugin has the parameter <redirectTestOutputToFile> which creates the following files in target/surefire-reports in addition with a test project here:
igb.so.so65465538.FirstTest-output.txt:
println(): First test...
22:32:25.537 [main] INFO igb.so.so65465538.FirstTest - log.info(): First test...
igb.so.so65465538.SecondTest-output.txt:
println(): Second test...
22:32:25.561 [main] INFO igb.so.so65465538.SecondTest - log.info(): Second test...

Parallel execution does not work in Selenium Page object Model

I'm doing automation with Selenium - Page object Model & TestNG & Java. I have 2 testcases in 2 class files and i want to run all my tests in parallel
I passed driver and test object to all my pages.
When running my testng.xml with parallel="classes" two browser windows opened and only in one window, tests is running. The other window is closed. Eclipse showed me Null pointer exception.
Answer:
Later i understood that this is about usage of static in ExtentReport initialization. I corrected my code in reporter class.
Test Class-1:
public class CreateXCase extends SeleniumBase
{
#BeforeTest(alwaysRun=true )
public void setTestDetails()
{
author = System.getProperty("user.name");
testcaseName="Verify that X case is successfully created";
testcaseDec = "Create X Case";
category="Regression";
}
#Test(priority=2,groups = {"Regression"})
public void createCaseWithNewParticipants() throws Exception
{
new LoginPage(driver, test).login().quickNavigation_CASE()
.navigateToCreateCase().enterApplicantInformation()
.navigateToCaseSection().createCase();
}
}
Test Class-2:
public class CreateYcase extends SeleniumBase
{
#BeforeTest(alwaysRun=true )
public void setTestDetails()
{
author = System.getProperty("user.name");
testcaseName="Verify that Y case is successfully created";
testcaseDec = "Create Y Case";
category="Regression";
}
#Test(priority=1,groups = {"Regression"})
public void createCaseWithNewParticipants() throws Exception
{
new LoginPage(driver,test).login().quickNavigation_CASE()
.navigateToCreateCase().enterApplicantInformation()
.navigateToCaseSection().createCase();
}
SeleniumBase.java:
public class SeleniumBase extends Reporter implements Browser, Element
{
public static WebDriverWait wait;
#BeforeMethod(alwaysRun=true )
public void configureAndLaunch() throws IOException
{
driver = startApp(ReadPropertyFile.get("Browser"), ReadPropertyFile.get("URL"));
}
#Override
#AfterMethod (alwaysRun=true )
public void closeBrowser()
{
driver.quit();
}
#Override
public RemoteWebDriver startApp(String browser, String url)
{
try
{
if (browser.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("firefox"))
{
System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver.exe");
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("ie"))
{
System.setProperty("webdriver.ie.driver", "./drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.get(url);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
catch (Exception e)
{
int a = e.toString().indexOf("Exception:");
String str = e.toString().substring(0, a + 30);
System.out.println(str + "Exception captured");
System.err.println("The Browser Could not be Launched. Hence Failed");
}
finally
{
takeSnap();
}
return null;
}
Reporter.java:
public abstract class Reporter {
public RemoteWebDriver driver;
public ExtentHtmlReporter reporter;
public static ExtentReports extent;
public ExtentTest test;
public String testcaseName, testcaseDec, author ;
public String category="";
public static String excelFileName;
public static String extentreportpath;
#BeforeSuite (alwaysRun=true )
public void startReport(ITestContext c) throws IOException
{
String reportName=this.getClass().getName().substring(29, 33).toUpperCase() +" Screen Test Report";
String screenName=this.getClass().getName().substring(29, 33).toUpperCase() +" Tests";
String rptName="h5{font-size: 0px;}h5::after{content:\'"+screenName+"\';font-size: 1.64rem; line-height: 110%;margin: 0.82rem 0 0.656rem 0;}";
String suiteName = c.getCurrentXmlTest().getSuite().getName();
if (suiteName.contains("Default suite")||suiteName.contains("Failed suite"))
suiteName ="";
extentreportpath="./reports/"+suiteName+"Report.html";
reporter = new ExtentHtmlReporter(extentreportpath);
reporter.setAppendExisting(true);
extent = new ExtentReports();
extent.attachReporter(reporter);
reporter.loadXMLConfig(new File("./Resources/extent-config.xml"));
reporter.config().setTheme(Theme.DARK);
reporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
reporter.config().setReportName(reportName);
reporter.config().setCSS(rptName);
}
#BeforeClass(alwaysRun=true )
public ExtentTest report()
{
test = extent.createTest(testcaseName, testcaseDec);
test.assignAuthor(author);
return test;
}
public abstract long takeSnap();
public void reportStep(String desc,String status,boolean bSnap)
{
MediaEntityModelProvider img=null;
if(bSnap && !status.equalsIgnoreCase("INFO"))
{
long snapNumber=100000L;
snapNumber=takeSnap();
try
{
img=MediaEntityBuilder.createScreenCaptureFromPath("./../reports/images/"+snapNumber+".jpg").build();
}
catch(IOException e)
{
}
}
if(status.equalsIgnoreCase("pass"))
{
//test.pass(desc,img);
test.log(Status.PASS, desc, img);
}
else if(status.equalsIgnoreCase("fail"))
{
//test.fail(desc,img);
test.log(Status.FAIL, desc, img);
}
else if(status.equalsIgnoreCase("INFO"))
{
//test.pass(desc);
test.log(Status.INFO, desc,img);
}
}
public void reportStep(String desc,String status)
{
reportStep(desc,status,true);
}
#AfterSuite (alwaysRun=true )
public void stopReport() throws Exception
{
extent.flush();
}
}
Making the ExtentReport variable 'extent' as static solved my issue.
Eg: public static ExtentReports extent;
I modified the code in my question also.
Since i have only one #Test in a class, parallel="methods" is of no use in my case.

Adding base64 screenshot to extendreport 3.1.5 is unsucessful

I want to take base64 screenshot for all the passed and failed screenshots with testNG, below is my code.
private static ExtentReports extent;
private static Platform platform;
private static String reportFileName = "ExtentReports-Version3-Test-Automaton-Report.html";
private static String macPath = System.getProperty("user.dir")+ "/TestReport";
private static String windowsPath = System.getProperty("user.dir")+ "\TestReport";
private static String macReportFileLoc = macPath + "/" + reportFileName;
private static String winReportFileLoc = windowsPath + "\" + reportFileName;
public static ExtentReports getInstance() {
if (extent == null)
createInstance();
return extent;
}
//Create an extent report instance
public static ExtentReports createInstance() {
platform = getCurrentPlatform();
String fileName = getReportFileLocation(platform);
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName);
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(fileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(fileName);
extent = new ExtentReports();
extent.setSystemInfo("Author", "Gladson Antony");
extent.setSystemInfo("Browser", Browser);
extent.setSystemInfo("OS", OSName);
extent.setSystemInfo("OS Version", OSVersion);
extent.setSystemInfo("OS Architecture", OSArchitecture);
extent.setSystemInfo("OS Bit", OSBit);
extent.setSystemInfo("JAVA Version",System.getProperty("java.version"));
extent.attachReporter(htmlReporter);
return extent;
}
//Select the extent report file location based on platform
private static String getReportFileLocation (Platform platform) {
String reportFileLocation = null;
switch (platform) {
case MAC:
reportFileLocation = macReportFileLoc;
createReportPath(macPath);
System.out.println("ExtentReport Path for MAC: " + macPath + "\n");
break;
case WINDOWS:
reportFileLocation = winReportFileLoc;
createReportPath(windowsPath);
System.out.println("ExtentReport Path for WINDOWS: " + windowsPath + "\n");
break;
default:
System.out.println("ExtentReport path has not been set! There is a problem!\n");
break;
}
return reportFileLocation;
}
//Create the report path if it does not exist
private static void createReportPath (String path) {
File testDirectory = new File(path);
if (!testDirectory.exists()) {
if (testDirectory.mkdir()) {
System.out.println("Directory: " + path + " is created!" );
} else {
System.out.println("Failed to create directory: " + path);
}
} else {
System.out.println("Directory already exists: " + path);
}
}
//Get current platform
private static Platform getCurrentPlatform () {
if (platform == null) {
String operSys = System.getProperty("os.name").toLowerCase();
if (operSys.contains("win")) {
platform = Platform.WINDOWS;
} else if (operSys.contains("nix") || operSys.contains("nux")
|| operSys.contains("aix")) {
platform = Platform.LINUX;
} else if (operSys.contains("mac")) {
platform = Platform.MAC;
}
}
return platform;
}
Below is my listerner class where I take screenshot for each passed test case using Base64 format.
private static ExtentReports extent = ExtentManager.createInstance();
private static ThreadLocal test = new ThreadLocal();
public synchronized void onStart(ITestContext context) {
System.out.println("Test Suite started!");
}
public synchronized void onFinish(ITestContext context) {
System.out.println(("Test Suite is ending!"));
extent.flush();
}
public synchronized void onTestStart(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " started!"));
ExtentTest extentTest = extent.createTest(result.getMethod().getMethodName(),
result.getMethod().getDescription());
test.set(extentTest);
}
public synchronized void onTestSuccess(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " passed!"));
test.get().pass("Test passed");
try {
test.get().pass(result.getTestClass().getName() + "." + result.getMethod().getMethodName(),
MediaEntityBuilder.createScreenCaptureFromBase64String(TestBase.addScreenshot()).build());
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void onTestFailure(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " failed!"));
test.get().fail(result.getThrowable());
try {
test.get().fail(result.getTestClass().getName() + "." + result.getMethod().getMethodName(),
MediaEntityBuilder.createScreenCaptureFromBase64String(TestBase.addScreenshot()).build());
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void onTestSkipped(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " skipped!"));
test.get().skip(result.getThrowable());
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
System.out.println(("onTestFailedButWithinSuccessPercentage for " + result.getMethod().getMethodName()));
}
Thanks in advance for the favour!!

how to store or display extended report in eclips after refreshing projects and simultanously at mentioned drive

Simultaneously, I want to display a extended report on eclipse window(which is come after refreshing project)and mentioned driver(eg. d:/project name/...) using selenium webdriver
This is my Extend report #BeforeTest method
#BeforeTest
public void setUp1() {
// where we need to generate the report
String fileName = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
htmlReporter = new ExtentHtmlReporter("C:/xampp/htdocs/Automation_report/files/summerrentals/summerrentals("+fileName+").html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// Set our document title, theme etc..
htmlReporter.config().setDocumentTitle("Testing");
htmlReporter.config().setReportName("Testing");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
Its after Medhod for attached screenshot
#AfterMethod
public void setTestResult(ITestResult result) throws IOException {
String screenShot = CaptureScreenShot.captureScreen(wd, CaptureScreenShot.generateFileName(result));
if (result.getStatus() == ITestResult.FAILURE) {
test.log(Status.FAIL, result.getName());
test.log(Status.FAIL,result.getThrowable());
test.fail("Screen Shot : " + test.addScreenCaptureFromPath(screenShot));
} else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(Status.PASS, result.getName());
test.pass("Screen Shot : " + test.addScreenCaptureFromPath(screenShot));
} else if (result.getStatus() == ITestResult.SKIP) {
test.skip("Test Case : " + result.getName() + " has been skipped");
}
extent.flush();
wd.quit();
}
This is my CaptureScreenShot class for taking screenshot
public class CaptureScreenShot {
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd SSS");
public static String captureScreen(WebDriver driver, String screenName) throws IOException{
TakesScreenshot screen = (TakesScreenshot) driver;
File src = screen.getScreenshotAs(OutputType.FILE);
String dest ="C:/xampp//htdocs/Automation_report/Test-ScreenShots"+screenName+".png";
File target = new File(dest);
FileUtils.copyFile(src, target);
return dest;
}
public static String generateFileName(ITestResult result){
Date date = new Date();
String fileName = result.getName()+ "_" + dateFormat.format(date);
return fileName;
}
}
Hope It will help you
May be you want the report to be created in the drive/folder d:/project name/...
// start reporters
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("d://testproject/extent.html");
// create ExtentReports and attach reporter(s)
ExtentReports extent = new ExtentReports();
extent.attachReporter(htmlReporter);
This will create the extent report in the folder/drive d://testproject. I have assumed the project name is testproject here.

Extent Reports: Logs are Getting Appended on to a Single Test Case in the Report

i am Unable to Have separate Logs/entries for Different Test Cases. i.e Logs are Getting Appended on to a Single Test Case in the Extent Report generated.
Using Extent Report Version 2.41.1..
The Report Sample:
MY Code Goes like This:
Base Class of TestNG:
public static ExtentReports report;
public static ExtentTest logger;
#BeforeSuite
#Parameters({"BrowserName"})
public void beforeSuite(#Optional("Firefox") String BrowserName)
{
date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-yyyy");
String TodaysDate = ft.format(date);
prop = ResourceBundle.getBundle("DataFile");
Driver = Browser_Factory_FSQA_Class.getBrowser(BrowserName);
path = "//home//workspace//....//FSQA.ExtentReports//FSQA_ExtentReport_" + TodaysDate;
File f=new File(path);
if(!f.exists())
{
report = new ExtentReports(path);
}
}
#BeforeTest
#Parameters({"BrowserName"})
public void SetUpConfig(#Optional("Firefox") String BrowserName)
{
report = new ExtentReports(path, false,DisplayOrder.NEWEST_FIRST);
report.loadConfig(new File("//home//......//extent-config.xml"));
report.addSystemInfo("Build-Tag", prop.getString("Build-Tag"))
.addSystemInfo("Selenium ", prop.getString("SelVer"))
.assignProject(prop.getString("Application"))
.addSystemInfo("Envirnoment", prop.getString("AppEnvirnoment"))
.addSystemInfo("Extent", prop.getString("ExtRpVer"));
logger = report.startTest(this.getClass().getSimpleName());
logger.log(LogStatus.INFO,this.getClass().getSimpleName() +" will Run on "+ BrowserName +" Browser");
Driver.get(prop.getString("URL"));
Driver.manage().window().maximize();
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
}
#AfterMethod(alwaysRun=true)
public void afterMethod(ITestResult result) throws IOException
{
try
{
if(result.getStatus()==ITestResult.FAILURE)
{
String res = captureScreenshot(Driver, result.getName());
String image= logger.addScreenCapture(res);
System.out.println(image);
String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
logger.log(LogStatus.FAIL, TestCaseName + logger.addScreenCapture(res));
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success and Title Verified");
}
else if(result.getStatus()==ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
}
}
catch(Throwable t)
{
logger.log(LogStatus.ERROR,t.getMessage());
}
}
public String captureScreenshot(WebDriver Driver, String TestName)
{
try
{
date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("dd_MM_yyyy");
String TodaysDate = ft.format(date);
TakesScreenshot ts=(TakesScreenshot)Driver;
File source=ts.getScreenshotAs(OutputType.FILE);
Sc_Destination = prop.getString("SC_Dest")+TestName+"__"+TodaysDate+".png";
FileUtils.copyFile(source,new File(Sc_Destination));
logger.log(LogStatus.FAIL,image, "Title verification");*/
return Sc_Destination;
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
return Sc_Destination;
}
#AfterTest(alwaysRun=true)
public void AfterTest()
{
Driver.close();
report.endTest(logger);
report.flush();
}
#AfterSuite
public void AfterSuite()
{
report.close();
Driver.quit();
}
My Tests are Separate Clases which Extends this Base Class:
TC1:
public classTC1 extends BaseTestNG
{
#Test(groups = {"Happy_Path"} , description="TC1")
public void TestCase1() throws InterruptedException, Exception
{
logger.log(LogStatus.INFO, " Test Case2 Block Entered");
Thread.sleep(4000);
......
......
logger.log(LogStatus.INFO, "Assert Flag Received");
Thread.sleep(4000);
Assert.assertTrue(AssertFlag);
}
}
TC2:
public classTC2 extends BaseTestNG
{
#Test(groups = {"Happy_Path"} , description="TC2")
public void TestCase2() throws InterruptedException, Exception
{
logger.log(LogStatus.INFO, " Test Case2 Block Entered");
Thread.sleep(4000);
......
......
logger.log(LogStatus.INFO, "Assert Flag Received");
Thread.sleep(4000);
Assert.assertTrue(AssertFlag);
}
}
I am Using POM Classes along with TestNG and running the Testcases using testng.xml.
I am able to generate the Extent Report but unable to Differentiate Between TC1 & TC2 Logs i.e all test Case logs are getting appended to single TestCase as shown in the Above Screen Shot.
I want each Test Case Logs/Entry in separate rows in the Extent Reports.
Can Anyone please rectify the mistake in my code and help me out.
Thanks in Advance!!!
I think, you should initialize your logger in BeforeMethod and use report.flush() in AfterMethod. That may solve your problem.

Categories

Resources