doctest
doctestを使うとdocstring的な記載で容易にテストが実行できるらしい!
argを2倍にするFunction「twice」の実装
- サンプルスクリプト
def twice(n): """ >>> twice(2) 4 >>> twice(-2) -4 """ return n*2 if __name__ == "__main__": print(twice(2)) import doctest doctest.testmod(verbose=True)
- 実行結果
- テストが実行される
4 Trying: twice(2) Expecting: 4 ok Trying: twice(-2) Expecting: -4 ok 1 items had no tests: __main__ 1 items passed all tests: 2 tests in __main__.twice 2 tests in 2 items. 2 passed and 0 failed. Test passed.
sampleスクリプトのラッパースクリプト
- サンプルスクリプト
import doctest_1 print(doctest_1.twice(3))
- 実行結果
- テストは実行されない!
6
修正(non-verbose化)
- 実験用にverboseモードを強制してたけど、普通はverboseモードをOFF(デフォルト)に戻す
# 修正前(上のほうでの記載) import doctest doctest.testmod(verbose=True) # 修正後 import doctest doctest.testmod()
修正後、verboseモードで実行したい場合の実行コマンドライン
python <<スクリプト名>> -v
import以降を記載してないが、doctestを実行したい場合の実行コマンドライン
# 通常モード python -m doctest <<スクリプト名>> # verboseモード python -m doctest <<スクリプト名>> -v