Skip to main content

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)

以下広告