【问题标题】:Python unittest: understand decorator issuePython unittest:了解装饰器问题
【发布时间】:2017-09-20 04:26:33
【问题描述】:

最近几天我在 python 中测试了一些技术来自动化单元测试,比如 C# 中的 TestCase。

我知道有些框架支持这种技术,但是我会更详细地学习python,所以我想了解一下。

对我来说,下面的帖子有一个很好的答案(来自 Xavier Decoret),所以我尝试了一下,结果非常好,但我无法毫无例外地堆叠装饰器。

Python unittest: Generate multiple tests programmatically?

简而言之我的两段代码,产生的异常和环境:

import sys

def for_examples(*parameters):

  def tuplify(x):
    if not isinstance(x, tuple):
      return (x,)
    return x

  def decorator(method, parameters=parameters):
    for parameter in (tuplify(x) for x in parameters):

      def method_for_parameter(self, method=method, parameter=parameter):
        method(self, *parameter)
      args_for_parameter = ",".join(repr(v) for v in parameter)
      name_for_parameter = method.__name__ + "(" + args_for_parameter + ")"
      frame = sys._getframe(1)  # pylint: disable-msg=W0212
      frame.f_locals[name_for_parameter] = method_for_parameter
    return None
  return decorator
import unittest

# some magic code will be added here later
from params import for_examples


    class DummyTest(unittest.TestCase):
      @for_examples(1, 2)
      @for_examples(3, 4)
      def test_is_smaller_than_four(self, value):
        self.assertTrue(value < 4)

      @for_examples((1,2),(2,4),(3,7))
      def test_double_of_X_is_Y(self, x, y):
        self.assertEqual(2 * x, y)

    if __name__ == "__main__":
      unittest.main()
AttributeError: 'NoneType' object has no attribute '__name__'
Launching unittests with arguments python -m unittest test.DummyTest.test_double_of_X_is_Y in D:\rené\PycharmProjects\params
Windws 10 Home 64-bit
PyCharm Community Edition 2017.1.1
Python 3.6.1

希望有人可以帮助我理解我的问题,我们可以找到一个可堆叠的解决方案。

【问题讨论】:

    标签: python unit-testing decorator


    【解决方案1】:

    您复制的装饰器不是为那样使用而设计的。

    原因是这一行:

    return None
    

    通常,装饰器应该返回被装饰的函数,而不是None。但是,在这种情况下,装饰器故意不返回函数,因此 unittest 不会将其视为测试用例。

    好在这根本不是问题,因为

    @for_examples(1, 2)
    @for_examples(3, 4)
    

    等价于

    @for_examples(1, 2, 3, 4)
    

    【讨论】:

    • 是的,我只用一个装饰器对其进行了测试,但根据我的理解,我知道为什么用两个装饰器不可能。必须更改的是运行两次。我已经用返回类型测试了一些变体,但没有得到令人满意的结果。当我使用method_for_parameter 作为返回类型时,测试框架不会执行任何操作。
    • @rené “正确的”返回值将是 method。但是你会得到一个额外的测试用例,它总是会失败,因为它没有接收到任何参数。
    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    相关资源
    最近更新 更多