Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial backend for Next Gen #426

Merged
merged 5 commits into from
May 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions nextgendata.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ build-backend = "setuptools.build_meta"
[tool.setuptools_scm]
local_scheme = "no-local-version"
write_to = "src/pytest_html/__version.py"

1 change: 1 addition & 0 deletions resources/nextgendata.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

72 changes: 72 additions & 0 deletions src/pytest_html/nextgen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import json
from typing import Any

This comment was marked as outdated.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I opened an issue to track typing (#434)

I also added mypy to our linting target and began work on typing the project in #435

from typing import Dict

import pytest


class NextGenReport:
def __init__(self, config, data_file):
self._config = config
self._data_file = data_file

self._title = "Next Gen Report"
self._data = {
"title": self._title,
"collectedItems": 0,
"environment": {},
"tests": [],
}

self._data_file.parent.mkdir(parents=True, exist_ok=True)

def _write(self):
try:
data = json.dumps(self._data)
except TypeError:
data = cleanup_unserializable(self._data)
data = json.dumps(data)

with self._data_file.open("w", buffering=1, encoding="UTF-8") as f:
f.write("const jsonData = ")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we combine these f.write calls on an f string line f"const jsonData = {data}\n"?

f.write(data)
f.write("\n")

@pytest.hookimpl(trylast=True)
def pytest_sessionstart(self, session):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't all the self._write calls overwrite self._data_file?

config = session.config
if hasattr(config, "_metadata") and config._metadata:
metadata = config._metadata
self._data["environment"] = metadata
self._write()

@pytest.hookimpl(trylast=True)
def pytest_collection_finish(self, session):
self._data["collectedItems"] = len(session.items)
self._write()

@pytest.hookimpl(trylast=True)
def pytest_runtest_logreport(self, report):
data = self._config.hook.pytest_report_to_serializable(
config=self._config, report=report
)
# rename to "extras" since list
if hasattr(report, "extra"):
for extra in report.extra:
print(extra)
if extra["mime_type"] is not None and "image" in extra["mime_type"]:
data.update({"extras": extra})
self._data["tests"].append(data)
self._write()


def cleanup_unserializable(d: Dict[str, Any]) -> Dict[str, Any]:
"""Return new dict with entries that are not json serializable by their str()."""
result = {}
for k, v in d.items():
try:
json.dumps({k: v})
except TypeError:
v = str(v)
result[k] = v
return result
10 changes: 9 additions & 1 deletion src/pytest_html/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@

import pytest
from _pytest.logging import _remove_ansi_escape_sequences
from _pytest.pathlib import Path
from py.xml import html
from py.xml import raw

from . import __pypi_url__
from . import __version__
from . import extras
from . import nextgen


@lru_cache()
Expand Down Expand Up @@ -101,7 +103,9 @@ def pytest_configure(config):
if not hasattr(config, "workerinput"):
# prevent opening htmlpath on worker nodes (xdist)
config._html = HTMLReport(htmlpath, config)
config._next_gen = nextgen.NextGenReport(config, Path("nextgendata.js"))
config.pluginmanager.register(config._html)
config.pluginmanager.register(config._next_gen)


def pytest_unconfigure(config):
Expand All @@ -110,6 +114,11 @@ def pytest_unconfigure(config):
del config._html
config.pluginmanager.unregister(html)

next_gen = getattr(config, "_next_gen", None)
if next_gen:
del config._next_gen
config.pluginmanager.unregister(next_gen)


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
Expand Down Expand Up @@ -728,7 +737,6 @@ def _post_process_reports(self):
test_report.longrepr = full_text
test_report.extra = extras
test_report.duration = duration

if wasxfail:
test_report.wasxfail = True

Expand Down