Skip to main content
 首页 » 编程设计

python之创建与 pytest.mark.parametrize 兼容的装饰器

2024年11月24日8sky-heaven

我想为我用 pytest 编写的测试创建一个装饰器。我的问题是,调用装饰器时,pytest 会引发装饰器没有参数“test_params”的异常。

装饰器示例:

def decorator_example(fn): 
 
    def create(*args, **kwargs): 
        # any code here 
        return fn(*args, **kwargs) 
 
return create 

测试示例:
@pytest.mark.parametrize( 
    "test_params", 
    [ 
        pytest.param("own_parameters") 
    ]) 
@decorator_example 
def test_1(self, fixture1, fixture2, test_params): 
    pass 

并捕获异常:
ValueError: <function create at address> uses no argument 'test_params' 

如何创建一个与 pytest 的参数化测试兼容的装饰器?

请您参考如下方法:

那是因为 decorator_example替换 test_1带有包装函数的函数create具有完全不同的签名,打破 pytest内省(introspection)(例如,检查 create 是否有参数 test_params 失败,因为只有 *args 和 **kwargs 可用)。您需要使用 functools.wraps 模仿包装函数的签名:

import functools 
 
 
def decorator_example(fn): 
 
    @functools.wraps(fn)     
    def create(*args, **kwargs): 
        # any code here 
        return fn(*args, **kwargs) 
 
    return create 

Python 2.7 兼容性

您可以使用 decorator 包裹。照常安装
$ pip install decorator 

上面的例子将是:
import decorator 
 
 
def decorator_example(fn): 
    def create(fn, *args, **kwargs): 
        return fn(*args, **kwargs) 
    return decorator.decorator(create, fn) 

或使用 six :
import six 
 
 
def decorator_example(fn): 
 
    @six.wraps(fn)     
    def create(*args, **kwargs): 
        # any code here 
        return fn(*args, **kwargs) 
 
    return create