实现该功能要用到pytest中的hook函数(钩子函数),如下:
可直接使用该代码
# 用例失败后自动截图
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""
获取用例执行结果的钩子函数
:param item:
:param call:
:return:
"""
outcome = yield
report = outcome.get_result()
if report.when == "call" and report.failed:
mode = "a" if os.path.exists("failures") else "w"
with open("failures", mode)as f:
if "tmpir" in item.fixturenames:
extra = " (%s)" % item.funcargs["tmpdir"]
else:
extra = ""
f.write(report.nodeid + extra + "\n")
with allure.step('添加失败截图...'):
allure.attach(driver.get_screenshot_as_png(), "失败截图",