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

时间:2017-10-13 12:40:21

标签: python pytest pytest-html

我正在使用带有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

⚠️更新

使用类范围的fixture来显示生成的HTML不是正确的方法,因为pytest-html将报告生成挂钩到会话终结器范围,这意味着在调用类终结器时,报告仍然不是已生成,您可能需要刷新浏览器页面才能实际查看报告。如果它似乎只是因为浏览器窗口可能需要一些额外的秒才能打开,这可能允许报告生成在文件加载到浏览器时完成。 / p>

this answer中解释了执行此操作的正确方法,并归结为使用pytest_unconfigure挂钩。

1 个答案:

答案 0 :(得分:1)

你可以在灯具中加一个断点,并查看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")))
相关问题