Adding screenshot to TestNG - html

I am running some tests using testNG and Selenium. The test data comes from a CSV file. In each step it is possible to take a screenshot of the page. I am trying to add this screenshot to the testNG HTML report (emailable report).
I am using this to add the img element;
Reporter.log("<img src=\"file:///" + pathToScreen + "\" alt=\"\"/><br />");
Now this works partially, because it is in fact adding this to the report as you can see in the screenshot below. But the HTML code does not seem to work.
Is the path to the image file wrong? I think so, but I am not sure how I can fix this.
UPDATE:
This is from the source code of the HTML report. Apparently its not even parsing it as HTML???
<div class="messages"><img src="file://C:\Users\myUSername\Desktop/screenshots/step 1_enter username_baseline.png" alt=""/></img></div>

To have the screenshot embedded in the index.html report I used relative paths as:
System.setProperty("org.uncommons.reportng.escape-output", "false");
Reporter.log(
"<a title= \"title\" href=\"../path/from/target/" + fileName + "\">" +
"<img width=\"418\" height=\"240\" alt=\"alternativeName\" title=\"title\" src=\"../surefire-reports/html/screenShots/"+fileName+"\">
</a>");
In this case, the Screenshot is displayed in the OutputReport not in the main index page with the stacktrace of the fails which is a bit anoying. But at least images and links are working.
I edit myself to add the complete solution, setting the property "org.uncommons.reportng.escape-output" as false we are passing the html code instead of the text.
I recommend to use ReportNG where the screenshots are attached correctly to the test failure with the complete stack trace:

Ok apparantly I was looking at the wrong file. I was looking at the emailable-report.html while reporter.log sends everything to index.html. In the index.html file everything is working fine using the code in my first post.

if you want to save your image both as file(jpg/png etc ..) and base64 format try below complete code .
Base64 format is recommended for emailable reports .
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//Saving image to current working directory , you can ignore this step if dont want to save file
FileUtils.copyFile(src, new File("./demotest.png"));
String fileName = System.getProperty("user.dir") + "/demotest.png";
Reporter.setEscapeHtml(false); //This need to be set as false
byte[] fileContent = FileUtils.readFileToByteArray(new File(fileName));
String encodedString = Base64.getEncoder().encodeToString(fileContent);
String path = "<img src=\"data:image/png;base64, " + encodedString + "\" width=\"300\" height=\"350\" />";
Reporter.log(path);
or if you want only Base64 file format then ..
String src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
String path = "<img src=\"data:image/png;base64, " + src + "\" width=\"300\" height=\"350\" />";
Reporter.log(path);
See Output:

Related

Flying Saucer - Open an attachment from pdf link

I would like to know if there is a way to create a link (Using HTML) to open an attachment embedded in the pdf document.
Something like this...
Open the attachment file or Open the attachment file
Any suggestion or recommendation?
Thanks
I have been able to implement this scenario after reading the next useful post
https://groups.google.com/forum/#!topic/flying-saucer-users/KuwPoTjaQYU
Steps:
Check out the next repository https://github.com/osnard/flyingsaucer
Analyse the file ITextOutputDevice.java, method processLink(RenderingContext c, Box box)
Make changes based on your needs
Build the project and use the jar file generated
Here the code to create an embedded file based on base64 content.
Java
...String doEmbedFile = handler.getAttributeValue( elem, "data-fs-embed-file" );
if ("true".equals(doEmbedFile.toLowerCase())) {
String fileName = new File(uri).getName();
String content = handler.getAttributeValue( elem, "content" );
com.lowagie.text.Rectangle targetArea = checkLinkArea(c, box);
if (targetArea == null) {
return;
}
try {
if (!_attachments.contains(fileName)) {
byte[] fileBytes = Base64.getDecoder().decode(content.getBytes("UTF-8"));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(_writer, null, fileName, fileBytes);
fs.addDescription(fileName, true);
_writer.addFileAttachment(fs);
_attachments.add(fileName);
}
targetArea.setBorder(0);
targetArea.setBorderWidth(0);
//This only works on Adobe Acrobat Reader
PdfAction action = PdfAction.javaScript(
"this.exportDataObject({cName:\"" + fileName + "\", nLaunch:2});",
_writer
);...
HTML
<body><div id='div1'><p><a href='test.png' data-fs-embed-file='true' content='iVBORw0KGgoAAAANSUhEU...'>open test.png file</a></p></div><div id='div2'><p><a href='test.pdf' data-fs-embed-file='true' content='JVBERi0xLjUNCiW1tbW1D...'>open test.pdf file</a></p></div><div id='div3'><p><a href='test.txt' data-fs-embed-file='true' content='VEVFRUVFRUVFRVNUIFRYVA=='>open test.txt file</a></p></div></body>
*base64 content truncated
Output
Greetings and I hope it can help others
just open it on new tab, add attribute target="_blank" in your anchor tag
Open attachment

How to upload a local file as link in asp.net

I want to know how to add a local file path as a link and after adding it i want to download the file while clicking the link in asp.net.
My code:
<a href="D:/Sample/test.html" runat="server">
Here i just add my local path to the server.But here nothing done while clicking the link. I want to use .zip file instead of .html file.Let me know how to upload and download by using a link.Thanks in advance
I fail to see the problem here. Just add "~/" to find file from the root of your project and add runat="server" to the anchor link:
Download Zip File
You need to resolve it from the root because while you may know that it's on the D drive on your local machine, you cannot be sure that will be the same on the server. And even if it is on the same drive on the server, what if someone migrates it later on?
As for uploading a file, simply use the Upload control?
There are lots of situation, Using this code you can do it.
File Upload Code
string FilePath = "";
string[] a = new string[1];
string fileName = "";
string FullName = "";
if (FileUploader.FileName.Length > 0)
{
a = FileUploader.FileName.Split('.');
fileName = Convert.ToString(System.DateTime.Now.Ticks) + "." + a.GetValue(1).ToString();
FilePath = Server.MapPath(#"~\SavedFolder");
Fup1.SaveAs(FilePath + #"\" + fileName);
FullName = FilePath + #"\" + fileName;
// Database Saved Code
}
File Download Code
string filename = "filename from Database";
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
string aaa = Server.MapPath("~/SavedFolder/" + filename);
Response.TransmitFile(Server.MapPath("~/SavedFolder/" + filename));
Response.End();

Css stylesheet loaded as html in Firefox

I've got a css file injected into my asp.net web form application page through a base page. The method I use look like the following:
private void InjectLocalStyleSheet()
{
if (this.Page.Header == null)
return;
Literal cssFile = new Literal()
{
Text =
#"<link rel=""stylesheet"" type=""text/css"" href=""" + Page.ResolveUrl("~/Common/Theme.css") +
#""" />"
};
Page.Header.Controls.Add(cssFile);
}
When I run the page in firefox, that css file gives me a 302 warning. Apparently, firefox view this file as html type while I've specified the type to be "text/css".
snap of request and response headers
I also run the web page in Chrome and get "Failed to load resouce: net::ERR_TOO_MANY_REDIRECTS"
Anyone has an idea about what is going on? Please help. Thank you.

MVC 5 Content Disposition errors in Chrome and Firefox

I would like to display the user manual of the system as pdf in the browser.
The following code works fine in IE9 but not
Chrome - Error duplicate errors received from server
Firefox - Corrupted content error
The MVC 5 code ( I think is adding duplicate headers which IE can handle)
Just wondering is there any way this will work with all browsers?
public FileResult UserManual()
{
var FileName = "user-manual.pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = FileName
};
Response.AddHeader("Content-Disposition", cd.ToString());
string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data/";
return File(path + FileName, MediaTypeNames.Application.Pdf, FileName);
}
I know this is old but I got into the same issue today.
If you add a "Content-Disposition" header then do not return File with the "FileName" argument added
Check this:
if (myFile.IsInlineContent()) // Evaluate the content type to check if the file can be shown in the browser
{
Response.AppendHeader("content-disposition", $"inline; myFile.Filename}");
return File(myFile.Path, myFile.Type); // return without filename argument
}
// if not, treat it as a regular download
return File(myFile.Path, myFile.Type, myFile.Filename); // return with filename argument
Hope this helps...
In order to show the file in the browser, do not provide the file name as the third parameter to the File method in your return statement. This forces a content-disposition of attachment behind the scenes. As such, your code should result in an invalid response with an ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION error.

The html page not showing correct link when using htmlunit driver

I have written a selenium script which runs in java :
String pageName = "my test url which invloves an link to html which has javscript excution";
logger.log(Level.INFO,"Page name : " + pageName);
WebDriver driver = new HtmlUnitDriver(true);
logger.log(Level.INFO,"driver instance created " );
String str ="";
logger.log(Level.INFO,"opening the url now.... " );
driver.get(pageName);
logger.log(Level.INFO,"url is now opened :: url = "+driver.getCurrentUrl());
logger.log(Level.INFO,"driver now going to sleep = "+driver.getCurrentUrl());
Thread.sleep(150000);
logger.log(Level.INFO,"Wake up from sleep now....");
logger.log(Level.INFO,"URL ::"+driver.getCurrentUrl());
logger.log(Level.INFO,"PageSource ::"+driver.getPageSource());
try {
logger.log(Level.INFO,"Driver going to wait now...");
driver.wait(100000);
logger.log(Level.INFO,"Driver came out of wait now normally...");
} catch (Exception e) {
logger.log(Level.INFO,"Driver came out of wait now exception::"+e);
}
logger.log(Level.INFO,"driver instance task completed " );
logger.log(Level.INFO,driver.getCurrentUrl());
logger.log(Level.INFO,driver.getCurrentUrl());
logger.log(Level.INFO,str);
driver.close();
Now when I debug this code I get my proper result but when I run this piece of code from servlet I get only the html content not the proper content which is excepted to come from the given link.
I also tried using the firefox driver and the same code works fine with it.
I also tried the same code with Web client but the same problem is coming.
Can anyone help me with this exception?
Thanks,
When you debug the code, you can halt at checkpoints. But you cannot stop browser from loading. It loads itself independently.
Htmlunitdriver pagesource returns all html contents as it cannot execute javascript completely.If the htmlpage contains Ajax, javascript calls then it shows the calls as it is .