To save screenshots of each execution in different folder in selenium - java

For each execution screenshots should be saved in different folder with date and time. Tried with below code but its not working as expected.It is generating folder based on minutes not on Execution.Please help..Thanks in advance.
public static String screenShot(WebDriver driver,
String screenShotName, String testName) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formater = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
SimpleDateFormat formater1 = new SimpleDateFormat("dd_MM_yyyy_hh_mm");
try {
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File targetFile = new File("iWealthHKTestAutomation/resources/Screenshots_"+formater1.format(calendar.getTime())+"/"+ screenShotName+formater1.format(calendar.getTime()) + ".png");
FileUtils.copyFile(screenshotFile, targetFile);
return screenShotName;
} catch (Exception e) {
System.out.println("An exception occured while taking screenshot " + e.getCause());
return null;
}
}
public String getTestClassName(String testName) {
String[] reqTestClassname = testName.split("\\.");
int i = reqTestClassname.length - 1;
System.out.println("Required Test Name : " + reqTestClassname[i]);
return reqTestClassname[i];
}
enter image description here

If I understood you correctly you call screenShot multiple times during one "run". So if you want the folder to have the "execution time" or rather the start time of the run, you have to pass that as a parameter as well. Otherwise screenShot() will always create a new timestamp.
So change the signature to
public static String screenShot(WebDriver driver,
String screenShotName, String testName, Date startTime) {...
and use startTime instead of the Calendar object.

You have to add testname in folder as it will track execution
If you use timestamp then it will change for same test also
public static String screenShot(WebDriver driver,String screenShotName, String
testName) {
try {
File screenshotFile = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
File targetFile =
new File("iWealthHKTestAutomation/resources/Screenshots_"
+ testName /* pass testname param here like this*/
+ "/"
+ screenShotName
+ String.valueOf(new
SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()))
+ ".png");
FileUtils.copyFile(screenshotFile, targetFile);
return screenShotName;
} catch (Exception e) {
System.out.println("An exception occured while taking screenshot " + e.getCause());
return null;
}
}

Related

Java string resetting stored value to null

