You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将setup变量传入pytest测试方法的my_decorator装饰器

解决方案

首先要明确核心限制:装饰器是在类定义阶段就被执行的,这时候测试类的实例(self)还没创建,setup夹具也没运行,cluster_details和account_details根本不存在。所以不能直接在装饰器参数里写self.cluster_details,必须用延迟获取的思路。

方案1:修改装饰器,支持从实例读取属性

这是最直接的方案,调整装饰器逻辑,让它先接收要获取的属性名称,等测试函数执行时再从self里取真实值:

调整后的装饰器实现
def my_decorator(attr_names):
    def decorator(func):
        def wrapper(self, *args, **kwargs):
            # 从测试实例self中取出指定属性的值
            target_params = tuple(getattr(self, attr) for attr in attr_names)
            # 这里用target_params替代原来的('arg1','arg2')执行装饰器逻辑
            print(f"装饰器获取到的参数:{target_params}")
            # 执行原测试函数
            return func(self, *args, **kwargs)
        return wrapper
    return decorator
测试类中使用

直接传入要读取的属性名称字符串:

class TestXYZ:
    @pytest.fixture(scope="function", autouse=True)
    def setup(self, before_function, after_function, test_details):
        self.cluster_details, self.account_details, self.application_details, self.testrail_details = test_details

    # 传入属性名,代替原来的固定参数
    @my_decorator(('cluster_details', 'account_details'))
    def test_1495990_verify_sensor_device_status(self,print_arguments): 
        """
        Step 1 :: Precondition
        - Adding Device to workspace
        """
        print('test started')

方案2:无法修改装饰器时的替代方案

如果my_decorator是第三方库提供的,不能修改源码,那可以把参数通过夹具提前取出,然后在测试函数内部手动触发装饰器逻辑:

class TestXYZ:
    @pytest.fixture(scope="function", autouse=True)
    def setup(self, before_function, after_function, test_details):
        self.cluster_details, self.account_details, self.application_details, self.testrail_details = test_details

    # 新增夹具提前获取参数
    @pytest.fixture(scope="function")
    def decorator_args(self):
        return (self.cluster_details, self.account_details)

    def test_1495990_verify_sensor_device_status(self, print_arguments, decorator_args):
        # 手动调用装饰器逻辑,传入动态获取的参数
        my_decorator(decorator_args)(lambda: None)()
        print('test started')

这种方式等于放弃了装饰器的语法糖,优先推荐方案1。


内容的提问来源于stack exchange,提问作者Shashank Jyotishi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 20:02:42