dastan12
dastan12

Reputation: 25

How to take screenshot on test error using pytest selenium

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)

Upvotes: 1

Views: 834

Answers (1)

Teejay Bruno
Teejay Bruno

Reputation: 2159

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)

Upvotes: 2

Related Questions