The screen shot is taken and stored in the folder. but its not displaying for the failed test.
displayed as corrupted image.
Java Code:
public synchronized void onTestFailure(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " failed!"));
test.get().fail(MarkupHelper.createLabel(result.getName()+ " - Test failed due to below issue/error: ", ExtentColor.RED));
test.get().fail(result.getThrowable());
//Take screenshot and allow automatic saving of media files relative to the report
//Extentreports log and screenshot operations for failed tests.
try {
File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// String base64Screenshot = "data:image/png;base64,"+((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
String path=prop.getProperty("Screenshot_Folder")+System.currentTimeMillis()+".png";
File destination=new File(path);
FileUtils.copyFile(src, destination);
test.get().fail("Below is Screen Shot of Error Page/Pop-up: ", MediaEntityBuilder.createScreenCaptureFromPath(path).build());
//test.get().fail("Below is Screen Shot of Error Page/Pop-up: ", MediaEntityBuilder.createScreenCaptureFromBase64String(base64Screenshot).build());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Screen-capture has been taken but not attached to Extent report");
}
}
below is the property file.
AutomationReport_Folder = D://Shared//V1core_automation
ExtentReport_Folder = D://Shared//V1core_automation//ExtentReports//
Screenshot_Folder = D://Shared//V1core_automation//ExtentReports//Screenshots//
Method for screen shot
public static String getScreenshot(WebDriver driver)
{
TakesScreenshot ts=(TakesScreenshot) driver;
File src=ts.getScreenshotAs(OutputType.FILE);
String path=System.getProperty("user.dir")+"/Screenshots/"+System.currentTimeMillis()+".png";
File destination=new File(path);
try
{
FileUtils.copyFile(src, destination);
} catch (IOException e)
{
System.out.println("Capture Failed "+e.getMessage());
}
return path;
}
Replace this line in your code:
test.get().fail("Below is Screen Shot of Error Page/Pop-up: ", MediaEntityBuilder.createScreenCaptureFromPath(path).build());
With
MediaEntityBuilder.addScreenCaptureFromPath(path, result.getMethod().getMethodName());
and see it works.
I had a similar requirement to store screenshots in base64 as reports will be shared with multiple stakeholders across my team. The following solution worked well for me.
Screenshot.java
public static String getScreenshot(WebDriver driver) {
String screenshotBase64 = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
return screenshotBase64;
}
TestListener.java
#Override
public void onTestFailure(ITestResult result) {
test.fail("Test case Failed");
test.fail("Failed step: ",MediaEntityBuilder.createScreenCaptureFromBase64String("data:image/png;base64,"+Screenshot.getScreenshot(driver)).build());
test.fail(result.getThrowable());
}
Related
I have implemented a function to download aws s3 files using the following code:
public void credentialsProvider()
{
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), "us-east-2:xxxxxx-xxxxx-xxxxx-xxxx-xxxxxxx", Regions.US_EAST_2
);
setAmazonS3Client(credentialsProvider);
System.out.println("setAmazonS3Client done");
}
public void setAmazonS3Client( CognitoCachingCredentialsProvider credentialsProvider)
{
s3 = new AmazonS3Client(credentialsProvider);
s3.setRegion(Region.getRegion(Regions.US_EAST_2));
}
public void setTransferUtility()
{
transferUtility = new TransferUtility(s3, getApplicationContext());
System.out.println("setTransferUtility done");
}
public void setFileDownload()
{
final String path = this.getFilesDir().getAbsolutePath();
File myFile = new File(path);
TransferObserver transferObserver = transferUtility.download("sample-bucket-001", "images-4.jpeg", myFile);
transferObserverListener(transferObserver);
}
public void transferObserverListener(TransferObserver transferObserver)
{
transferObserver.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int id, TransferState state) {
System.out.println("onStateChanged: "+ state);
if(state == TransferState.FAILED || state == TransferState.WAITING_FOR_NETWORK){
}
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
int percentage = (int)(bytesCurrent/bytesTotal * 100);
System.out.println("percentage: "+ percentage);
}
#Override
public void onError(int id, Exception ex) {
System.out.println("Error faced: "+ ex.toString());
}
});
}
As I try to execute the following code I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxx.xxxxxxxx/com.xxxxxx.xxxxxxxx.Activity}: java.lang.IllegalArgumentException: Invalid file: /data/user/0/com.xxxxxx.xxxxxxxx/files/
I cannot save the file on external storage as I prefer to have them hidden and protected, and deleted in case the app got deleted. I used to use the path to save files on it, that are directly loaded from the internet and no problem there.
Kindly advise on the matter.
The file path supplied to TransferUtility needs to include a file name, e.g.:
final String path = this.getFilesDir().getAbsolutePath() + "images-4.jpeg";
I have finally found the solution to the question asked, which simple using a path that is totally new, unused previously, so it can create the folder that where it will store the downloaded picture or file.
final String path = this.getFilesDir().getAbsolutePath()+"/zip";
I wish Amazon's feedback could be a bit more specific than just 'invalid file'.
I'm having a hard time passing files with spaces in their names into Twilio chat.
Forgetting about the fact that I'm using Twilio, and just concentrating that I'm trying to upload a file from within the Android phone. I have an image on my android phone which I found its path as /Internal storage/Download/4893079.jpg
Below is the full code:
public void testing() {
Messages messagesObject = channel.getMessages();
try {
messagesObject.sendMessage(
Message.options()
.withMedia(new FileInputStream("/Internal%20storage/Download/4893079.jpg"), "image/jpeg")
.withMediaFileName("4893079.jpg")
.withMediaProgressListener(new ProgressListener() {
#Override
public void onStarted() {
System.out.println("Upload started");
}
#Override
public void onProgress(long bytes) {
System.out.println("Uploaded " + bytes + " bytes");
}
#Override
public void onCompleted(String mediaSid) {
System.out.println("Upload completed");
}
}),
new CallbackListener<Message>() {
#Override
public void onSuccess(Message msg) {
System.out.println("Successfully sent MEDIA message");
}
#Override
public void onError(ErrorInfo error) {
System.out.println("Error sending MEDIA message");
}
});
} catch (FileNotFoundException e) {
System.out.println("FAILED HORRIBLY");
System.out.println(e);
e.printStackTrace();
}
}
However running the app I end up with the error,
java.io.FileNotFoundException: /Internal%20storage/Download/4893079.jpg (No such file or directory)
As shown I've tried replacing space with %20, but that didn't work. I've also tried \ , \\ . However non of them worked. I've looked at Opening a local Android File with spaces, Save file in Android with spaces in file name.
How should I be replacing the space?
You need to get the actual path programmatically. So the real path is
Environment.getExternalStorageDirectory().toString() + "/Download/4893079.jpg"
Internal storage is just something the user sees, but not a real path on the machine.
I am new to automation. I want to take a screen shot when soft assert fails. I tried the code which is given here and here. But I get error when I #override onAssertFailure().
#Override //Here I get "Method does not override method from its superclass" error.
public void onAssertFailure(IAssert assertCommand, AssertionError ex) {
// TakingScreen here
File scrFile = ((TakesScreenshot) SetUp.driver)
.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File("AssertFailure_" + assertCommand.getMessage()+ ".jpg"));
}
catch (IOException e) {
e.printStackTrace();
}
}
I get following error:
Method does not override method from its superclass
and I cannot run my code.
Can anyone please, help me how can I proceed further.
I am trying to send my extent reports as email. The reports as being sent. The problem is the screenshots in my extent reports is missing in the email. If I open the report in my local device, the screenshot is there.
This is for a Selenium test am doing. I am using extent reports for my logs. I am trying to send my extent reports as email. The reports as being sent. The problem is the screenshots in my extent reports is missing in the email. If I open the report in my local device, the screenshot is there. Below is code of my Listeners.java
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class Listeners implements ITestListener {
protected static WebDriver driver;
protected static ExtentReports reports;
public static ExtentTest test;
Base B = new Base();
public void onTestStart(ITestResult result) {
test = reports.startTest(result.getMethod().getMethodName());
test.log(LogStatus.INFO, result.getMethod().getMethodName() + " test started");
}
public void onTestSuccess(ITestResult result) {
test.log(LogStatus.PASS, result.getMethod().getMethodName() + " test passed");
}
public void onTestFailure(ITestResult result) {
test.log(LogStatus.FAIL, result.getMethod().getMethodName() + " test failed");
try {
B.getScreenshot(result.getName());
String file =
test.addScreenCapture("/Users/username/Documents/Eclipse-Workspace/Test/test-output/"+result.getName()+"screenshot.png");
test.log(LogStatus.FAIL, result.getMethod().getMethodName() + "test failed", file);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onTestSkipped(ITestResult result) {
test.log(LogStatus.SKIP, result.getMethod().getMethodName() + " test skipped");
}
public void onStart(ITestContext context) {
System.out.println("Started");
driver = new ChromeDriver();
reports = new ExtentReports( "./test-output/Extentreports.html");
}
public void onFinish(ITestContext context) {
driver.close();
reports.endTest(test);
reports.flush();
}
}
I expect to view the screenshot taken on test failure when I receive the email. But now I see an empty thumbnail in the emailed extent report.
This question has been raised multiple times in the past. A quick search would have pointed you in the right direction.
The solution is to email the report along with screenshots as a zip file, and ensuring images are saved relatively to the Html file.
I'm running a series of automated GUI tests using Selenium in Java. These tests regularely takes screenshots using:
public static void takeScreenshot(String screenshotPathAndName, WebDriver driver) {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(screenshotPathAndName));
} catch(Exception e) {
e.printStackTrace();
}
}
This works excellently in Chrome and IE, however in firefox I keep getting large pieces of whitespace under the screenshots. I suspect that the whitespace is actually a part of the page itself, but normally hidden from view in the browser(the scrollbar stops before the whitespace). I did a quick test with
driver.get("http://stackoverflow.com/");
takeScreenshot("D:\\TestRuns\\stackoverflow.png", driver);
and found that when using the Firefox driver the entire page in captured in the screenshot, while with the Chrome driver only what's shown in the browser is captured.
Is there any way to force the Firefox driver to take a screenshot containing ONLY what can actually be seen in the browser (what an actual user would see)?
Based on answers from this question I was able to add 4 lines of code to just crop the image down to the browser size. This does solve my problem, although it would have been nicer if it could be solved through the driver instead of cropping after the screenshot has been taken.
public static void takeScreenshot(String screenshotPathAndName, WebDriver driver) {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
int height = driver.manage().window().getSize().getHeight();
BufferedImage img = ImageIO.read(scrFile);
BufferedImage dest = img.getSubimage(0, 0, img.getWidth(), height);
ImageIO.write(dest, "png", scrFile);
FileUtils.copyFile(scrFile, new File(screenshotPathAndName));
} catch(Exception e) {
e.printStackTrace();
}
}
Try this :
private static void snapshotBrowser(TakesScreenshot driver, String screenSnapshotName, File browserFile) {
try {
File scrFile = driver.getScreenshotAs(OutputType.FILE);
log.info("PNG browser snapshot file name: \"{}\"", browserFile.toURI().toString());
FileUtils.deleteQuietly(browserFile);
FileUtils.moveFile(scrFile, browserFile);
} catch (Exception e) {
log.error("Could not create browser snapshot: " + screenSnapshotName, e);
}
}