Pytest: how to display generated report after test run?

自闭症网瘾萝莉.ら 提交于 2019-12-06 15:26:22

Instead of using fixtures you may try using hooks.

In the past I did something interesting with them, unfortunately I don't remember if there's called at the very end of the run but probably yes

In your 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)

Notes:

  • pytest-html writes the report in pytest_sessionfinish hook, so you will need a custom sessionfinish hook. Mark it with trylast=True to ensure your hook impl runs after pytest-html's one.
  • config.option.htmlpath is what is passed via --html-path command line argument; config._html.logfile is what pytest-html actually uses as file name. It's accessible after pytest-html's configure hook finishes, so I used trylast=True one more time.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!