extent report version 4 screenshot not generating - screenshot

I simply do not understand why this error occurs. Unable to generate the extent report and capture screenshot. I have appended the Test, AfterMethod & AfterTest and screenshot method. I want to capture screenshots under a different folder.
The error message i am getting is as following.
FAILED CONFIGURATION: #AfterMethod getReport([TestResult
name=checkTitle status=SUCCESS method=Google.checkTitle()[pri:0,
instance:Google#3224f60b] output={null}]) java.io.IOException: The
filename, directory name, or volume label syntax is incorrect hod.
Following is my selenium test code.
#Test
public void checkTitle() {
test = extent.createTest("Title Check test");
Actual_Title = driver.getTitle();
System.out.println(Actual_Title);
Assert.assertEquals(Actual_Title, Expected_Tite);
test.log(Status.PASS, "This Test is Passed!");
}
#AfterMethod
public void getReport(ITestResult result) throws IOException {
if (result.getStatus() == ITestResult.FAILURE) {
test.log(Status.FAIL,MarkupHelper.createLabel(result.getMethod().getMethodName(),ExtentColor.RED));
test.fail("TestFailed due to"+" "+result.getThrowable().getMessage());
String imagePath =Google.captureScreen(driver,result.getName());
test.addScreenCaptureFromPath(imagePath);
}
else if (result.getStatus() == ITestResult.SKIP) {
test.log(Status.SKIP,MarkupHelper.createLabel(result.getMethod().getMethodName(),ExtentColor.AMBER));
test.skip(result.getThrowable().getMessage());
} else {
test.log(Status.PASS,MarkupHelper.createLabel(result.getMethod().getMethodName(),ExtentColor.GREEN));
String imagePath =Google.captureScreen(driver, result.getName());
test.addScreenCaptureFromPath(imagePath);
}
}
#AfterTest
public void endTest() {
extent.flush();
driver.quit();
}
public static String captureScreen(WebDriver driver,String screenshotname)throws IOException {
String date = new SimpleDateFormat("MM-dd-yy,hh:mm:ss").format(new Date());
TakesScreenshot ts = (TakesScreenshot)driver;
File src= ts.getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir")+"/ScreenShots/"+screenshotname+date+".png";
File destination = new File(path);
FileUtils.copyFile(src, destination);
return path;
}

I could reproduce your problem.
For below code, I am getting exact same error as you mentioned.
String date = new SimpleDateFormat("MM-dd-yy,hh:mm:ss").format(new Date());
String screenshotname = "MyScreenshot";
String path = System.getProperty("user.dir")+"/test-
output/"+screenshotname+date+".png";
logger.info("In failedTCTakeScreenshot:: ******path***** " + path);
Error in log
[INFO ] 2020-07-28 23:09:52.281 [main] com.resources.BaseTest -In
failedTCTakeScreenshot:: ******path*****
E:\Automation\EclipseWorkspace\AutomationPrj/test-output/MyScreenshot07-28-
20,11:09:52.png
[ERROR] 2020-07-28 23:09:52.285 [main] com.resources.BaseTest -
BaseTest::failedTCTakeScreenshot::***In Catch Block *** java.io.IOException: The
filename, directory name, or volume label syntax is incorrect
Root cause Analysis:-
On analysis , I found that, you are storing your screenshot having name MM-dd-yy,hh:mm:ss date format in it. Windows does not accept any : or , in filename. You need to change your screenshotname so that it does not contains : , etc.
When I change DateFormat in my code to MM-dd-yyyy , I could successfully copy screenshot and no error thrown.
String date = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
String screenshotname = "MyScreenshot";
String path = System.getProperty("user.dir")+"/test-
output/"+screenshotname+date+".png";
logger.info("In failedTCTakeScreenshot:: ******path***** " + path);
Log :-
[INFO ] 2020-07-28 23:24:27.457 [main] com.resources.BaseTest - In
failedTCTakeScreenshot:: ******path*****
E:\Automation\EclipseWorkspace\AutomationPrj/test-output/MyScreenshot07-28-
2020.png
[INFO ] 2020-07-28 23:24:27.463 [main] com.resources.BaseTest - In
failedTCTakeScreenshot:: ******path destination*****
E:\Automation\EclipseWorkspace\AutomationPrj\test-output\MyScreenshot07-28-
2020.png
So you just need to change Screenshotname so that it should not contains special characters like ; and ,

Related

Null pointer exception while taking screenshot in selenium POM with extent report

A null pointer exception is thrown While trying to take screenshot when the scenario fails. I have an actions class in which i have defiled the capture screenshot method.
public static String capture(WebDriver driver) throws NullPointerException, IOException {
File scrFile;
scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File Dest = new File("D:\\Dinu\\SeleniumReports\\Test" + System.currentTimeMillis() + ".jpeg");
String filepath = Dest.getAbsolutePath();
org.openqa.selenium.io.FileHandler.copy(scrFile, Dest);
return filepath;
}
Extent reports are implemented using Itestlisterner interface. Below given code for which implements the screenshot method given:
public synchronized void onTestFailure(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " failed!"));
test.get().fail(result.getThrowable());
try {
String screenshotPath = actions.capture(driver);
test.get().addScreenCaptureFromPath(screenshotPath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And am getting the below error: Please help in resolving the same.
public static String getScreenhot(WebDriver driver, String screenshotName) throws Exception {
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
//after execution, you could see a folder "FailedTestsScreenshots" under src folder
String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/"+screenshotName+dateName+".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
return destination;
}
#AfterMethod
public void getResult(ITestResult result) throws IOException{
if(result.getStatus() == ITestResult.FAILURE){
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getName());
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getThrowable());
//To capture screenshot path and store the path of the screenshot in the string "screenshotPath"
//We do pass the path captured by this mehtod in to the extent reports using "logger.addScreenCapture" method.
String screenshotPath = ExtentReportsClass.getScreenshot(driver, result.getName());
//To add it in the extent report
logger.log(LogStatus.FAIL, logger.addScreenCapture(screenshotPath));
}else if(result.getStatus() == ITestResult.SKIP){
logger.log(LogStatus.SKIP, "Test Case Skipped is "+result.getName());
}
// ending test
//endTest(logger) : It ends the current test and prepares to create HTML report
extent.endTest(logger);
}

