【问题标题】:Pytest: how to display generated report after test run?Pytest:测试运行后如何显示生成的报告?
【发布时间】:2018-08-27 05:13:13
【问题描述】:

我将 pytest 与 pytest-html 插件结合使用,该插件会在测试运行后生成 HTML 报告。

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

@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)

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

我的理解是scope="session" 是最广泛的可用范围,我的假设是 pytest-html 应该在会话结束之前完成生成报告,但显然情况并非如此。

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

【问题讨论】:

  • 为什么要在测试框架内部而不是外部执行此操作?
  • @StephenRauch:因为我想避免在每个调用 pytest 的脚本中明确地这样做。

标签: python report pytest pytest-html


【解决方案1】:

在你的conftest.py:

import pytest

@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    config._htmlfile = config._html.logfile


@pytest.hookimpl(trylast=True)
def pytest_sessionfinish(session, exitstatus):
    file = session.config._htmlfile
    # invoke the file opening in external tool
    os.system('open ' + file)

注意事项:

  • pytest-html 将报告写入 pytest_sessionfinish 钩子,因此您将需要一个自定义 sessionfinish 钩子。用trylast=True 标记它,以确保你的钩子实现在pytest-html 之后运行。
  • config.option.htmlpath 是通过 --html-path 命令行参数传递的; config._html.logfilepytest-html 实际用作文件名的内容。在pytest-html 的配置钩子完成后可以访问它,所以我又使用了trylast=True 一次。

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

    • 恐怕在取消配置挂钩中打开文件还为时过早。仔细检查您不只是打开以前生成的报告。例如。 rm myreport.html && pytest --html=myreport.html.
    • @hoefling:其实调试显示pytest_unconfigure运行之后 pytest_sessionfinishtrylast=True
    • 你说得对,我自己通过pytest --debug 进行了测试。酷,由于某些原因,一直认为unconfiguresessionfinish 之前被调用。因此,您的回答完全有效,请忽略我上面的评论!
    【解决方案3】:

    您可以尝试使用hooks,而不是使用固定装置。

    过去我和他们做过一些有趣的事情,不幸的是我不记得在运行的最后是否有调用,但可能是的

    【讨论】:

    • 这正是我的想法:但问题是哪个钩子最合适? pytest_report_collectionfinish?我看到 pytest-html 挂钩到 pytest_sessionfinish,那么在那之后我将如何挂钩?
    • collection_finish 应该在收集结束时调用,而不是在执行后调用。正如我所说,我现在没有时间检查文档,也许以后会
    猜你喜欢
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多