【问题标题】:Decorator over a nose test case that yields一个鼻子测试用例上的装饰器,产生
【发布时间】:2016-03-02 15:22:46
【问题描述】:

我有以下装饰器,它应该将测试用例函数的实现包装在 try/except 块中,并在发生异常时打印日志。

def print_log(test_case):
    @wraps(test_case)
    def run_test(self):
        try:
            test_case(self)
        except:
            Test_Loop.failure_teardown(self)
            raise
   return run_test

然而,这似乎不适用于我的一个调用产量生成器的测试用例

请耐心等待,因为这是一个基本示例:

class Test_Loop:
    # ton of implementation here (e.g. initialization, etc)

    def runIt(self, name, ip, port):
        # code here

    @print_log
    def test_log_looper(self):
        for l in self.links:
            # initialize variables seen below and other stuff
            for n in names:
                # do stuff
                for i in ips:
                    # do stuff
                    for p in ports:
                        yield self.runIt, l, n, i, p

从调试来看,在应用装饰器时,似乎连第一个循环都没有进入。我做错了什么?

【问题讨论】:

  • 1.您永远不会真正返回从包装器调用 test_case 的结果。 2. 您实际上也不会在包装器内使用生成器。
  • print_log 调用test_case 只是返回生成器;你没有迭代它。

标签: python decorator yield


【解决方案1】:

您需要遍历您的生成器。像这样修改你的装饰器:

def print_log(test_case):
    @wraps(test_case)
    def run_test(self):
        try:
            for _ in test_case(self): pass
        except:
            Test_Loop.failure_teardown(self)
            raise
   return run_test

【讨论】:

  • 谢谢。我最终将 for 循环移到 try 块之外并在 in 中调用 yield _,因为我希望每次迭代都被包装,但是现在它无法识别何时会发生异常..
  • 您确定需要将其移出试用版吗?如果您保留它,则每次迭代都将被包装到您的 try 语句中。
  • 是的,我希望生成器的每次迭代都包含在 try 中,这样如果有人抛出异常,就会打印日志。但是,我无法相应地完成这项工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 2011-07-31
  • 2015-01-21
相关资源
最近更新 更多