zoukankan      html  css  js  c++  java
  • Python -- 文档测试


    Python内置的“文档测试”(doctest)模块可以直接提取注释中的代码并执行测试。

    例子:

    # mydict2.py
    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()

    如果程序没有错误,则没有输出

    如果程序有问题,比如把__getattr__()方法注释掉,再运行就会报错:

    >>> 
    **********************************************************************
    File "C:UsersSQDDesktopGitPythondoctestmydict2.py", line 12, in __main__.Dict
    Failed example:
        d1['y']
    Exception raised:
        Traceback (most recent call last):
          File "C:Python34libdoctest.py", line 1324, in __run
            compileflags, 1), test.globs)
          File "<doctest __main__.Dict[4]>", line 1, in <module>
            d1['y']
        KeyError: 'y'
    **********************************************************************
    1 items had failures:
       1 of   9 in __main__.Dict
    ***Test Failed*** 1 failures.

    注意到最后3行代码。当模块正常导入时,doctest不会被执行。只有在命令行直接运行时,才执行doctest。所以,不必担心doctest会在非测试环境下执行。

    KEEP LEARNING!
  • 相关阅读:
    CSS基础
    HTML基础
    JavaScript基础目录
    python 面向对象的基本概念(未完待续)
    python核心编程笔记(转)
    转: cJSON的使用方法
    转: C语言交换两个变量数值的几种方法
    转: 100个gdb小技巧项目
    转:C语言中的typeof关键字
    转:安全起见,小心使用C语言realloc()函数
  • 原文地址:https://www.cnblogs.com/roronoa-sqd/p/4905421.html
Copyright © 2011-2022 走看看