一、前置说明
在自动化测试时,经常会遇到页面和元素未加载完成,从而造成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.