问题
I am using pytest in combination with the pytest-html plugin which generates an HTML report after the test has run.
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.
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.
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?
回答1:
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
回答2:
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 inpytest_sessionfinish
hook, so you will need a custom sessionfinish hook. Mark it withtrylast=True
to ensure your hook impl runs afterpytest-html
's one.config.option.htmlpath
is what is passed via--html-path
command line argument;config._html.logfile
is whatpytest-html
actually uses as file name. It's accessible afterpytest-html
's configure hook finishes, so I usedtrylast=True
one more time.
回答3:
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)
来源:https://stackoverflow.com/questions/52032885/pytest-how-to-display-generated-report-after-test-run