How to embed base64 image in HTML using pytest-html? - pytest

I am using python-appium client and generating a HTML report after the tests are finished. I would like to add the embedded images of the failure tests in the HTML report. The reason to embed the image is that I can access it from the remote machine as well. Here is the code which I tried and doesn't work on another system but locally it works:
#pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
if report.when == 'call' or report.when == 'setup':
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
screenshot = driver.get_screenshot_as_base64()
extra.append(pytest_html.extras.image(screenshot, ''))
report.extra = extra
It seems to me that the encoded image is not generated properly as this is what I can see in the output HTML file:
<td class="extra" colspan="4">
<div class="image"><img src="assets/75870bcbdda50df90d4691fa21d5958b.png"/></div>
and I expect "src" to not to end with ".png" and it should be long string of characters. I have no idea how to resolve this.

Your code is correct. However, the standard behaviour of pytest-html is that even if you pass the image as base64 string, it will still store a file in the assets directory. If you want to embed the assets in the report file, you need to pass the --self-contained-html option:
$ pytest --html=report.html --self-contained-html
Or store the option in the pytest.ini:
# pytest.ini (or tox.ini or setup.cfg)
[pytest]
addopts = --self-contained-html
For the sake of completeness, here's the relevant spot in pytest-html readme:
Creating a self-contained report
In order to respect the Content Security Policy (CSP), several assets such as CSS and images are stored separately by default. You can alternatively create a self-contained report, which can be more convenient when sharing your results. This can be done in the following way:
$ pytest --html=report.html --self-contained-html
Images added as files or links are going to be linked as external resources, meaning that the standalone report HTML-file may not display these images as expected.
The plugin will issue a warning when adding files or links to the standalone report.

Related

Can you get access to a pages front matter (or other data) in a eleventy (11ty) plugin

I'm creating (would like to create) an eleventy (11ty) plugin that can automatically generate Open Graph images based on a pages data. So in the template:
---
generate_og_image: true
image_text: "text which will be baked into the image"
og_image_filename: some_file_name.jpg
---
#some markdown
...
I can process each file in my .eleventy.js file via plugin using:
module.exports = function (eleventyConfig) {
eleventyConfig.addLinter("og-image-generator", function(content, inputPath, outputPath) {
title = HOW_TO_ACCESS_TEMPLATE_FRONT_MATTER
createImage(title)
});
}
But only have access to the content, inputPath and outputPath of the template.
How can I access the front matter data associated with the Template? Or is there a better way to go about this?
Answering my own question. As #moritzlost mentioned it is not possible directly. I found this workaround.
eleventyComputed allows you to dynamically assign values to keys. It also allows you to call a custom shortcode.
You can pass whatever properties you like from the template into the shortcode. In this case ogImageName the image name, ogImageTemplate a template or background image and text which is the text to be written on that background.
You can even pass in other keys from your front matter and process them as you go.
---
layout: _main.njk
title: "Some title here"
eleventyComputed:
ogImageName: "{% ogCreateImage { ogImageName: title | slug, ogImageTemplate: 'page-blank.png', text: title } %}"
---
Then in .eleventy.js or a plugin:
eleventyConfig.addShortcode("ogCreateImage", function(props) {
const imageName = props.ogImageName
const imageTemplate = props.ogImageTemplate
const imageText = props.text
console.log('-----------------ogCreateImage-----------------');
console.log(`filename: ${imageName}`);
console.log(`using template: ${imageTemplate}`);
console.log(`with the text : ${imageText}`);
// call the image creation code — return filename with extension
const imageNameWithExtension = createOGImage(imageName, imageTemplate, imageText)
return imageNameWithExtension
});
Returning the final filename which you can use in your template.
I've also come across this problem. I don't think what you're trying to do is possible at the moment. There are not many ways for a plugin to hook into the build step directly:
Transforms
Linters
Events
I think events would be the best solution. However, events also don't receive enough information to process a template in a structured way. I've opened an issue regarding this on Github. For your use-case, you'd need to get structured page data in this hook as well. Or eleventy would need to provide a build hook for each page. I suggest opening a new feature-request issue or adding a comment with your use-case to my issue above so those hooks can be implemented.
Other solutions
Another solution that requires a bit more setup for the users of your plugin would be to add your functionality as a filter instead of an automatic script that's applied to every template. This means that the users of your plugin would need to add their own template which passes the relevant data to your filter. Of course this also gives more fine-control to the user, which may be beneficial.
I use a similar approach for my site processwire.dev:
A special template loops over all posts and generates an HTML file which is used as a template for the generated preview images. This template is processed by eleventy. (source)
After the build step: I start a local server in the directory with the generated HTML files, open them using puppeteer and programmatically take a screenshot which is saved alongside the HTML templates. The HTML templates are then deleted.
This is integrated into the build step with a custom script that is executed after the eleventy build.
I've published the script used to take screenshots with Puppeteer as an NPM package (generate-preview-images), though it's very much still in alpha. But you can check the source code on Github to see how it works, maybe it helps with your plugin.

