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

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

一、前置说明


自动化测试时,经常会遇到页面和元素未加载完成,从而造成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. 
目录
相关文章
|
12天前
在使用async/await时,如果异步操作本身没有抛出错误,但是在后续的同步代码中出现了错误,该如何处理?
在使用async/await时,如果异步操作本身没有抛出错误,但是在后续的同步代码中出现了错误,该如何处理?
81 57
|
8月前
|
Java Spring
@Async注解导致循环依赖,BeanCurrentlyInCreationException异常
@Async注解导致循环依赖,BeanCurrentlyInCreationException异常
|
8月前
|
关系型数据库 MySQL Serverless
函数计算产品使用问题之触发器不能正常触发函数执行怎么办
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
|
10月前
|
Java 测试技术 数据库
你遇到过哪些触发NPE的代码场景?
【5月更文挑战第18天】空指针异常(NPE)是开发过程中常见的障碍,它不仅阻碍了代码的正常运行,还常常成为系统不稳定性的根源。本文讲述关于如何避免NPE的一些看法。
|
前端开发
13 # promise 的状态更改问题
13 # promise 的状态更改问题
74 0
|
10月前
|
存储
在actions中如何处理异步操作的错误
在Vuex的`actions`中,处理异步操作错误通常涉及捕获和处理。使用`try-catch`块能捕获如`axios`请求可能抛出的错误。
|
前端开发
前端学习案例-严格模式2-对象的静默失败
前端学习案例-严格模式2-对象的静默失败
95 0
前端学习案例-严格模式2-对象的静默失败
【异常机制】异常抛出变量的生命周期
【异常机制】异常抛出变量的生命周期
84 0
【异常机制】异常抛出变量的生命周期
setSupportActionBar()方法报错
今天在使用Tollbar替换标题栏时,出现了这样的错误
90 0
setSupportActionBar()方法报错
|
Java 测试技术 持续交付
老司机使用CompletableFuture实现集成任务失败后自动重跑
0 老司机集成任务在Aone实验室中遇到的问题  老司机平台是一个集合了用例管理,用例执行,测试沉淀等功能的一站式集成测试平台。老司机中提供了一种名为集成任务的测试件,它一般包含一组核心的可执行用例,主要在变更发布前回归指定的接口或应用时由平台或手工触发运行。也可以在每日定时执行指定的集成任务,以实现用例与测试任务的持续集成。  集成任务用作发布前的卡点测试件时,一般是在流水线中加入Aone实验室
1459 1
老司机使用CompletableFuture实现集成任务失败后自动重跑