How to add screenshot using selenum in docker or linux env

I am tring to add screenshot, whenever my testcases are getting failed. However i have succeeded doing this in Windows env, but i am unable to achieve it in docker/linux env.
code for screenshot:
public void testFailure(Failure failure) throws java.lang.Exception
{
Random rand = new Random();
//Scenario scenario;
System.out.println("Execution Failure : ");
try {
//String screenshotName = failure.getTestHeader().toString();
int num = rand.nextInt(10000000);
String screenshotName = "Screenshot"+num;
/*File sourcePath = ((TakesScreenshot)Homepage.driver).getScreenshotAs(OutputType.FILE);
File destinationPath = new File(System.getProperty("user.dir") + "/target/CucumberExtentReport/Screenshots/" + screenshotName +".jpeg");
Files.copy(sourcePath, destinationPath);
Reporter.addScreenCaptureFromPath(destinationPath.toString());
*/
final byte[] screenshot = ((TakesScreenshot)Homepage.driver).getScreenshotAs(OutputType.BYTES);
File destinationPath = new File(System.getProperty("user.dir") + "/target/CucumberExtentReport/Screenshots/" + screenshotName +".jpeg");
FileUtils.writeByteArrayToFile(destinationPath, screenshot);
//Files.copy(sourcePath, destinationPath);
Reporter.addScreenCaptureFromPath(destinationPath.toString());
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
Note: I have used extent reports for adding screenshot on failed testcases...

Getting sscreenshot attached for failed test to allure report in format: datetime-classsname-testname selenium, testng, allure

I am using testng, maven, allure in my framework. Currently my screenshots for failed test are saved in surefire-reports/screenshots as :
datetime-classname-methodname
eg: 09-22-2017_01.13.23_ClassName_Methodname.png
Here is code for this :
#AfterMethod
protected void screenShotIfFail(ITestResult result) throws IOException {
if (!result.isSuccess()) {
takeScreenShot(result.getMethod());
}
}
private void takeScreenShot(String name) throws IOException {
String path = getRelativePath(name);
File screenShot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenShot, new File(path));
String filename = makeScreenShotFileName(name);
System.out.println("Taking Screenshot! " + filename);
Reporter.log("<a href=" + path + " target='_blank' >" + filename
+ "</a>");
}
private void takeScreenShot(ITestNGMethod testMethod) throws IOException {
String nameScreenShot = testMethod.getTestClass().getRealClass()
.getSimpleName()
+ "_" + testMethod.getMethodName();
takeScreenShot(nameScreenShot);
}
private String makeScreenShotFileName(String name) {
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy_hh.mm.ss");
Date date = new Date();
return dateFormat.format(date) + "_" + name + ".png";
}
private String getRelativePath(String name) throws IOException {
Path path = Paths.get(".", "target", "surefire-reports", "screenShots",
makeScreenShotFileName(name));
File directory = new File(path.toString());
return directory.getCanonicalPath();
}
For getting attached to allure reports, i tried #Attachment like this :
#Attachment(value = "filename", type = "image/png")
private byte[] takeScreenShot(String name) throws IOException {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
Screenshot is getting attached to allure report, but how can i get it in same format as in surefire reports.
Thanks !!
You can pass a custom name directly into method annotated with #Attachment:
#Attachment(value = "{name}", type = "image/png")
private byte[] takeScreenShot(String name) throws IOException {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
The only difference between Allure 1 and Allure 2 is in value parameter. For Allure 1 use the following syntax:
value = "{0}"
Where {0} is reference to the first method's parameter (its index).
For Allure 2, use the following:
value = "{name}"
In this case {name} is the name of a method's parameter.

How to test login page with multiple webpage(present in notepad) using selenium web driver Java?

I am testing like 100 url everything is working good. my problem is when the test starts it get web url from notepad then open the url here my process is to check the login or not in some case if the for example 10th url shows 404 error the test terminate here it cant process further urls. Any solution for this process...
my codes
public class File {
#Test(dataProvider="testdata")
public void sum(String url)
{
System.out.println(url);
}
#DataProvider
public Object[][] testdata(){
int count=20;
Object[][] obj = new Object[count][1];
for(int i=0;i<=count;i++)
{
String fileName = "E:\\ework\\Web\\bin\\Websearch\\test.txt";
try {
String line = null;
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
String[] abs={line};
int size = abs.length;
for(int j=0;j<=size;j++)
{
obj[i][0]=abs[j];
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
`}
return obj;
}
}
thank you.:)
If you are using framework like TestNG then look at DataProviders for the same.
Use Try{} Catch(Exception e){} block. Insert your assertion in try block and once the assertion fails then try to capture the exception in some list or other data structure and after all urls are processed then iterate over the exception list and report it in your Reports or logs.

Unable to add screenshot in ReportNG HTML report

I am trying to take a screenshot for failure methods and also want to put the same in my Report, I am able to take the screenshot but unable to show the same in HTML report. Following is my code, friends any clue on this ?
public class SB1 {
private static Logger logger = Logger.getLogger(SB1.class);
WebDriver driver = new FirefoxDriver();
#Test
public void Testone() {
driver.get("http://www.google.com/");
assert false;
}
public void catchExceptions(ITestResult result) {
System.out.println("result" + result);
String methodName = result.getName();
System.out.println(methodName);
if (!result.isSuccess()) {
try {
String failureImageFileName = new SimpleDateFormat("MM-dd-yyyy_HH-ss").format(new GregorianCalendar().getTime())+ ".png";
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(failureImageFileName));
String userDirector = System.getProperty("user.dir") + "/";
Reporter.log("<a href=\""+ userDirector + failureImageFileName +"\"><img src=\"file:///" + userDirector
+ failureImageFileName + "\" alt=\"\""+ "height='100' width='100'/> "+"<br />");
Reporter.setCurrentTestResult(null);
} catch (IOException e1) {
e1.printStackTrace();
}
}
Have you set ESCAPE_PROPERTY to false? This is what you will have to do if you want reportng to post the screenshot -
private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
and in your setUp-
System.setProperty(ESCAPE_PROPERTY, "false");
I tried this. It seems like if you set the System Property to false, it removes the escaping from the ENTIRE log... From what I can tell, the report is generated after the test, with whatever the system property is set to at the time. I want to insert the screenshot (which worked with above code) but I do not want to remove the other formatting (br tags).
You can use following code.
Reporter.log("<br>Chrome driver launched for ClassOne</br>");
Or you can use customize method, where you do not need to append the br tag everytime, use following customized method.
public void customLogReport(String testCaseDescription) throws Exception{
try{
Reporter.log("<br>" + testCaseDescription + "</br>");
}catch(Exception e){
e.printStackTrace();
}
}