【问题标题】:Testing if a python object has written documentation测试 python 对象是否有书面文档
【发布时间】: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) 只是一个辅助函数,它返回被检查对象的正确名称

问题

并不是我所有的函数或类都需要文档(比如单元测试中的setUptearDown 方法)。在这些情况下,我想明确表示不会为相关项目编写任何文档。我的单元测试的目标是检查是否有任何文档被遗忘,因此测试应该跳过这些情况

我的解决方案

我编写了以下装饰器以应用于这些情况:

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


    【解决方案1】:

    你不应该对你所拥有的东西有任何重大问题(我能想到的)。但是,您可以通过显式修改__doc__ 来避免新的子类/函数:

    def no_doc(item):
        """A decorator to add the no-doc docstring
         objects that don't need any other documentation"""
    
        t = "class" if inspect.isclass(item) else "function"
        item.__doc__ = "This {} intentionally has no documentation".format(t)
    
        return item
    

    这样做可确保您获得完全相同的类型(对于类)和完全相同的函数签名,并避免任何一种情况可能导致的任何问题。

    【讨论】:

    • 这很简单,很好,是我的第一个实现。问题是当你尝试用它装饰一个类时,你会得到一个AttributeError: attribute '__doc__' of 'type' objects is not writable。做一些基本的脚本确实不可能改变一个类__doc__字符串,如果它是一个用户类则事件
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2011-02-12
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多