简单分享下Python装饰器

示例 1: 日志记录装饰器

实际使用场景: 在接口测试中记录每个测试函数的调用情况。

import loggingdef log_function_call(func):    def wrapper(*args, **kwargs):        logging.basicConfig(level=logging.INFO)        logger = logging.getLogger(__name__)        logger.info(f"Calling function {func.__name__} with args: {args}, kwargs: {kwargs}")        result = func(*args, **kwargs)        logger.info(f"Function {func.__name__} returned: {result}")        return result    return wrapper@log_function_calldef test_api_endpoint(url):    # 这里可以是调用API的逻辑    print(f"Testing endpoint at {url}")test_api_endpoint("https://example.com/api")

图片

图片

示例 2: 性能测量装饰器

实际使用场景: 测量接口测试函数的执行时间。

import timedef measure_time(func):    def wrapper(*args, **kwargs):        start_time = time.time()        result = func(*args, **kwargs)        end_time = time.time()        print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds to run.")        return result    return wrapper@measure_timedef test_api_performance(url):    # 这里可以是调用API的逻辑    print(f"Testing performance of endpoint at {url}")test_api_performance("https://example.com/api")

图片

图片

示例 3: 异常处理装饰器

实际使用场景: 捕获并处理接口测试中的异常。

import requestsdef handle_exceptions(func):    def wrapper(*args, **kwargs):        try:            return func(*args, **kwargs)        except Exception as e:            print(f"An error occurred in {func.__name__}: {e}")            return None    return wrapper@handle_exceptionsdef test_api_with_exceptions(url):    response = requests.get(url)    if response.status_code == 200:        print("Request successful")    else:        raise Exception(f"Request failed with status code {response.status_code}")test_api_with_exceptions("https://example.com/api")

图片

图片

示例 4: 重试机制装饰器

实际使用场景: 当接口测试失败时自动重试一定次数。

​​​​​​​

import requestsdef retry(max_retries=3):    def decorator(func):        def wrapper(*args, **kwargs):            for attempt in range(max_retries):                try:                    return func(*args, **kwargs)                except Exception as e:                    if attempt < max_retries - 1:                        print(f"Attempt {attempt + 1} failed, retrying...")                    else:                        print(f"Max retries ({max_retries}) reached, last error: {e}")                        return None        return wrapper    return decorator@retry(max_retries=3)def test_api_with_retry(url):    response = requests.get(url)    if response.status_code == 200:        print("Request successful")    else:        raise Exception(f"Request failed with status code {response.status_code}")test_api_with_retry("https://example.com/api")

图片

图片

示例 5: 验证响应状态码装饰器

实际使用场景: 确保接口返回预期的状态码。

import requestsdef validate_status_code(expected_status=200):    def decorator(func):        def wrapper(*args, **kwargs):            response = func(*args, **kwargs)            if response.status_code == expected_status:                print(f"Status code is as expected: {response.status_code}")            else:                raise Exception(f"Unexpected status code: {response.status_code}")            return response        return wrapper    return decorator@validate_status_code(expected_status=200)def test_api_status(url):    return requests.get(url)test_api_status("https://example.com/api")

图片

图片

示例 6: 参数验证装饰器

实际使用场景: 在接口测试中验证输入参数的有效性。

def validate_params(*param_names, **param_types):    def decorator(func):        def wrapper(*args, **kwargs):            for name in param_names:                if name not in kwargs:                    raise ValueError(f"Missing required parameter: {name}")            for name, type_ in param_types.items():                if name in kwargs and not isinstance(kwargs[name], type_):                    raise TypeError(f"Parameter {name} must be of type {type_.__name__}")            return func(*args, **kwargs)        return wrapper    return decorator@validate_params("url", url=str)def test_api_with_params(url):    print(f"Testing endpoint at {url}")test_api_with_params(url="https://example.com/api")

图片

图片

示例 7: 限制调用频率装饰器

实际使用场景: 限制接口测试函数的调用频率,避免过载服务器。

import timedef limit_calls(max_calls_per_minute=60):    def decorator(func):        call_times = []        def wrapper(*args, **kwargs):            current_time = time.time()            while len(call_times) > 0 and current_time - call_times[0] > 60:                call_times.pop(0)            if len(call_times) >= max_calls_per_minute:                raise Exception("Maximum calls per minute exceeded")            call_times.append(current_time)            return func(*args, **kwargs)        return wrapper    return decorator@limit_calls(max_calls_per_minute=60)def test_api_limit_calls(url):    print(f"Testing endpoint at {url}")for _ in range(61):    test_api_limit_calls(url="https://example.com/api")    time.sleep(1)

图片

图片

示例 8: 数据驱动测试装饰器

实际使用场景: 执行多次接口测试,每次使用不同的测试数据。

def data_driven_test(test_data):    def decorator(func):        def wrapper():            for data in test_data:                func(**data)        return wrapper    return decorator@test_data([    {"url": "https://example.com/api1"},    {"url": "https://example.com/api2"}])def test_api_multiple_urls(url):    print(f"Testing endpoint at {url}")test_api_multiple_urls()

图片

图片

示例 9: 环境配置装饰器

实际使用场景: 根据不同的环境配置(如开发、测试、生产)调用不同的API端点。

def configure_environment(environment="dev"):    environments = {        "dev": "https://dev.example.com",        "test": "https://test.example.com",        "prod": "https://api.example.com"    }    def decorator(func):        def wrapper(*args, **kwargs):            base_url = environments.get(environment, "https://default.example.com")            kwargs["base_url"] = base_url            return func(*args, **kwargs)        return wrapper    return decorator@configure_environment(environment="test")def test_api_with_environment(base_url, endpoint):    print(f"Testing endpoint at {base_url}/{endpoint}")test_api_with_environment(endpoint="api")

图片

图片

示例 10: 并发执行装饰器

实际使用场景: 并发执行接口测试,以提高测试效率。

import concurrent.futuresdef concurrent_execute(max_workers=5):    def decorator(func):        def wrapper(*args, **kwargs):            with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:                futures = [executor.submit(func, *arg, **kwarg) for arg, kwarg in zip(args, kwargs)]                concurrent.futures.wait(futures)        return wrapper    return decorator@concurrent_execute(max_workers=5)def test_api_concurrently(url):    print(f"Testing endpoint at {url}")urls = ["https://example.com/api1", "https://example.com/api2", "https://example.com/api3"]test_api_concurrently(urls)
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小软件大世界

谢谢支持,我将会更加努力的寻找

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值