pytest:试运行后如何显示生成的报告?

时间:2018-08-27 05:13:14

标签: python report pytest pytest-html

我将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)

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

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

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

3 个答案:

答案 0 :(得分:1)

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

过去我对他们做过一些有趣的事情,不幸的是,我不记得跑步结束时是否打来电话,但可能是

答案 1 :(得分:1)

massimo很有帮助地暗示,一种可能的解决方案是使用hook,特别是pytest_unconfigure,可以将其放置在 ButtonTheme( minWidth: 16.0, height: 30.0, child: RaisedButton( padding: const EdgeInsets.all(8.0), onPressed:()=>print("a"), child: new Row( children: <Widget>[ Padding( padding: const EdgeInsets.only(right: 6.0), child: Icon(Icons.filter,size: 16.0,), ), Text('FILTER',style: TextStyle(fontSize: 12.0),), ], ), ), ), 中,以便所有测试都可以使用

conftest.py

答案 2 :(得分: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.logfile实际上是pytest-html的文件名。 pytest-html的配置挂钩完成后即可访问,因此我又使用了trylast=True
相关问题