pytest-dev / pytest-dev/pytest-html
How to add HTML Extras that contain a <script> tag (and allow that script to be executed)?
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 779
- Forks
- 260
- PR merge metrics
- No merged PRs in 30d
Description
I'm trying to do similar to https://github.com/pytest-dev/pytest-html/issues/931 but I think I've worked out the general case - is there a way we can add extra HTML code that contains script tags, such that the script can be executed?
Minimum viable demo:
import pytest_html
def test_demo(extras):
extras.append(pytest_html.extras.html('Before'))
extras.append(pytest_html.extras.html('<script>alert("Hello, World!");</script>'))
extras.append(pytest_html.extras.html('After'))
When you load in a web browser, you'll find the <script> tag added between 'Before' and 'After'. However, if you open report.html in a text editor, you find that it isn't inserted into the raw HTML, but rather it's encoded data as part of the data-jsonblob property of <div id="data-container" data-jsonblob="..."> - i.e. the <script> doesn't get executed, because it's inserted dynamically. It appears this is understood behaviour
A bit of experimentation suggested that the createRange method documented here would work, with the disadvantage that the script seems to be executed whenever the row is expanded or collapsed. I achieved this by replacing these lines
if (format_type === 'html') {
resultBody.querySelector('.extraHTML').insertAdjacentHTML('beforeend', `<div>${content}</div>`)
}
with
if (format_type === 'html') {
const range = document.createRange()
const fragment = range.createContextualFragment(content)
resultBody.querySelector('.extraHTML').appendChild(fragment)
}
This isn't necessarily the best way to fix this though.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the minimum demo from the issue, then inspect src/pytest_html/scripts/dom.js around the format_type === 'html' handling and the data-jsonblob rendering path. Compare the current insertion behavior with the createRange experiment described in the issue. Done means HTML extras containing script tags are handled as intended when the report is loaded, without unintended repeated execution when rows are expanded or collapsed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, python
- Domain
- frontend, testing
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100