首页 > 解决方案 > 如何构建包装 pytest 插件?

问题描述

我想用以下方式包装 pytest-html 插件:

  1. 添加选项 X
  2. 给定选项 X,从报告中删除数据

我能够通过实现该pytest_addoption(parser)功能添加选项,但被困在第二件事上......

我能做的是:实现一个钩子 frmo pytest-html。但是,我必须访问我的选项 X,才能执行该操作。问题是,pytest-html 的钩子没有将“请求”对象作为参数,所以我无法访问选项值......

我可以为钩子添加额外的参数吗?或类似的东西?

标签: pythonpytestpytest-html

解决方案


您可以将其他数据附加到报告对象,例如通过pytest_runtest_makereport挂钩周围的自定义包装器:

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    report.config = item.config

现在config可以通过report.config所有报告挂钩访问该对象,包括pytest-html

def pytest_html_report_title(report):
    """ Called before adding the title to the report """
    assert report.config is not None

推荐阅读