使用Decorator进行数据驱动测试

时间:2013-04-27 13:40:35

标签: python decorator

我正在尝试使用装饰器参数化一个函数。最后,我能够在经过大量的打击和试验后按预期运行。但是我仍然不满意它似乎正在工作,它似乎不是正确的方法。

请帮我改进此代码。

这是我的代码:

def WarmWelcome(fn):
    def wrapped(DataProvider):
       for name in DataProvider(): 
         print fn(name) + ":)"
    return wrapped

def DataProvider():
    names=["abc","xyz","def"]
    for name in names:
        yield name

@WarmWelcome
def hello(name):
    return "hello " +name

hello(DataProvider) 

以下是更新后的代码:

def WarmWelcome(DataProvider):
  def real_decorator(fn):
    def wrapped():
       for name in DataProvider(): 
         print fn(name) + ":)"
    return wrapped
  return real_decorator

def DataProvider():
    names=["abc","xyz","def"]
    for name in names:
        yield name
@WarmWelcome(DataProvider)
def hello(name):
    return "hello " +name

hello() 

1 个答案:

答案 0 :(得分:1)

还可以向WarmWelcome装饰者提供数据集权利:

def WarmWelcome(*data_sets):
    def _decorator(func):
        def _func():
            for ds in data_sets:
                func(*ds)
        return _func
    return _decorator

@WarmWelcome(
    ("abc", ),
    ("xyz", ),
    ("def", ),
)
def hello(name):
    return "hello " +name

原文:PHPUnit-like dataProvider implementation for Python unittest