i am new to Java but have 3 years experience in C#, i am encountering an issue where by a String is not retaining its assigned value (using Getter/Setter methods).
my object class is looking like so;
public class filePathPojo {
private String FilePath;
public void setFilePath(String _Path){
this.FilePath = _Path;
}
public String getFilePath(){
return this.FilePath;
}
}
I am having a separate class file with two methods, one is creating a Directory Route with unique value based on who is using application, it is then storing the Path using the Set, the next method is capturing a screenshot and moving to the new directory. Everytime the screenshot method is running and calling the 'Get' it is returning NULL! this is quite frustrating for something so simple.
other class looks like so
public class folderSetup extends filePathPojo {
public void SetupDirectory(String ScenarioName){
String Root = "C:\\Users\\" + SomeIdentifier + "\\GherkinEvidence\\SomeProject\\";
String Today = DateTime.now().toString("dd:MM:yyyy");
Today = Today.replace(":", "-");
String dtNOW = DateTime.now().toString("HH:mm:ss");
dtNOW = dtNOW.replace("/", "-").replace(":", "");
File file = new File(Root + Today + "\\" + dtNOW + " " + ScenarioName);
boolean dirCreated = file.mkdirs();
System.out.println("***Attemping To Create Directory: " + file.getAbsolutePath());
FilePath = file.getAbsolutePath();
setFilePath(FilePath);
}
public String takeScreenshot(String screenshotName, WebDriver driver){
String path = getFilePath();
System.out.print("Filepath for screenshot picked up is" + path);
try {
WebDriver augmentedDriver = new Augmenter().augment(driver);
File source = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
//path = "./target/screenshots/" + source.getName();
FileUtils.copyFile(source, new File(path + "\\" + screenshotName + ".png"));
}
catch(IOException e) {
//path = "Failed to capture screenshot: " + e.getMessage();
}
return path;
}
}
please done anybody have an ideas?
method calls here;
contained i Step Definitions #Before (FolderSetup)
Public Class PerformanceSteps{
#Inject private folderSetup folderSetup;
#Before
public void FolderSetup(Scenario scenario){
System.out.print("***Performing Evidence Directory Setup***");
System.out.println("ScenarioName = " + scenario.getName().toString() + "**");
folderSetup.SetupDirectory(scenario.getName());
}
}
public class Navigate extends BasePage {
#Inject private com.test.utilities.folderSetup folderSetup;
public void toAppianHomePage(){
System.out.println("Navigating to Appian URL " + LoadProperties.Appian_URL);
driver.navigate().to(LoadProperties.Appian_URL);
driver.manage().window().maximize();
folderSetup.takeScreenshot("Navigate Appian Home", driver);
}

How to fix issue with taking a Screenshot and exporting it to Extent Report in Listener class for testng?

I'm creating a TestNG Maven framework.
I have a problem with taking a screenshot on test failure and uploading it to Extent Report
Below is Extent Report listener.
String targetLocation = null;
String testClassName = result.getInstanceName();
String errorDate = new SimpleDateFormat("(MM.dd.YYYY HH-mm-ss)").format(new Date());
String testMethodName = result.getName();
String screenShotName = testMethodName + errorDate + ".png";
String fileSeperator = System.getProperty("file.separator");
String reportsPath = System.getProperty("user.dir") + fileSeperator + "TestReport" + fileSeperator
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
targetLocation = reportsPath + fileSeperator + testClassName + fileSeperator + screenShotName;
try {
File targetFile = new File(targetLocation);
FileHandler.copy(src, targetFile);
} catch (FileNotFoundException e) {
Log.info("File not found exception occurred while taking screenshot " + e.getMessage());
} catch (Exception e) {
Log.info("An exception occurred while taking screenshot " + e.getCause());
}
// attach screenshots to report
try {
ExtentTestManager.getTest().fail("Screenshot", MediaEntityBuilder.createScreenCaptureFromPath(targetLocation).build());
} catch (IOException e) {
Log.info("An exception occured while taking screenshot " + e.getCause());
}
ExtentTestManager.getTest().log(Status.FAIL, "Test Failed");
Simply put this code for screenshot.
ExtentTestManager.startTest(method.getName(), description);
ExtentTest extentTest = ExtentTestManager.getTest();
String base64Screenshot = "data:image/png;base64," + ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
extentTest.log(LogStatus.FAIL, logs, ExtentTestManager.getTest().addBase64ScreenShot(base64Screenshot));

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.

Access file using Java in Windows with illegal Character in path

I am using a Windows machine and Java. I'm just trying to backup a file, but I ran into an issue with an illegal character in the path ("#"). I really tried and I'm stuck. I rewrote it trying all the variations I could find or think of. Any help would be greatly appreciated.
public class SyncActionMachine {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, URISyntaxException {
String MSI_one, MSI_two, dropBox;
GetDate getDate = new GetDate();
MSI_one = "C:\\Users\\Brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\Q2965ZS7\\localhost\\ActionMachine.sol";
MSI_two = "C:\\Users\\Brian\\Desktop\\test.txt";
dropBox = "C:\\Users\\Brian\\Dropbox\\Action Machine History\\ActionMachine.sol";
File source = new File(MSI_one);
File destination = new File(dropBox);
// Attempt #1 using string with special characters
try {
Files.copy(source.toPath(), destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #2 using URI - not really sure how to use it.
URI uri;
uri = new URI("file:///C:/Users/Brian/AppDate/Roaming/Macromedia/Flash%20Player/%23SharedObjects/Q2965ZS7/localhost/ActionMachine.sol");
Path uriSelfMadePath = Paths.get(uri);
try {
Files.copy(uriSelfMadePath, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #3 Suggestion from Aurasphere. Thanks again for quick response.
// Not sure what I'm suppose to do with the URL
String thePath = MSI_one;
thePath = URLEncoder.encode(thePath, "UTF-8");
Path aurasphereThePath = Paths.get(thePath);
try {
Files.copy(aurasphereThePath, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #4 build path using Patha and passing in augruments separately
Path pathOneByOne = Paths.get("C:", "Users", "Brian", "AppDate", "Roaming", "Macromedia", "Flash Player",
"#SharedObjects", "Q2965ZS7", "localhost", "ActionMachine.sol");
try {
Files.copy(pathOneByOne, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Seeing what all these path's look like
URL fileUrl = source.toURI().toURL();
URI fileUri = source.toURI();
System.out.println("------------Path Print out------------------");
System.out.println("URLEncoder : " + thePath);
Path from = Paths.get(fileUri);
System.out.println("URL : " + fileUrl);
System.out.println("URI : " + fileUri);
System.out.println("source: " + source);
}
}
Thanks for any advice.
Just use URLEncode:
String thePath = "your_path";
thePath = URLEncoder.encode(thePath, "UTF-8");
Thank you everyone that looked and commented. Must have been some sleep derived moment. Anyway here is the source, it worked fine. Turned out # was a big deal, I'm not even sure what my hang up was.
public static void main(String[] args) throws IOException, URISyntaxException {
String MSI_one, MSI_two, dropBox;
GetDate getDate = new GetDate();
MSI_one = "C:\\Users\\Brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\Q2965ZS7\\localhost\\ActionMachine.sol";
MSI_two = "C:\\Users\\brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\HSTARDTM\\localhost\\ActionMachine.sol";
dropBox = "C:\\Users\\brian\\Dropbox\\Action Machine History\\";
// Create new file name for backup file
dropBox = dropBox + "ActionMachine-" + getDate.today() + ".sol";
File source = new File(MSI_two);
File destination = new File(dropBox);
copyNewFile cf = new copyNewFile(source, destination);
}
public class copyNewFile {
public copyNewFile(File source, File dest) throws IOException {
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(source.toPath(), dest.toPath(), options);
System.out.println("File sucessfully copied.");
}
}

System.getProperty("user.home") returns /root when running on Tomcat

I am developing my application in Ubuntu. I have one Java web Spring MVC application. In that I have a controller. The client can upload a file (posting through AngularJS). In the controller, I am getting the file and copying to a specific location.
Here is my controller
#RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
#ResponseBody
public String UploadFile(HttpServletRequest request,HttpServletResponse response) {
SimpleDateFormat sdf = new SimpleDateFormat("MM_dd_yyyy_HHmmss");
String date = sdf.format(new Date());
String fileLoc = null;
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Iterator<String> itr = mRequest.getFileNames();
while (itr.hasNext()) {
MultipartFile mFile = mRequest.getFile(itr.next());
String fileName = mFile.getOriginalFilename();
String homePath=System.getProperty("user.home");
String separator=File.separator;
fileLoc = homePath + separator + "myapp" + separator + "file-uploads" +
separator + date + "_" + fileName;
System.out.println(fileLoc);
try {
File file = new File(fileLoc);
// If the directory does not exist, create it
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileCopyUtils.copy(mFile.getBytes(), file);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
return fileLoc;
}
But when I deploy it in tomcat server and run, the file is getting created in root.
When I print the value of fileLoc, it shows
/root/myapp/file-uploads/01_16_2014_000924_document.jpg
I added a main method in the controller.
public static void main(String[] args) {
String homePath=System.getProperty("user.home");
String separator=File.separator;
System.out.println("Home Path: " + homePath);
System.out.println("Separator: " + separator);
}
When I run this as Java Application, I am getting proper output
Home Path : /home/shiju
Separator : /
Why it's giving root when running on Tomcat?
If you are executing the application with the root user then it is obvious that /root/ will be returned in the user.home property.

Categories

Resources