doctestとは

  • モジュールドキュメント中の対話モード記述通りに動作するかの検証
  • 回帰テストの実現
def add(a, b):
    """ 任意の2つのオブジェクトの合計を返す。
    >>> add(1,2)
    3
    >>> add([1],[2])
    [1, 2]
    >>> add([1],2)
    Traceback (most recent call last):
    TypeError: can only concatenate list (not "int") to list
    """
    return a+b

if __name__ == "__main__":
    import doctest
    doctest.testmod()
  • v オプションなし、エラーあり
C:\Documents and Settings\hirogl\My Documents>D:\Python\python.exe toy.py
**********************************************************************
File "toy.py", line 5, in __main__.add
Failed example:
    add([1],[2])
Expected:
    [1,2]
Got:
    [1, 2]
**********************************************************************
1 items had failures:
   1 of   3 in __main__.add
***Test Failed*** 1 failures.
  • v オプションあり、エラーなし
C:\Documents and Settings\hirogl\My Documents>D:\Python\python.exe toy.py -v
Trying:
    add(1,2)
Expecting:
    3
ok
Trying:
    add([1],[2])
Expecting:
    [1, 2]
ok
Trying:
    add([1],2)
Expecting:
    Traceback (most recent call last):
    TypeError: can only concatenate list (not "int") to list
ok
1 items had no tests:
    __main__
1 items passed all tests:
   3 tests in __main__.add
3 tests in 2 items.
3 passed and 0 failed.
Test passed.