天天看點

Python程式設計:使用doctest進行文檔測試

doctest子產品是内置子產品

應用舉例

# -*- coding: utf-8 -*-

def add(x, y):
    """
    求和 x + y
    Args:
        x: int
        y: int

    Returns:
        int

    eg:
    >>> add(1, 1)
    2
    >>> add(5, 5)
    10
    >>> 2/0
    Traceback (most recent call last):
        ...
    ZeroDivisionError: division by zero
    """

    return x + y * 2


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

運作結果

**********************************************************************
Failed example:
    add(1, 1)
Expected:
    2
Got:
    3
**********************************************************************

Failed example:
    add(5, 5)
Expected:
    10
Got:
    15
**********************************************************************
1 items had failures:
   2 of   2 in __main__.add
***Test Failed*** 2 failures.

Process finished with exit code 0
      

如果所有測試用例都能通過測試,則不生成任何輸出結果