From 145c746a076f8378d1a0475f642dee14d979032a Mon Sep 17 00:00:00 2001 From: Christian Sandberg Date: Sun, 23 Feb 2020 21:58:39 +0100 Subject: [PATCH] Add extra fixture --- README.rst | 11 +++++++++++ pytest_html/plugin.py | 24 ++++++++++++++++++++++++ testing/test_pytest_html.py | 14 ++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/README.rst b/README.rst index ff5bafeb..449cd815 100644 --- a/README.rst +++ b/README.rst @@ -192,6 +192,17 @@ created hyper link: extra.append(pytest_html.extras.text('some string', name='Different title')) +It is also possible to use the fixture :code:`extra` to add content directly +in a test function without implementing hooks. These will generally end up +before any extras added by plugins. + +.. code-block:: python + + from pytest_html import extras + + def test_extra(extra): + extra.append(extras.text('some string')) + Modifying the results table ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/pytest_html/plugin.py b/pytest_html/plugin.py index d0d5a61d..4d4d2553 100644 --- a/pytest_html/plugin.py +++ b/pytest_html/plugin.py @@ -15,6 +15,7 @@ import re from html import escape +import pytest try: from ansi2html import Ansi2HTMLConverter, style @@ -89,6 +90,29 @@ def pytest_unconfigure(config): config.pluginmanager.unregister(html) +@pytest.hookimpl(tryfirst=True, hookwrapper=True) +def pytest_runtest_makereport(item, call): + outcome = yield + report = outcome.get_result() + if report.when == "call": + fixture_extras = item.funcargs.get("extra", []) + plugin_extras = getattr(report, "extra", []) + report.extra = fixture_extras + plugin_extras + + +@pytest.fixture +def extra(): + """Add details to the HTML reports. + + .. code-block:: python + + import pytest_html + def test_foo(extra): + extra.append(pytest_html.extras.url('http://www.example.com/')) + """ + return [] + + def data_uri(content, mime_type="text/plain", charset="utf-8"): data = b64encode(content.encode(charset)).decode("ascii") return f"data:{mime_type};charset={charset};base64,{data}" diff --git a/testing/test_pytest_html.py b/testing/test_pytest_html.py index d5af5cc3..0b19c12d 100644 --- a/testing/test_pytest_html.py +++ b/testing/test_pytest_html.py @@ -583,6 +583,20 @@ def {test_name}(): assert link in html assert os.path.exists(src) + def test_extra_fixture(self, testdir): + content = b64encode(b"foo").decode("ascii") + testdir.makepyfile( + f""" + def test_pass(extra): + from pytest_html import extras + extra.append(extras.png('{content}')) + """ + ) + result, html = run(testdir, "report.html", "--self-contained-html") + assert result.ret == 0 + src = f"data:image/png;base64,{content}" + assert f'' in html + def test_no_invalid_characters_in_filename(self, testdir): testdir.makeconftest( """