截图
在mini中截图使用的是screenshot_pic
方法
-
@allure.step("截图并存放到「{path}」中")
-
def screenshot_pic(self, path: str):
-
self.native.screen_shot(path)
两种断言方式
在编写测试用例的时候会使用到两种断言方式
-
# 常规方式
-
assert False, '错误描述'
-
# 多重断言 使用pytest-assume插件
-
pytest.assume(False, '错误描述')
常规方式断言失败截图
常规方式断言会在用例执行失败后结束当前用例,所以使用pytest自带的钩子:pytest_runtest_makereport
-
@hookspec(firstresult=True)
-
def pytest_runtest_makereport(
-
item: "Item", call: "CallInfo[None]"
-
) -> Optional["TestReport"]:
-
"""Called to create a :class:`~pytest.TestReport` for each of
-
the setup, call and teardown runtest phases of a test item.
-
See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
-
:param item: The item.
-
:param call: The :class:`~pytest.CallInfo` for the phase.
-
Stops at first non-None result, see :ref:`firstresult`.
-
"""
它会在用例执行完成后进入
在执行后判断一下当前case是否失败或异常,如果是则截图
所以当一个对象有native对象时,它就能进行截图
使用item.funcargs.items()从堆栈中找到包含native对象的对象,然后进行截图
-
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
-
def pytest_runtest_makereport(item, call):
-
"""
-
pytest 失败后执行
-
:param item: 测试用例
-
:param call: 测试步骤
-
:return:
-
"""
-
out = yield
-
result = out.get_result()
-
if result.outcome in ['failed', 'error']:
-
for k, v in item.funcargs.items():
-
try:
-
if hasattr(v, 'native'):
-
attach_png(f'{Constant().TEST_PIC}/{int(time.time())}.png', "失败截图", v)
-
break
-
except Exception as e:
-
logger.error(f"失败截图异常:{e}")
多重断言失败截图
在pytest_assume插件中有一个hook:pytest_assume.hooks.pytest_assume_fail
-
def pytest_assume_fail(lineno, entry):
-
"""
-
Hook to manipulate user-defined data in-case of assumption failure.
-
lineno: Line in the code from where asumption failed.
-
entry: The assumption failure message generated from assume() call
-
"""
-
pass
当assume第一个参数是False时,它就会进入pytest_assume_fail钩子
同上,找到包含native对象的对象,然后进行截图
-
def pytest_assume_fail(lineno, entry):
-
"""
-
assume 断言报错截图
-
"""
-
for i in inspect.stack():
-
if os.path.split(i.filename)[1].startswith('test_'):
-
try:
-
for k, v in i.frame.f_locals.items():
-
if hasattr(v, 'native'):
-
attach_png(f'{Constant().TEST_PIC}/{int(time.time())}.png', f"失败截图_{int(time.time())}", v)
-
break
-
except Exception as e:
-
logger.error(f"失败截图异常:{e}")
感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:
这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!有需要的小伙伴可以点击下方小卡片领取