Python 內建 doctest 模組能從文檔字串提取範例代碼並自動執行驗證,實現「文檔即測試、測試即文檔」。本文完整示範 doctest 寫法、執行方式、異常處理、... 處理長輸出、與 unittest 整合等進階用法。
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)
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()
$ python mydict.py
# 無輸出 = 所有測試通過
# 若註解掉 __getattr__ 再執行:
$ python mydict.py
**********************************************************************
File "mydict.py", line 7, in __main__.Dict
Failed example:
d1.x
Exception raised:
Traceback (most recent call last):
...
AttributeError: 'Dict' object has no attribute 'x'
**********************************************************************
File "mydict.py", line 13, in __main__.Dict
Failed example:
d2.c
Exception raised:
...
AttributeError: 'Dict' object has no attribute 'c'
**********************************************************************
if __name__ == '__main__': 保護,import 時不執行... 萬用字元:匹配任意多行輸出,用於異常堆疊、長列表>>>> 區塊共享同一命名空間doctest.testfile('readme.txt') # 獨立文檔檔案
import unittest
import doctest
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(my_module))
suite.addTest(doctest.DocFileSuite('readme.txt'))
runner = unittest.TextTestRunner()
runner.run(suite)
doctest.testmod(optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
# ELLIPSIS: 支援 ... 萬用字元
# NORMALIZE_WHITESPACE: 忽略空白差異
# IGNORE_EXCEPTION_DETAIL: 忽略異常詳情只檢查型別
class MyClass:
'''Class docstring with examples.
>>> MyClass().method()
42
'''
def method(self):
return 42
| 優勢 | 限制 |
|---|---|
| 文檔與測試同步維護 | 不適合複雜測試邏輯(需 setup/teardown、參數化) |
| 範例代碼保證可執行 | 異常堆疊輸出格式敏感,跨版本易斷 |
| 零配置、標準庫內建 | 無法測試非公開介面(私有方法) |
| 適合純函式、API 契約驗證 | 大型專案測試覆蓋率統計不包含 doctest |
doctest 範例unittest/pytest 完整測試python -m doctest 與 pytestsphinx.ext.doctest 文檔生成時同步驗證