【发布时间】:2017-10-13 12:40:20
【问题描述】:
我正在使用带有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?
⚠️ 更新
使用类范围的夹具来显示生成的 HTML 不是正确的方法,因为pytest-html 将报告生成挂钩到会话终结器范围,这意味着在调用类终结器时报告仍未生成,并且您可能需要刷新浏览器页面才能真正看到报告。如果它似乎可以工作,那只是因为浏览器窗口可能需要一些额外的时间才能打开,这可能会在文件加载到浏览器中时完成报告生成。
this answer 中解释了正确的方法,归结为使用 pytest_unconfigure 钩子。
【问题讨论】:
标签: python pytest pytest-html