实现该功能要用到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(), "失败截图", allure.attachment_type.PNG)
但是需要注意的是在conftest.py中初始化的时候需要中driver的使用,如果不处理截图函数将不能使用
可以看到上面截图需要先用到driver,但是这个函数中又没有定义,我们进行如下处理: