2

我将 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 文件仅在文件创建后才在浏览器中打开?

4

3 回答 3

2

正如massimo所暗示的那样,一个可能的解决方案是使用一个钩子,特别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)
于 2018-08-27T07:02:31.863 回答
2

在你的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以确保您的钩子 impl 在pytest-html' 之后运行。
  • config.option.htmlpath是通过--html-path命令行参数传递的内容;config._html.logfilepytest-html实际用作文件名的内容。pytest-html'configure hook 完成后可以访问它,所以我又使用trylast=True了一次。
于 2018-08-27T07:25:40.643 回答
1

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

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

于 2018-08-27T06:33:53.163 回答