添加新的字段到TestReport对象,并在pytest_html_results_table_html钩子中使用它.&



我想获得有关在测试call阶段引发的异常的信息,并将它们添加到使用pytest-html插件创建的报告中。所以我为pytest_runtest_makereport创建了hookwrapper:

@hookimpl(hookwrapper=True)
def pytest_runtest_makereport(call):
outcome = yield
result = outcome.get_result()
errors = getattr(result, "errors", [])
if result.when == "call":
if result.failed:
if error := call.excinfo:
errors.append(error.typename)
result.errors = errors
else:
logger.info("PASSED")

要将这些信息添加到测试报告中,我使用:

def pytest_html_results_table_html(report, data):
del data[:]
if errors := getattr(report, "errors", []):
data.append(html.div(", ".join(errors), class_="failed log"))

不幸的是,在pytest_html_results_table_html中,报告实例中没有errors字段。如果我将result.errors = errors添加到拆卸阶段,则字段出现在报告对象中,但它具有空列表。我知道有一个extra字段,但pytest-html将其直接添加到报告中。我想在添加这些值之前对它们做一些处理。

我在这里错过了什么?如何将此值从pytest_runtest_makereport传递到pytest_html_results_table_html?

我正在使用的测试类示例:

from logging import getLogger
from pytest import fixture
logger = getLogger()

class TestVariousOutputs:
@fixture()
def setup(self):
logger.info("Run setup")
raise RuntimeError("Error raised during setup")
@fixture()
def teardown(self):
logger.info("Run setup")
yield
logger.info("Run teardown")
raise RuntimeError("Error raised during teardown")
def test_pass(self):
logger.info("Run test")
assert True
def test_fail(self):
logger.info("Run test")
assert False, "Assert False"
def test_raise_error(self):
logger.info("Run test")
raise RuntimeError("Error raised during test run")
def test_setup_raise_error(self, setup):
logger.info("Run test")
assert True
def test_teardown_raise_error(self, teardown):
logger.info("Run test")
assert True
def test_teardown_raise_error_and_test_fails(self, teardown):
logger.info("Run test")
assert False, "Assert False but teardown should also fail"

因为这是pytest-html当前实现的方式:对于每个测试用例,它将获取teardown报告并从callsetup报告中复制选定的字段。当然,定制字段会被忽略(呸!)因此,您必须拦截pytest报告的这种后处理,并确保您的自定义字段出现在teardown报告上。放入conftest.py的示例:

@pytest.hookimpl(tryfirst=True)  # run our hookimpl before pytest-html does its own postprocessing
def pytest_sessionfinish(session):
html_report = getattr(session.config, "_html", None)
for rep_setup, rep_call, rep_teardown in html_report.reports.values():
# copy errors field from call report to teardown report
rep_teardown.errors = getattr(rep_call, "errors", [])

相关内容

  • 没有找到相关文章

最新更新