Python 文檔測試

文檔測試

看到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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章