美文网首页python3笔记
Python 文档测试

Python 文档测试

作者: shenshizhong | 来源:发表于2018-06-11 23:51 被阅读5次

    文档测试

    看到Python的官方文档,很多都有示例代码,比如re模块就带了很多示例代码:
    >>> import re
    >>> m = re.search('(?<=abc)def', 'abcdef')
    >>> m.group(0)
    'def'
    
    

    可以把示例代码在Python的交互式环境下输入执行,结果与文档的示例代码显示的一致。

    当我们编写注释,写上下面的注释更友好:
    def abs(n):
        '''
        Function to get absolute value of number.
    
        Example:
        >>> abs(1)
        1
        >>> abs(-1)
        1
        >>>abs(0)
        0
        '''
        return  n if n >= 0 else (-n)
    

    好处:

    • 告诉函数的调用者该函数期望输入和输出
    • Python内置的“文档测试”(doctest)模块可以直接提取注释中的代码并执行测试
    • doctest 严格按照Python交互式命令行的输入和输出判断测试结果是否正确,只有测试异常的时候,可以用...表示一大推输出
    使用doctest来测试编写的Dict类:
    class Dict(dict):
        '''
        Simple dict but also support access as x.y style.
    
        >>> d1 = Dict()
        >>> d1['x'] = 100
        >>> d1.x
        100
        >>> d1.y = 200
        >>> d1['y']
        200
        >>> d2 = Dict(a=1, b=2, c='3')
        >>> d2.c
        '3'
        >>> d2['empty']
        Traceback (most recent call last):
            ...
        KeyError: 'empty'
        >>> d2.empty
        Traceback (most recent call last):
            ...
        AttributeError: 'Dict' object has no attribute 'empty'
        '''
        def __init__(self, **kw):
            super(Dict, self).__init__(**kw)
    
        def __getattr__(self, key):
            try:
                return self[key]
            except KeyError:
                raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
    
        def __setattr__(self, key, value):
            self[key] = value
    
    if __name__=='__main__':
        import doctest
        doctest.testmod()
    

    运行后什么也没输出,这说明编写的doctest运行都是正确的, 如果程序有问题,比如我们试着把 __ getattr__ 注释掉,
    会有就会有报错:

    注释如下:

        # def __getattr__(self, key):
        #     try:
        #         return self[key]
        #     except KeyError:
        #         raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
    
    

    执行结果,报错内容:

    Error
    **********************************************************************
    File "E:/pyplace/learn_python3/learn/two/测试/文档测试/mydict2.py", line 7, in Dict
    Failed example:
        d1.x
    Exception raised:
        Traceback (most recent call last):
          File "D:\JetBrains\PyCharm 2018.1.1\helpers\pycharm\docrunner.py", line 140, in __run
            compileflags, 1), test.globs)
          File "<doctest Dict[2]>", line 1, in <module>
            d1.x
        AttributeError: 'Dict' object has no attribute 'x'
    
    
    Error
    **********************************************************************
    File "E:/pyplace/learn_python3/learn/two/测试/文档测试/mydict2.py", line 13, in Dict
    Failed example:
        d2.c
    Exception raised:
        Traceback (most recent call last):
          File "D:\JetBrains\PyCharm 2018.1.1\helpers\pycharm\docrunner.py", line 140, in __run
            compileflags, 1), test.globs)
          File "<doctest Dict[6]>", line 1, in <module>
            d2.c
        AttributeError: 'Dict' object has no attribute 'c'
    
    
    Process finished with exit code 0
    
    总结:
    • Python 官方文档的示例代码,可以在Python 交互式环境下执行。
    • 写注释会显得更加有好

    github地址: https://github.com/shenshizhong/learn_python3

    相关文章

      网友评论

        本文标题:Python 文档测试

        本文链接:https://www.haomeiwen.com/subject/cuvkeftx.html