我正在使用pytest与pytest-html模块生成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
而不是硬编码?
使用类范围的fixture来显示生成的HTML不是正确的方法,因为pytest-html
将报告生成挂钩到会话终结器范围,这意味着在调用类终结器时仍然不会生成报告,您可能需要刷新实际查看报告的浏览器页面。如果它似乎工作,那只是因为浏览器窗口可能需要一些额外的秒才能打开,这可能允许报告生成在文件加载到浏览器时完成。
在this answer中解释了正确的方法,并归结为使用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")))