Home > Software engineering >  How to take screenshot on test error using pytest selenium
How to take screenshot on test error using pytest selenium

Time:08-31

I have pytest hoook that takes screenshots on test failure. For the tests with failed status selenium takes a screenshot. However, when the test fails inside pytest fixture the test status is error, and selenium does not take a screenshot. How to take a screenshot when a test fails on a fixture?

This is a pytest hook that takes screenshots on test failure.

def pytest_runtest_makereport(item, call):
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()

    if report.when == "call":
        xfail = hasattr(report, "wasxfail")
        if (report.skipped and xfail) or (report.failed and not xfail):
            time.sleep(1)
            DRIVER.save_screenshot(screenshot_file)

CodePudding user response:

Currently you're only checking if the report was generated during the call phase, which is the test function.

Including the setup phase, which is any fixture executed before your test, should solve the issue --

def pytest_runtest_makereport(item, call):
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()

    if report.when in ("setup", "call"):
        xfail = hasattr(report, "wasxfail")
        if (report.skipped and xfail) or (report.failed and not xfail):
            time.sleep(1)
            DRIVER.save_screenshot(screenshot_file)
  • Related