【问题标题】:Doctest and third party decoratorDoctest 和第三方装饰器
【发布时间】:2020-11-13 14:40:20
【问题描述】:

我需要对一个必须用装饰器包装的方法进行文档测试,该装饰器不适用于被包装的方法@functools.wrapsfunctools.update_wrapper。在这种情况下,doctest 看不到要测试的方法的 docstring:

@third_party_decorator
def method_to_be_tested():
    """
    >>> method_to_be_tested()
    "foo"
    """
    return "foo"

This question 类似,但是我无法更改装饰器的代码。

我能做的最好的事情是什么?

【问题讨论】:

    标签: python python-3.x python-decorators doctest


    【解决方案1】:

    一个小的元装饰器来解决这个问题:

    def w(decorator): 
        def wrapper(func): 
            return wraps(func)(decorator(func))
        return wrapper 
    

    用途:

    @w(third_party_decorator)
    def method_to_be_tested():
        """
        >>> method_to_be_tested()
        "foo"
        """
        return "foo"
    

    或者,猴子修补它(只做一次):

    third_party_decorator = w(third_party_decorator)
    

    【讨论】:

      【解决方案2】:

      您可能无法更改third_party_decorator的代码,但您可以将其重新包装以解决问题,甚至在必要时重新使用相同的名称:

      def third_party_decorator(f):
          # badly behaved decorator, this removed f's docstring
          def no_docstring():
              return f()
          return no_docstring
      
      old_third_party_decorator = third_party_decorator
      
      def third_party_decorator(f):
          # replace third_party_decorator AND preserve docstring
          new_f = old_third_party_decorator(f)
          new_f.__doc__ = f.__doc__
          return new_f
      
      @third_party_decorator
      def method_to_be_tested():
          """
          >>> method_to_be_tested()
          'foo'
          """
          return "foo"
      
      import doctest
      print(doctest.testmod())
      

      【讨论】:

        猜你喜欢
        • 2014-05-16
        • 1970-01-01
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2016-02-10
        • 2010-10-16
        • 2012-09-11
        • 2020-01-11
        相关资源
        最近更新 更多