ExtentReports in Selenium Webdriver - selenium

I'm having an issue where ExtentReports is not showing the screenshot when the report is viewed on another machine. When saving the image into the report, I pass the absolute path of the image file. The user who wants to view the report have to copy report.html and Errorscreenshot folder to their D drive. Then only they can see the screenshot. Please suggest another way so that user can copy these files to any of their location so that screenshot can be viewed.
My code is below:
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String dest = "D:\\ErrorScreenshots\\"+screenShotName+System.currentTimeMillis()+".png";
File destination = new File("D:\\ErrorScreenshots\\"+screenShotName+System.currentTimeMillis()+".png");
FileUtils.copyFile(source, destination);
//FileUtils.copyFile(source, );

Instead of relative path. I found it is easier if the image is converted to base64 format. In that case, we only want to share .html file only.
TakesScreenshot ts = (TakesScreenshot)driver;
String dest = ts.getScreenshotAs(OutputType.BASE64);
return "data:image/jpg;base64, " + dest ;

I have used the extent report version 2.40.2 jar and have achieved sharing of my reports folder in this way. The paths are relative here and the report would render correctly with these paths. Hope this helps. I went through many links but nothing actually helped so came up with this logic.
public String capture() throws IOException {
try{
//take screenshot and save it in a file
File sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//copy the file to the required path
File destinationFile = new File(System.getProperty("user.dir")+"/reports/image_" + System.currentTimeMillis()+ ".png");
FileHandler.copy(sourceFile, destinationFile);
String[] relatvePath = destinationFile.toString().split("reports");
screenshotPath = ".\\" + relatvePath[1];
}
catch(Exception e){
//if it fails to take screenshot then this block will execute
System.out.println("Failure to take screenshot "+e);
}
return screenshotPath;
}
test.log(LogStatus.FAIL, Constants.REPORT_ERROR, test.addScreenCapture(capture()) + Constants.REPORT_ERROR_STATUS);

Use relative path for your screenshots. Save your screenshots where your html file is located.

Use relative path for screenshot as below:
String path = System.getProperty("user.dir")+"\\ErrorScreenshots\\"+screenShotName+System.currentTimeMillis()+".png";
File destination = new File(path);

Related

Report screenshot attachment link is confused

I've embedding several screenshots of various states of UI. The screenshots are attached however, the link to view the attachments are confused and opening another attachment on the report.
For e.g. 'Attachment 1 (PNG)' link to a screenshot opens/collapses the 2nd screenshot and the same with others.
I'm wondering if there is an option to customize a link text, instead of saying "Attachment 1 (PNG)" to something like "Current User Data Screenshot", to be more interactive.
I tried to upgrade the cucumber-JVM version but the issue is still there.
You can rename the screenshot file and then attach to the scenario.
//take screenshot using selenium
File src = driv.getScreenshotAs(OutputType.FILE);
//Rename the file
File newfile =new File("Current User Data Screenshot"); // Need absolute file name
if(src.renameTo(newfile)){
System.out.println("File renamed");
}else{
System.out.println("Sorry! the file can't be renamed");
}
//convert the screenshot to byte array
BufferedImage o=ImageIO.read(newfile);
ByteArrayOutputStream b=new ByteArrayOutputStream();
ImageIO.write(o, "png", b);
byte[] myscreenshot=b.toByteArray()
//Attach the screenshot to scenario
scenario.embed(myscreenshot,"image/png");

Selenium sendkeys enter pipe ( | ) for backslash (\)

