我想编写一个python装饰器来装饰unittest.TestCase的测试函数,以决定该函数应该运行的目标主机.看这个例子:
class MyTestCase(unittest.TestCase):
@target_host(["host1.com", "host2.com"])
def test_my_command(self):
#do something here against the target host
Run Code Online (Sandbox Code Playgroud)
在装饰函数中,我希望能够对所有主机执行此测试,我该怎么做?target_host的声明应该返回一个新函数,但是可以返回测试运行器可以执行的多个函数吗?
谢谢!
小智 11
您可以只返回一个对象(因此从技术上讲,您可以返回一组函数).如果你想避免惊讶每个人,如果你想调用结果,你最好还是返回一个函数.但是这个函数很可能会在循环中调用其他几个函数...你知道这会导致什么吗?
你需要一个装饰器工厂,它返回一个闭包,调用它们应用于工厂得到的每组参数的函数.在代码中(包括functools.wraps保留名称和文档字符串,可能有用与否,我倾向于默认包含它):
def call_with_each(*arg_tuples):
def decorate(f):
@functools.wraps(f)
def decorator():
for arg_tuple in arg_tuples:
f(*arg_tuple)
return decorator
return decorate
# useage example:
@call_with_each((3,), (2,)) # note that we pass several singleton tuples
def f(x):
print x
# calling f() prints "3\n2\n"
Run Code Online (Sandbox Code Playgroud)
支持关键字参数需要更多代码,也许还有一些丑陋,但这是可能的.如果它总是将是一个参数,代码可以简化(def call_with_each(*args),for arg in args: f(arg),等).
| 归档时间: |
|
| 查看次数: |
3005 次 |
| 最近记录: |