doctest 簡介

2022-08-03 16:29 更新

doctest模塊搜索看起來像交互式Python會話的文本片段,然后執(zhí)行這些會話以驗證它們完全按照所示方式工作。有幾種常用的方法可以使用doctest:

  • 通過驗證所有交互式示例仍按記錄工作來檢查模塊的文檔是否是最新的。
  • 通過驗證測試文件或測試對象中的交互式示例如預(yù)期工作來執(zhí)行回歸測試。
  • 為包編寫教程文檔,用輸入輸出示例大量地說明。根據(jù)實例或說明文本是否被強調(diào),這具有“識字測試”或“可執(zhí)行文檔”的味道。

這是一個完整但很小的示例模塊:

"""
This is the "example" module.

The example module supplies one function, factorial().  For example,

>>> factorial(5)
120
"""

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    If the result is small enough to fit in an int, return an int.
    Else return a long.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> [factorial(long(n)) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(30)
    265252859812191058636308480000000L
    >>> factorial(30L)
    265252859812191058636308480000000L
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    >>> factorial(30.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
    >>> factorial(30.0)
    265252859812191058636308480000000L

    It must also not be ridiculously large:
    >>> factorial(1e100)
    Traceback (most recent call last):
        ...
    OverflowError: n too large
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result


if __name__ == "__main__":
    import doctest
    doctest.testmod()

如果您直接從命令行運行example.py,那么doctest可以發(fā)揮它的魔力:

$ python example.py

沒有輸出!這很正常,而且這意味著所有的例子都有效。傳遞-v給腳本,并doctest打印它正在嘗試的詳細(xì)日志,并在最后打印摘要:

$ python example.py -v
Trying:
    factorial(5)
Expecting:
    120
ok
Trying:
    [factorial(n) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok
Trying:
    [factorial(long(n)) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok

以此類推,最終結(jié)局如下:

Trying:
    factorial(1e100)
Expecting:
    Traceback (most recent call last):
        ...
    OverflowError: n too large
ok
2 items passed all tests:
   1 tests in __main__
   8 tests in __main__.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.

這就是你需要知道的開始有效使用doctest!跳入。以下部分提供完整的詳細(xì)信息。請注意,標(biāo)準(zhǔn)Python測試套件和庫中有很多文檔測試的例子。在標(biāo)準(zhǔn)測試文件中可以找到特別有用的示例Lib/test/test_doctest.py


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號