微信小程序自动化测试pytest版-失败截图

2615 篇文章 26 订阅
2196 篇文章 14 订阅

截图

在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}")

最后:在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助。 【保证100%免费】

软件测试面试刷题

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值