Taking screen shot when soft assert fails using appium java - java

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.

Related

screen shot is not displayed in extent report

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());
}

FFmpeg doesn't work on android 10, goes strait to onFailure(String message) with empty message

I'm using FFmpeg in one of my projects for video compression. On Android 10 (Google Pixel 3a), it goes straight to onFailure(String message) with empty message for any command sent for execution.
so I have (api 'com.writingminds:FFmpegAndroid:0.3.2') specified in my app gradle file,
permission (android.permission.WRITE_EXTERNAL_STORAGE) in the manifest is specified
So I do:
InitializationCallback initializationCallback = new InitializationCallback();
try {
FFmpeg.getInstance(context).loadBinary(initializationCallback);
} catch (FFmpegNotSupportedException e) {
initializationCallback.onFailure();
initializationCallback.onFinish();
}
Initializes just fine, no problems here.
Later:
void getData(File inputFile) {
//inputFile points to: /storage/emulated/0/Android/data/{package_name}/files/temp_files/temp_1.mp4
String[] cmd = ("-i " + inputFile.getAbsolutePath()).split(" ");
try {
FFmpeg.getInstance(App.instance).execute(cmd, this);
} catch (FFmpegCommandAlreadyRunningException e) {
throw new Error(e);
}
}
#Override
public void onStart() {
//This method is called
}
#Override
public void onSuccess(String message) {
//This method is NOT called
extractAvailableData(message);
}
#Override
public void onProgress(String message) {
//This method is NOT called
extractAvailableData(message);
}
#Override
public void onFailure(String message) {
//This method is called and the message is empty
extractAvailableData(message);
}
#Override
public void onFinish() {
//This method is called
}
If I do something like:
String command = "-i ***/file1.mp4 -map 0:v -map 0:a -preset ultrafast -s:v 750:350 ***/file2.mp4";
//file2.mp4 is a non existent file at this point
// (***) --> is just a replacement for the full path of the file, just to keep things shorter here.
String[] cmd = command.split(" ");
try {
FFmpeg.getInstance(App.instance).execute(cmd, this);
} catch (FFmpegCommandAlreadyRunningException e) {
throw new Error(e);
}
gives the same result, no video conversion, just a call to onFailure("Nothing")
Even if I do:
String[] cmd = {"-version"};
try {
FFmpeg.getInstance(App.instance).execute(cmd, this);
} catch (FFmpegCommandAlreadyRunningException e) {
throw new Error(e);
}
I get nothing, no output at all.
I encountered this issue only on Android 10 so far, it works fine on other devices.
Android 10 had behavioral changes where execute permission for app home directory was removed. You will get a permission denied exception if you try and run the execution file from App home directory.
Here are the details on the changes for target SDK version 29 : https://developer.android.com/about/versions/10/behavior-changes-10#execute-permission
java.io.IOException: Cannot run program "/data/user/0/<package name>/files/ffmpeg": error=13, Permission denied
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1050)
at nl.bravobit.ffmpeg.ShellCommand.run(ShellCommand.java:15)
at nl.bravobit.ffmpeg.FFcommandExecuteAsyncTask.doInBackground(FFcommandExecuteAsyncTask.java:43)
at nl.bravobit.ffmpeg.FFcommandExecuteAsyncTask.doInBackground(FFcommandExecuteAsyncTask.java:12)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.io.IOException: error=13, Permission denied
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:133)
at java.lang.ProcessImpl.start(ProcessImpl.java:141)
I don't know if it'd be your case, but in my case the problem was that I didn't call ffmpeg.loadBinary before using it.
It seems a bit counter intuitive, because it actually work with my testing device without doing that. I have some ideas on why, but no time to test these. The important thing is that it's working now. Here an example of what I had to implement:
FFmpeg ffmpeg = FFmpeg.getInstance(context);
ffmpeg.loadBinary(new FFmpegLoadBinaryResponseHandler() {
#Override
public void onFailure() {
// Report failure to logcat,show the user a dialog, throw an exception or whatever you want to do in case of failure
}
#Override
public void onSuccess() {
// Execute the real ffmpeg stuff here
}
#Override
public void onStart() {
}
#Override
public void onFinish() {
}
});
In a real world scenario, if you plan to use it several times, you may use a flag to make sure it's not been loaded already and avoid trying to reload it in such case.

