创建与兼容的装饰器pytest.mark.parametriz参数

2024-04-26 21:11:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为用pytest编写的测试创建一个装饰器。我的问题是,在调用decorator时,pytest引发了一个异常,decorator没有参数“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?你知道吗


Tags: test示例参数returnpytestexampledefcreate
1条回答
网友
1楼 · 发布于 2024-04-26 21:11:31

这是因为decorator_example用具有完全不同签名的包装函数create替换了test_1函数,打破了pytest自省(例如,检查create是否有参数test_params失败,因为只有*args**kwargs可用)。您需要使用^{}来模拟包装函数的签名:

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兼容性

您可以使用^{}包。按常规安装

$ pip install decorator

上面的例子是:

import decorator


def decorator_example(fn):
    def create(fn, *args, **kwargs):
        return fn(*args, **kwargs)
    return decorator.decorator(create, fn)

或使用^{}

import six


def decorator_example(fn):

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

    return create

相关问题 更多 >