Pytest HTML 报告:如何获取报告文件的名称?

Pytest HTML report: how to get the name of the report file?

我正在使用带有 pytest-html 模块的 pytest 来生成 HTML 测试报告。

在拆卸阶段,我使用 webbrowser.open('file:///path_to_report.html') 在浏览器中自动打开生成的 HTML 报告 — 这工作正常,但我是 运行 具有不同参数和对于每组参数,我通过命令行参数设置不同的报告文件:

pytest -v mytest.py::TestClassName --html=report_localhost.html

我的拆解代码如下所示:

@pytest.fixture(scope='class')
def config(request):
    claz = request.cls
    claz.host = request.config.getoption("--host", default=HOST_DEFAULT)
    ...

    def teardown_env():
        print('destroying test harness')
        webbrowser.open("file:///path_to_report_localhost.html")

    request.addfinalizer(teardown_env)

    return "prepare_env"

问题是如何从测试中的拆卸挂钩访问报告文件名,这样我就可以使用传入的任何路径作为命令行参数,而不是对其进行硬编码,即 --html=report_for_host_xyz.html?

⚠️更新

使用 class-scoped fixture 来显示生成的 HTML 不是正确的方法,因为 pytest-html 将报告生成挂接到会话终结器范围,这意味着到时候class 终结器被调用 报告仍未生成,您可能需要刷新浏览器页面才能真正看到报告。如果它 似乎 工作,那只是因为浏览器 window 可能需要额外几秒钟才能打开,这可能允许报告生成在文件加载到浏览器。

this answer and boils down to using the pytest_unconfigure 钩子中解释了正确的方法。

你可以在夹具中放置一个断点,然后查看 request.config.option 对象——这是 pytest 放置所有 argparsed 键的地方。

您要查找的是request.config.option.htmlpath

@pytest.fixture(scope='class')
def config(request):
    claz = request.cls
    claz.host = request.config.getoption("--host", default=HOST_DEFAULT)

    yield 100   # a value of the fixture for the tests

    print('destroying test harness')
    webbrowser.open("file:///{}".format(request.config.option.htmlpath))

或者您可以对 --host 键执行相同的操作:

@pytest.fixture(scope='class')
def config(request):
    claz = request.cls
    claz.host = request.config.getoption("--host", default=HOST_DEFAULT)

    yield 100   # a value of the fixture for the tests

    print('destroying test harness')
    webbrowser.open("file:///{}".format(request.config.getoption("--html")))