使用装饰器实现一种失败重跑的方法

简介: 使用装饰器实现一种失败重跑的方法

一、前置说明


在自动化测试时,经常会遇到页面和元素未加载完成,从而造成click点击或swipe滑动失败。selenium提供了隐式等待和显示等待的方式,我们也可以自己实现一个更加灵活的失败重跑的方式。


二、代码实现


# decorators.py
import functools
import logging
import time
logger = logging.getLogger(__name__)
def rerun_if_exception(max_attempts=3, interval=0.5, capture_exception=Exception, exclude_exception=TimeoutError):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last_exception = None
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except capture_exception as e:
                    if isinstance(e, exclude_exception):
                        raise e
                    time.sleep(interval)
                    last_exception = e
                    logger.debug(
                        f'Retry attempt {attempt} for method "{func.__name__}" failed. Exception: {last_exception}')
            raise TimeoutError(
                f'Rerun method "{func.__name__}" failed after {max_attempts} attempts. ') from last_exception
        return wrapper
    return decorator


三、Demo验证


# demo.py
from libs.decorators import rerun_if_exception
@rerun_if_exception()
def method_index_error():
    raise IndexError('index error')
@rerun_if_exception()
def method_timeout_error():
    raise TimeoutError('timeout error')
if __name__ == '__main__':
    import logging
    logging.basicConfig(level=logging.DEBUG)
    method_index_error()


输出日志:

DEBUG:libs.decorators:Retry attempt 0 for method "method_index_error" failed. Exception: index error
DEBUG:libs.decorators:Retry attempt 1 for method "method_index_error" failed. Exception: index error
DEBUG:libs.decorators:Retry attempt 2 for method "method_index_error" failed. Exception: index error
Traceback (most recent call last):
  File "D:\BaiduSyncdisk\xyouwen-workspace\ddautotest\libs\decorators.py", line 15, in wrapper
    return func(*args, **kwargs)
  File "D:\BaiduSyncdisk\xyouwen-workspace\ddautotest\libs\demo.py", line 6, in method_index_error
    raise IndexError('index error')
IndexError: index error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "D:\BaiduSyncdisk\xyouwen-workspace\ddautotest\libs\demo.py", line 19, in <module>
    method_index_error()
  File "D:\BaiduSyncdisk\xyouwen-workspace\ddautotest\libs\decorators.py", line 25, in wrapper
    raise TimeoutError(
TimeoutError: Rerun method "method_index_error" failed after 3 attempts. 
目录
相关文章
|
Go 芯片 异构计算
Vivado初体验LED工程 3
Vivado初体验LED工程
615 0
|
12月前
|
边缘计算 运维 前端开发
阿里云 ESA “函数和Pages”全面开放|打通开发者“最后一公里”!
随着云计算技术的不断下沉,从中心云到边缘云的演进已成为不可逆转的趋势。为了满足开发者对更低延迟、更灵活部署以及更低运维成本的极致追求,阿里云 ESA 正式推出了备受期待的「函数和Pages」功能。这一发布标志着阿里云迈出了关键一步——让计算触手可及,让部署快如闪电。
阿里云 ESA “函数和Pages”全面开放|打通开发者“最后一公里”!
|
6月前
|
域名解析 数据采集 运维
Vsping在线Ping:网络链路稳定性监测与深度故障运维排查方案
Vsping在线Ping是一款云端多节点网络诊断工具,突破传统本地Ping局限,支持电信/联通/移动全网覆盖及跨境探测。一键检测延迟、丢包、连通性,可视化呈现结果,零门槛操作,精准定位故障归属,适用于个人自查与企业运维全场景。(239字)
652 0
|
数据采集 存储 前端开发
如何开发门店业绩上报管理系统中的销售日报板块?(附架构图+流程图+代码参考)
门店业绩上报管理系统中的销售日报板块是零售企业管理运营的核心工具。通过汇总当日销售数据,系统帮助管理者实时掌握门店经营状况,提升决策效率和市场竞争力。本文详解销售日报模块的功能设计、业务流程、开发技巧及实现效果,涵盖数据库设计、前端展示、数据采集与分析等内容,助力企业打造高效精准的销售日报系统,实现数据驱动的精细化管理。(239字)
|
6月前
|
人工智能 安全 Anolis
解读《2025龙蜥社区操作系统白皮书》,这四大亮点值得关注
操作系统在 AI 时代该怎么走,龙蜥社区给出的答案已经越来越清晰。
|
安全 物联网 量子技术
量子加密技术
量子加密技术
1622 1
|
Linux 编译器 Shell
Linux系统下实现QT程序打包发布
Linux系统下实现QT程序打包发布
2686 0
|
存储 Kubernetes 算法框架/工具
Kubevirt
Kubevirt
1276 12
|
Linux 文件存储 数据安全/隐私保护
Linux用户组管理实战:创建、管理与删除的全面指南
在 Linux 系统中,用户组管理是实现权限控制和资源共享的关键。本文档详细介绍如何创建用户组、管理用户组成员及查看与删除用户组。首先,通过 `groupadd` 命令创建新用户组,并在 `/etc/group` 文件中记录。接着,利用 `usermod` 和 `gpasswd` 命令来添加或删除用户组成员,其中 `gpasswd` 提供更灵活的管理方式。最后,使用 `getent` 或直接读取 `/etc/group` 查看用户组信息,并通过 `groupdel` 删除空用户组。这些操作有助于高效管理和保护系统资源。
1145 4
|
存储 算法 数据库
人脸识别数据集
人脸识别数据集
2516 155