Why does DITA Open Toolkit PDF plugin rename image href attributes?

I'm sorry if this doesn't have enough information. I don't typically ask for help online like this.
I'm using DITA Open Toolkit 3.4 on Windows. I generated a plugin called "vcr2" using Jarno's (very excellent and helpful) PDF Plugin Generator and then made a handful of customizations. The plugin uses the pdf2 plugin as a base. When I try to use the vcr2 plugin, my images are not working. I've tracked the problem down to malformed image filenames in the image's href attribute.
For example:
In my source file (a DITA Task), the markup for one of my images looks like this:
<image href="MyRemindersChooseReminder.png"/>
If I run a transform with the pdf2 plugin, the images work fine. In the merged stage1.xml file in the Temp folder, the XML for that same image looks like this:
<image class="- topic/image " href="df2d132af27436c59c5c8c4282e112d62bec8201.png" placement="inline" xtrc="image:1;10:66" xtrf="file:/V:/Vasont/Extract/t12340879-minimal/t12340879.xml"/>
It is processed into a file Topic.fo, and looks like this:
<fo:external-graphic
 src="url('file:/V:/Vasont/Extract/t12340879-minimal/MyRemindersChooseReminder.png')"/>
Everything works fine and the image looks fine.
If I run the same file through my 'vcr2' plugin, which just calls the same pdf2 plugin with some overrides, all the images get broken:
stage1.xml
<image class="- topic/image " href="df2d132af27436c59c5c8c4282e112d62bec8201.png" placement="inline" xtrc="image:1;10:66" xtrf="file:/V:/Vasont/Extract/t12340879-minimal/t12340879.xml"/>
Topic.fo
<fo:external-graphic
 src="url('file:/V:/Vasont/Extract/t12340879-minimal/df2d132af27436c59c5c8c4282e112d62bec8201.png')"
/>
As I track this down further, it appears that somewhere in the map-reader Ant task, this filename gets changed to that cryptic string of pseudo-hexadecimal. I think later on it's supposed to be changed back or resolved to a complete URI or something.
So, the two-part question is: Why does Open Toolkit change my filenames, and what's supposed to change them back?
DITA-OT's preprocess uses hashes for temporary filenames because it allows the code to not deal with directory structures. This enables preprocess to work in so-called "map-first" mode, where it first processes all DITA map resources and only then starts to process DITA topic and image resources.
The preprocess has a step called clean-preprocess that can rewrite the temporary file names to match source resource files names. However, this rewrite operation is disabled for PDF output because the original file names are not used for anything in that output type.

Combine two TCPDF documents

