Pytest:测试运行后如何显示生成的报告? [英] Pytest: how to display generated report after test run?

查看:54
本文介绍了Pytest:测试运行后如何显示生成的报告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 pytest 与 pytest-html 插件结合使用,该插件生成一个测试运行后的 HTML 报告.

I am using pytest in combination with the pytest-html plugin which generates an HTML report after the test has run.

我正在使用自动连接的会话装置在浏览器中自动打开生成的 HTML 报告:

I am using an auto-wired session fixture to automatically open the generated HTML report in a browser:

@pytest.fixture(scope="session", autouse=True)
def session_wrapper(request):
    print('Session wrapper init...')
    yield

    # open report in browser on Mac or Windows, skip headless boxes
    if platform.system() in ['Darwin', 'Windows']:
        html_report_path = os.path.join(request.config.invocation_dir.strpath, request.config.option.htmlpath)
        open_url_in_browser("file://%s" %html_report_path)

上面的代码有效,但不一致,因为有时浏览器会在创建文件之前尝试加载文件,这会导致文件未找到错误,并且需要手动刷新浏览器才能显示报告.

The code above works, but not consistently, because sometimes the browser attempts to load the file before it is created which results in a file not found error, and requires a manual browser refresh in order for the report to be shown.

我的理解是 scope="session" 是最广泛的可用范围,我的假设是 pytest-html 应该在会话结束之前完成生成报告,但显然不是案例.

My understanding is that scope="session" is the widest available scope, and my assumption was that pytest-html should finish generating the report before the end of the session, but apparently that is not the case.

问题是:钩住浏览器报告自动启动代码的正确方法是什么?难道 pytest-html 也挂钩到会话终结器作用域?在这种情况下,如何确保 HTML 文件只有在创建文件后才能在浏览器中打开?

The question is: what would be the correct way to hook the browser report auto-launch code? Could it be that pytest-html is also hooking into the session finalizer scope? In that case how to make sure that the HTML file is open in the browser only after the file has been created?

推荐答案

正如 massimo 所暗示的那样,一个可能的解决方案是使用 hook,特别是 pytest_unconfigure 可以放在conftest.py 以便它可用于所有测试.

As helpfully hinted by massimo, a possible solution is to use a hook, specifically pytest_unconfigure which can be placed in conftest.py so that it is available for all tests.

def pytest_unconfigure(config):
    if platform.system() in ['Darwin', 'Windows']:
        html_report_path = os.path.join(config.invocation_dir.strpath, config.option.htmlpath)
        open_url_in_browser("file://%s" % html_report_path)

这篇关于Pytest:测试运行后如何显示生成的报告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