装饰器
在接口自动化中装饰器可以帮助简化代码、提高代码可维护性和可重复性的工具。
常用的装饰器介绍:
1.日志记录装饰器(log_decorator):
日志记录装饰器用于记录函数或方法的调用信息,包括输入参数和返回结果,大部分用于调试和排拆问题。
#直接调用log_decorator
@log_decorator
2.时间装饰器(timeout_decorator):
用于设置函数或方法的最大执行时间,防止长时间运行导致接口错误。
#先导入timeout_decorator
import timeout_decorator
@timeout_decorator.timeout(10) #设置最大执行时间10秒
3.重试装饰器(retrying)
用于在函数或方法失败时自动重试,增加接口自动化测试稳定性。
#先导入retrying
import retrying
@retrying.retry(stop_max_attempt_number = 5) #最多重试5次
4.数据驱动装饰器(data_driven)
用于通过不同的输入数据多次运行同一个测试用例,增加测试的覆盖率。
@data_driven
5.缓存装饰器(functools)
用于缓存函数或方法的结果,减少重复计算,提高性能
#导入缓存装饰器
import functools
@functools.lru_cache(maxsize = None) #设置缓存大小为无限
6.参数检查装饰器(check_input_args)
检查函数或方法的输入参数是否符合预期,提前发现错误。
@check_input_args
7.认证装饰器(authenticate)
在执行接口自动化测试前进行身份认证,确保测试环境安全性。
@authenticate("user","psw")
8.计时装饰器(timing_decorator)
记录函数或方法的执行时间,用来评估性能和优化代码。
@timing_decorator
9.接口模拟装饰器(mock_interface)
用来模拟接口的返回数据。
@mock_interface
10.日志文件装饰器(log_to_file)
用于将函数或方法的执行日志记录到文件中,方便查看和分析。
def log_to_file(log_file):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
with open(log_file, "a") as file:
file.write(f"{func.__name__} 执行结果:{result}\n")
return result
return wrapper
return decorator
@log_to_file("test.log")
def test_interface():
# 执行接口测试的代码,将执行结果记录到test.log文件中