I'm using TCPDF to create two separate reports in different parts of my website. I would like that, in the end of the first report, the second report should be loaded.
It's different than import a PDF file, because the second report is also generated by TCPDF. Is there a way to do this?
I assume from your question that what you ultimately want to provide is one PDF file that consists of the first PDF concatenated with the second PDF.
One quick and dirty solution is to utilize the pdftk command line PDF processor and call it from within your PHP code using the exec() function. The pdftk command has many features and concatenating files is only one of them, but it does an awesome job. Depending on your hosting situation, this may or may not be an option for you.
The other option would be to use FPDI to import the two PDF files and concatenate them within your PHP code and then send the concatenated version to the user.
More information on using PFDI here:
Merge existing PDF with dynamically generated PDF using TCPDF
Given that you're already using TCPDF, importing the pre-existing file that you want to concatenate with the one you've just created shouldn't be too difficult.
Just add FPDI to your project/composer from:
https://www.setasign.com/products/fpdi/downloads/
Can you still used tcpdf.
FPDI support all the methods of tcpdf, just used new FPDI() instead new tcpdf() the result will be the same in your report, after you create your report marge the files with the code from this page:
https://www.setasign.com/products/fpdi/about/
In a loop, once set the first file and after this set the second...
If you will need help i am here for you.

Karma html2js doesn't seem to have created any __html__ array

I am attempting to set up tests for a Polymer application using Karma. However an essential element of those tests is the basic html fixture.
However, when I get to the code that tries to read the __html__ array. this gives an undefined.
I have included all the key files in a gist
https://gist.github.com/akc42/121c619ef2476ce82086
Because polymer.js needs to be loaded as the first script in head, and because Karma includes all the files as script tags, I have a PolymerTests.js script which adds the Polymer element to the head. It also defines a load fixtures function which should read one of the files that have been placed in __html__ and adds it to a container div in the main body of the test page.
var container; //Used to hold fixture
PolymerTests.loadFixture = function(fixture,done) {
container = document.createElement("div");
container.innerHTML = __html__[fixture];
document.body.appendChild(container);
waits(0);
done();
};
This is called in a beforeEach routine for a specific test.
However when I get there, I get undefined.
EDITED
The question of course is has anyone any idea how to work out what I am doing wrong. I tried a debug session, but can't see window.__html__ defined anywhere.
In order for the pre-processor to actually put files into the __html__ array is is necessary to ensure the files are also included in the "files" section of the karma configuration file. If there are not included there, they won't be put into the array.
Probably you also use ng-html2js preprocessor. And they have ugly thing in index.js:
// TODO(vojta): remove this in 0.11
'preprocessor:html2js': ['factory', require('./html2js')]
After removing it, it will work.

How to combine several PNG images as layers in a single XCF image?

I have several PNG images, which I need to combine as individual layers in a new GIMP XCF image. I need to perform this task many times, so a script based solution would be best.
So far i tried to play around with the batch mode of GIMP, but failed miserably.
Instead of script-fu, which uses Scheme, I'd recommend using the GIMP-Python binding for this, since it is far easier to manipulate files and listings.
If you check filters->Python->Console you will b dropped into an interactive mode - at the bottom of it, there will be a "Browse" button which lets you select any of GIMP's procedures in its API and paste it directly in this console.
There is as an API call to "load a file as a layer" - pdb.gimp_file_load_layer -
this however, brings the image to memory, but do not add it to the image - you have to call
pdb.gimp_image_insert_layer afterwards
You can type this directly in the interactive console, or,check one of my other GIMP-related answers, or some resource on GIMP-Python on the web to convert it to a plug-in, which won't require pasting this code each time you want to perform the task:
def open_images_as_layers(img, image_file_list):
for image_name in image_file_list:
layer = pdb.gimp_file_load_layer(image_name)
pdb.gimp_image_insert_layer(img, layer, None, 0)
img = gimp.image_list()[0]
image_list = "temp1.png temp2.png temp3.png"
open_images_as_layers(img, image_list.split())
The second to last line img = ... picks a needed reference to an open image
in GIMP - you could also create a new image using pdb calls if you'd prefer
(example bellow).
The file list is a hardcoded space separated string in the snippet above,
but you can create the file list in any of the ways allowed by Python.
For example, to get all the ".png" file names in a
c:\Documents and Settings\My user\Pictures folder, you could do:
from glob import glob
image_list = glob("c:/Documents and Settings/My user/Pictures/*png")
To create an image programatically:
img = gimp.Image(1024, 768)
pdb.gimp_display_new(img)