Check and open downloaded file in Selenium?

I must check downloaded PDF and open it using Selenium. For that, I am using Robot class. This is not the permanent or we can say general solution of this.
Question : Can anyone please help and provide more reliable solution for the same ?
Please find below code:
public boolean CommonEvents(WebDriver driver) throws InterruptedException {
try {
Thread.sleep(2000);
Robot robot = new Robot();
robot.mouseMove(100, 700);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(10000);
} catch(Exception e) {
BaseTest.reportPass(driver, null, "Should click on PDF to open", "Failed to click on PDF to open");
}
}
Just in case you really need to open every downloaded PDF then I would simply add this line to your preferences (e.g. for Firefox):
ffprofile.setPreference("browser.helperApps.neverAsk.openFile", "application/pdf");
Then it will automatically open the downloaded file after finishing the download.
You can use something similar to this if you have a fixed directory where you are saving the downloaded pdf files .
public static void main(String[] args) {
try {
File pdfFile = new File("c:\\Hello.pdf");
if (pdfFile.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(pdfFile);
} else {
System.out.println("Awt Desktop is not supported.");
}
} else {
System.out.println("File doesn't exists.");
}
System.out.println("File opened.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
Reference : https://docs.oracle.com/javase/6/docs/api/java/awt/Desktop.html
We use below logic:
First set preference for a download location, so that the file will be downloaded to your desired location.
chromePrefs.put("download.default_directory", downloadFilepath);
Set Preference so that it won't ask the pop to download.
chromePrefs.put("profile.default_content_settings.popups", 0);
As #Mudit_ has answered check for the *.pdf with regex pattern, if you want to make it dynamic.

PixelCopy android implementation

I am new to android development so I think this may be a teething issue on my part, but I am currently trying to use the PixelCopy function in android studio. I have code as shown below, and it matches what the base class is expecting although it is returning an error. Would anyone be able to assist me with this issue?
The code I currently have is as follows:
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
SurfaceView current = new SurfaceView(view.getContext());
PixelCopy.OnPixelCopyFinishedListener copyResult;
// Make the request to copy.
PixelCopy.request(current, bitmap, copyResult, handlerThread);
if (copyResult. == PixelCopy.SUCCESS) {
//If successful do tasks in here
}
Try crating extracting finish listener as shown below in class.
private static void onPixelCopyFinished(int result) {
if (result != PixelCopy.SUCCESS) {
Log.e("err", "errMsg");
return;
}
}
You can pass the listener as below and also you'll also need to wrap it in try catch as it might throw an exception.
try {
PixelCopy.request(current, bitmap, <YOUR CLASS>::onPixelCopyFinished, this.getHandler());
} catch (IllegalArgumentException e) {
// PixelCopy may throw IllegalArgumentException, make sure to handle it
e.printStackTrace();
}

How to add help file to frame?

I'm making plugin for eclipse which opens frame with some table's when plugin command is activated. Now I want to add help file to plugin's frame, so that when clicked on help file's link in frame, file opens (executes). File is suppose to be part of plugin. My problems are:
Don't know how to make link and add it to frame.
Don't know how to locate that file in plugin from run time application.
JLabel lblFileLink = new JLabel("Help");
lblFileLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblFileLink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
/* Add code for opening file from plugin.*/
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
Found this code somewhere, now I need to implement link, any thoughts?
If i understand you question correct, something like this should work:
JLabel lblFileLink = new JLabel("Help");
lblFileLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblFileLink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
java.awt.Desktop.getDesktop().edit(INSERTYOURFILEHERE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
This will open the standard text editor and show your file. Just replace INSERTYOURFILEHERE with your own text file.
Edit: If you want to open it in Eclipse maybe look at this
Edit2: The gist of the link above:
File fileToOpen = new File("externalfile.xml");
if (fileToOpen.exists() && fileToOpen.isFile()) {
IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditorOnFileStore( page, fileStore );
} catch ( PartInitException e ) {
//Put your exception handler here if you wish to
}
} else {
//Do something if the file does not exist
}

Categories

Resources