In selenium sendkeys sometimes the backslash ( \ ) is replaced with a pipe ( | ) symbol. this issue is a sporadic issue.
Below is the code snippet that i have used
aItDriver.switchTo().window("[TITLE:Choose File to Upload]");
aItDriver.getKeyboard().sendKeys(new String[]{"I:\Downloads\fileName.txt" + Keys.ENTER});
in here we used autoit (aItDriver) driver to enter the file path for file upload screen,
expected output for the file upload screen was :
I:\Downloads\fileName.txt
But we see the below text entered to the upload window text box in rare cases.
I:|Downloads\fileName.txt
Could someone give an explanation to this sporadic issue, and if there is a correct way to enter the given text or fix for this issue?
#Marlan
depending on the language that you use, there is few solutions to fix the absolute path.
In java you can try:
public static void main(String[] args) throws IOException {
Path path = Paths.get("myFile.txt");
Path absolutePath = path.toAbsolutePath();
System.out.println(absolutePath.toString());
}
After that you can just used element.sendKeys(absolutePath.toString());
to upload file
Using JavaScript:
const path = require('path');
let absoluteFilePath = path.resolve('myFile.txt');
element(by.id('something').sendKeys(absoluteFilePath);

How to Download PDF Links in Column and Save to Common Folder

We have a column that contains links to PDFs that starts on line 4 (e.g B4:B). I am trying to find a way to automatically download the PDF files that are accessed via the links to a folder on Drive. This is what I have so far:
function savePDFs() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for (var i = 3; i < data.length; i++) {
Logger.log(data[i][1]);
}
}
Presumably the above code would write the links starting in column B (index value of [1]) on row 4 (i value of 3) (ie., B4) until the bottom of the data set (eg., data.length()).
I'm now confused about how to access and save the PDF link that are written in the logger to a folder.
Would someone be willing to help me out? I'm currently having to go to each link, click Save Link As... and then navigate to the folder that I'd like to save the linked PDF to. My hope is to modify the above process using code.
Update: I found this bit of code here that may help me out. Note, I changed the PDF link to a currently valid PDF link.
var urlOfThePdf = 'http://download.p4c.philips.com/l4b/9/929000277411_eu/929000277411_eu_pss_aenaa.pdf';// an example of online pdf file
var folderName = 'GAS';// an example of folder name
function saveInDriveFolder(){
var folder = DocsList.getFolder(folderName);// get the folder
var file = UrlFetchApp.fetch(urlOfThePdf); // get the file content as blob
folder.createFile(file);//create the file directly in the folder
}
Okay, I'm going to go and noodle with the data that is in the logger to confirm that the data is in properly formatted PDF links, then I'm going to test this new bit of code out. I feel like I'm getting close.
You can't force a download of a file from an apps script, you must try that from an HTMLService and not sure it will work.
For your need I would recommend to create a dedicated folder and you add all the pdf in it and you use the download function of the drive interface to download all files in one clic.
In drive, a file can be put in several folders so the pdf files stay in the original folder but you create a new folder 'PDF for download" for example and you put them in it. To do that from drive interface you have to click on "shift"+Z when file(s) is/are selected.
For you current list of file you just have to add in your loop the add to folder function. You can use this function.
function addFileToFolder(id){
var folderPDF = DriveApp.getFolderById("Id OFFolder to put pdf");
var file = DriveApp.getFileById(id);
folderPDF.addFile(file);
}
EDIT : Function will browse list of url, get the file and make a copy in a dedicated folder on the user drive.
function downloadInDriveFolder(){
var folderID = 'Id of the folder';// put id of the folder
var folder = DriveApp.getFolderById(folderID)// get the folder
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for (var i = 3; i < data.length; i++) {
var blob = UrlFetchApp.fetch(data[i][1]).getContent();
var pdf = DriveApp.createFile(blob);
pdf.setName(data[i][0]);//Put as name of the file the value in col A
folder.addFile(pdf);
}
}
Well I figured it out. I was expecting more code, but this does it for me:
function listPDFs() {
var out = new Array();
var row = 3; //row index of 0 = row 1
var column = 4; // column index of 0 = column A
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var folder = DriveApp.getFolderById("this is where you paste your folder id"); // destination folder (this is the 0978SDFSDFKJHSDF078Y98hkyo looking value when you right click your folder and select "Get Link")
for (var i=row ; i<data.length ; i++) {
if(data[i][column] !== "") {
var file = UrlFetchApp.fetch(data[i][column]);
folder.createFile(file);
}
}
return
}
As you can see, I included a row and column variable so that I could easily change these.
I haven't figured out how to assemble them into a merged PDF, but I did figure out that I could sort them by date (which places the top most item first) and then right click and select "Open With...PDF Mergy", which then moves the PDFs into PDF Mergy and merges them up in the correct order. You can find PDF Mergy in the Chrome App Store. If I figure out how to automatically call PDF Mergy from GAS, I'll post that up--but for the time being the above code has saved us a ton of time...so I'm calling it good enough for the time being.

Internet Explorer file download prompt character encoding

In Internet Explorer running an MVC 4 application, when downloading a file with an Arabic filename, the download prompt displays a filename which appears to be in the wrong character set. Please see the attached image.
If it's possible to alter the display of this filename how do I do it?
If you are using the return File method, try encoding the file name
var fileName = Path.GetFileName(filePath);
if (Request.Browser.Browser == "IE")
{
string attachment = string.Format("attachment; filename=\"{0}\"",
Server.UrlPathEncode(fileName));
Response.AddHeader("Content-Disposition", attachment);
}
return File(filePath, "application/octet-stream", fileName);

Load local HTML into WebView

Can I load a local HTML file (with images and ...) into a WebView?
Just setting the Source parameter does not do the trick.
You can load it from a file as long as the file is part of the app package, e.g.:
WebView2.Source = new Uri("ms-appx-web:///assets/text.html");
From WebView.Navigate
WebView can load content from the application’s package using
ms-appx-web://, from the network using http/https, or from a string
using NavigateToString. It cannot load content from the application’s
data storage. To access the intranet, the corresponding capability
must be turned on in the application manifest.
For a 'random' file, I suppose you could prompt user via file picker to select the file then read it into a string and use NavigateToString, but the user experience there may be a bit odd depending on what you're trying to accomplish.
I was working at this problem for a long time and I found a way to do that:
At first you should save it in InstalledLocation folder. If you haven't option to create a new .html file you can just use file.CopyAsync(htmlFolder, fname + ".html");
Look into my example:
StorageFolder htmlFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFolderAsync(#"HtmlFiles", CreationCollisionOption.GenerateUniqueName);
IStorageFile file = await htmlFolder .CreateFileAsync(fname + ".html", CreationCollisionOption.GenerateUniqueName);
and than you can easily open your .html file:
var fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".html");
var file = await fop.PickSingleFileAsync();
if (file != null)
{
string myPath = file.Path.Substring(file.Path.IndexOf("HtmlFiles"));
myWebview.Navigate(new Uri("ms-appx-web:///" + myPath));
}
Remember just only from InstalledLocation you can open it with ms-appx-web:///