gpt4 book ai didi

python - Pytest HTML 报告 : how to get the name of the report file?

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:29 30 4
gpt4 key购买 nike

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

在拆卸阶段,我自动在浏览器中打开生成的 HTML 报告 webbrowser.open('file:///path_to_report.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"

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

⚠️更新

使用类范围的固定装置来显示生成的 HTML 不是正确的方法,因为 pytest-html将报告生成 Hook 到 session 终结器范围中,这意味着当调用类终结器时,报告仍未生成,您可能需要刷新浏览器页面才能实际查看报告。如果它似乎有效,那只是因为浏览器窗口可能需要额外几秒钟的时间才能打开,这可能会在文件加载到浏览器中时完成报告生成。

this answer 中解释了正确的操作方法。归结为使用 pytest_unconfigure 钩子(Hook)。

最佳答案

您可以在装置中放置一个断点,然后查看 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")))

关于python - Pytest HTML 报告 : how to get the name of the report file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46730180/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com