python 文档测试

12 Feb 2018

doctest 模块按照交互模式自动执行注释内容,以此测试测程序

class Dict(dict):
    '''
    >>> d1 = Dict()
    >>> d1.y = 200
    >>> d1['y']
    200
    >>> d2 = Dict(a=1, b=2, c='3')
    >>> d2.c
    '3'
    '''
    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(verbose=True) # verbose 默认False,True 表示要啰嗦地打印出日志

以下是输出:

Trying:
    d1.y = 200
Expecting nothing
ok
Trying:
    d1['y']
Expecting:
    200
ok
Trying:
    d2 = Dict(a=1, b=2, c='3')
Expecting nothing
ok
Trying:
    d2.c
Expecting:
    '3'
ok
Trying:
    d2['empty']
Expecting:
    Traceback (most recent call last):
        ...
    KeyError: 'empty'
ok
Trying:
    d2.empty
Expecting:
    Traceback (most recent call last):
        ...
    AttributeError: 'Dict' object has no attribute 'empty'
ok
4 items had no tests:
    __main__
    __main__.Dict.__getattr__
    __main__.Dict.__init__
    __main__.Dict.__setattr__
1 items passed all tests:
   9 tests in __main__.Dict
9 tests in 5 items.
9 passed and 0 failed.
Test passed.