LoginSignup
9
2

More than 3 years have passed since last update.

doctestの使い方メモ

Posted at

doctestとは

簡易なテストを実行する為のpython標準ライブラリです

使い方

1. テストを書く

docstringに実行内容と正しい返り値をセットで書くだけです

def add(a, b):
    '''
    >>> add(1, 2)
    3
    >>> add(-8, -2)
    -10
    '''
    pass

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

2. テストを実行する

terminal
python hoge.py

3. 結果

出力
**********************************************************************
File "__main__", line 3, in __main__.add
Failed example:
    add(1, 2)
Expected:
    3
Got nothing
**********************************************************************
File "__main__", line 5, in __main__.add
Failed example:
    add(-8, -2)
Expected:
    -10
Got nothing
**********************************************************************
1 items had failures:
   2 of   2 in __main__.add
***Test Failed*** 2 failures.
TestResults(failed=2, attempted=2)

4. 修正する

正しく返すように修正します

hoge.py
def add(a, b):
    '''
    >>> add(1, 2)
    3
    >>> add(-8, -2)
    -10
    '''
    return a + b

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

5. 再度テストする

terminal
python hoge.py

6. 結果

テストがすべて成功すれば出力は出ません

出力

特定の関数を指定してテストする

doctest.testmod()を使うとすべての関数をテストしてくれますが、特定の関数だけをテストする場合はdoctest.run_docstring_examples()を使います。以下のように書けばadd()だけテストします。

hoge.py
    import doctest
    doctest.run_docstring_examples(add, globals())

jupyter notebookで使う場合

doctest.testmod()すると定義したすべての関数をテストするのは同じなので、セル内で普通に実行するだけです。

jupyter_notebook
def add(a, b):
    '''
    >>> add(1, 2)
    3
    >>> add(-8, -2)
    -10
    '''
    pass

import doctest
doctest.testmod()
9
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
2