selenium+pytest+allure用例失败自动截图
pytest 有个很好的钩子函数 pytest_runtest_makereport 可以获取到用例执行的结果,所以我们在这个钩子函数里面判断用例失败后截图就可以了。
@pytest.hookimpl作用
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
-
该装饰器作用于pytest的钩子函数上,可以获取到测试用例不同执行阶段的结果(setup,call,teardown)
-
可以获取钩子方法的调用结果(返回一个result对象)和调用结果的测试报告(返回一个report对象)
在钩子函数装饰器的yield处,Pytest将执行下一个钩子函数实现,并以Result对象的形式,封装结果或异常信息的实例的形式将其结果返回到yield处。因此,yield处通常本身不会抛出异常(除非存在错误)
在 conftest.py 文件写用例执行的钩子函数
# 调用上一个用例的运行结果
@pytest.fixture(scope='function')
def last_result():
return case_result
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""
每个测试用例执行后,制作测试报告
:param item:测试用例对象
:param call:测试用例的测试步骤
执行完常规钩子函数返回的report报告有个属性叫report.when
先执行when=’setup’ 返回setup 的执行结果
然后执行when=’call’ 返回call 的执行结果
最后执行when=’teardown’返回teardown 的执行结果
:return:
"""
# 执行所有其他钩子以获取报告对象
# 获取常规钩子方法的调用结果,返回一个result对象
outcome = yield
# 获取调用结果的测试报告,返回一个report对象, report对象的属性包括when(steup, call, teardown三个值)、nodeid(测试用例的名字)、outcome(用例的执行结果,passed,failed)
rep = outcome.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(root_path+"failures", mode) as f:
if "tmpdir" in item.fixturenames:
extra = " (%s)" % item.funcargs["tmpdir"]
else:
extra = ""
f.write(rep.nodeid + extra + "\n")
with allure.step('添加失败截图...'):
allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)
allure报告添加截图可以使用 allure.attach 方法
测试用例 test_login.py
import allure
import pytest
from page.login_page import LoginPage
from common.config import WebConfig
@allure.feature("登录")
class TestLogin:
@allure.title("登录"+WebConfig.username)
def test_login(self, browser):
page = LoginPage(browser)
with allure.step("打开首页"):
page.open(WebConfig.url)
with allure.step("点击打开登录页面"):
page.login_a.click()
with allure.step("输入用户名"):
page.username_input = WebConfig.username
with allure.step("输入密码"):
page.password_input = WebConfig.password
with allure.step("点击登录按钮"):
page.login_span.click()
with allure.step("断言主页顶部栏用户名"):
assert page.username_span.text == WebConfig.username
if __name__ == '__main__':
pytest.main(["-s", "test_login.py"])
这里username故意写错 username = “chenlq”
运行用例后,截图会存到./report 报告目录,allure报告展示如下:
评论