gpt4 book ai didi

python - Doctest 和第三方装饰器

转载 作者:行者123 更新时间:2023-12-04 04:00:59 27 4
gpt4 key购买 nike

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

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

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

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

最佳答案

您可能无法更改 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())

关于python - Doctest 和第三方装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63061571/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com