【发布时间】:2013-05-27 13:58:01
【问题描述】:
一些上下文
我正在编写一个 Python 应用程序,我想保证没有人忘记为类、模块和公共函数/方法编写文档。为此我创建了一个单元测试,为了这个问题,断言部分如下(需要测试的过滤部分更复杂,我避免将其放在这里):
...
assertIsNotNone(item.__doc__, msg="%s has no documentation" % name(item))
assertGreaterEqual(len(item.__doc__.strip()), 10, msg="%s should have more documentation" % name(item))
...
name(item) 只是一个辅助函数,它返回被检查对象的正确名称
问题
并不是我所有的函数或类都需要文档(比如单元测试中的setUp 和tearDown 方法)。在这些情况下,我想明确表示不会为相关项目编写任何文档。我的单元测试的目标是检查是否有任何文档被遗忘,因此测试应该跳过这些情况
我的解决方案
我编写了以下装饰器以应用于这些情况:
import inspect
def no_doc(item):
"""
Decorator that makes explicit that the function/method
or class in question has no documentation
"""
result = None
if inspect.isclass(item):
class wrapper (item):
"Class intentionally with no documentation"
pass
result = wrapper
elif inspect.isfunction(item):
def wrapper(*args, **kwargs):
"Function intentionally with no documentation"
return item(*args, **kwargs)
result = wrapper
return result
担忧
作为装饰器的目标,它只更改 doc 字符串,仅此而已,我的装饰函数/方法/类必须尽可能保持它们的行为。我担心用@no_doc 装饰它们以解决开发问题会导致生产代码出现错误或行为更改。
最后,问题
我问你我的装饰器方法是否是解决问题的好方法,装饰器本身是否安全实现
谢谢
【问题讨论】:
标签: python unit-testing documentation decorator