Python + unittest
方針
- Python で、標準ライブラリの
unittestを使用
プロジェクト作成
bash
mkdir -p ~/workdir/SamplePython
code ~/workdir/SamplePython
最小のコード
sample.py
def add(a: int, b: int) -> int:
return a + b
test_sample.py
import unittest
from sample import add
class AddTest(unittest.TestCase):
def test_two_plus_three(self) -> None:
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
決まりごと
unittest.TestCaseを継承し、test_*で始まるメソッドを定義test_*メソッド内ではself.assertEqual()などのマッチ関数を実行test_*メソッドはunittest.main()で実行される- ファイル名 : なんでも良いが、
pytestから呼びたいならtest_*.pyとしておく
実行
bash
python3 test_sample.py
表示例
成功時
- 関数名は出ない
- TODO: verbose オプションなどある?
txt
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
失敗時
txt
F
======================================================================
FAIL: test_two_plus_three (__main__.AddTest.test_two_plus_three)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/takaaki/workdir/SamplePython/test_sample.py", line 6, in test_two_plus_three
self.assertEqual(add(2, 4), 5)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
AssertionError: 6 != 5
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
以下広告