最近做webUI自动化时,希望用例执行失败的时候,可以自动截图,以便于判断失败原因
pytest 有个很好的钩子函数 pytest_runtest_makereport 可以获取到用例执行的结果,所以我们在这个钩子函数里面判断用例失败后截图就可以了。
allure报告添加截图可以使用 allure.attach 方法
在 conftest.py 文件写用例执行的钩子函数
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""
获取每个用例状态的钩子函数
:param item: 测试用例
:param call: 测试步骤
:return:
"""
# 获取钩子方法的调用结果
out_come = yield
rep = out_come.get_result() # 从钩子方法的调用结果中获取测试报告
# rep.when表示测试步骤,仅仅获取用例call 执行结果是失败的情况, 不包含 setup/teardown
if rep.when == "call" and rep.failed:
mode = "a" if os.path.exists("failures") else "w"
with open("failures", mode) as f:
if "tmpdir" in item.fixturenames:
extra = " (%s)" % item.funcargs["tmpdir"]