【问题标题】:How to build a wrapper pytest plugin?如何构建包装 pytest 插件?
【发布时间】:2020-04-28 15:27:45
【问题描述】:

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

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

我能够通过实现pytest_addoption(parser) 函数来添加选项,但在第二件事上卡住了......

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

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

【问题讨论】:

  • 你真的需要它吗?为什么不report.config.getoption("myoption")?报表对象不可用的唯一挂钩是 pytest_html_results_table_header,但您可以使用其他四个挂钩中的任何一个。
  • 谢谢!这实际上是我首先尝试的方式,但报告是一个 TestReport 对象,并且没有“config”成员。只有 HTMLReport 有“配置”...
  • 确实,你是对的 - 那么让我添加一个答案。

标签: python pytest pytest-html


【解决方案1】:

您可以将其他数据附加到报告对象,例如通过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

【讨论】:

  • 而且这种方式比在pytest_configure()中声明一个全局并为其赋值要好?
  • 你的意思是模块全局变量?我会避免这种情况——首先,pytest 不鼓励这样做,其次,你不可能想到全局可能导致的所有影响;考虑通过xdist 和其他东西并行运行测试。
猜你喜欢
  • 1970-01-01
  • 2020-05-24
  • 2023-01-27
  • 2021-09-08
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多