萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python doctest 文檔測試模組實戰:注釋即測試、自動驗證範例代碼正確性

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)

實戰:為 Dict 類別添加 doctest

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 時不執行
  • 嚴格匹配輸出:含空白、換行、異常堆疊格式
  • ... 萬用字元:匹配任意多行輸出,用於異常堆疊、長列表
  • 命名空間隔離:每個 >>>> 區塊共享同一命名空間

進階用法

1. 測試外部檔案

doctest.testfile('readme.txt')  # 獨立文檔檔案

2. 與 unittest 整合

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)

3. 選項控制

doctest.testmod(optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
# ELLIPSIS: 支援 ... 萬用字元
# NORMALIZE_WHITESPACE: 忽略空白差異
# IGNORE_EXCEPTION_DETAIL: 忽略異常詳情只檢查型別

4. 類別/模組級別 doctest

class MyClass:
    '''Class docstring with examples.
    >>> MyClass().method()
    42
    '''
    def method(self):
        return 42

最佳實踐與限制

優勢限制
文檔與測試同步維護不適合複雜測試邏輯(需 setup/teardown、參數化)
範例代碼保證可執行異常堆疊輸出格式敏感,跨版本易斷
零配置、標準庫內建無法測試非公開介面(私有方法)
適合純函式、API 契約驗證大型專案測試覆蓋率統計不包含 doctest

建議策略

  • 公開 API 文檔字串加入 doctest 範例
  • 核心業務邏輯用 unittest/pytest 完整測試
  • CI 階段同時執行 python -m doctest 與 pytest
  • 使用 sphinx.ext.doctest 文檔生成時同步驗證
copyright © 萬盛學電腦網 all rights reserved