Skip to main content

Python + pytest

方針

  • Python のサードパーティ コマンド pytest を使う
  • 標準ライブラリの unittest との併用もできるようだ

前提

bash
pip install pytest

プロジェクト作成

bash
mkdir -p ~/workdir/SamplePython
code ~/workdir/SamplePython

最小のコード

sample.py
def add(a: int, b: int) -> int:
return a + b
test_sample.py
from sample import add

def test_add_two_and_three() -> None:
assert add(2, 3) == 5

決まりごと

  • ファイル名 : test_*.py
  • 関数名 : test_*()
  • テストしたい箇所で assert <条件> を呼ぶ

実行

bash
pytest

表示例

成功時

  • 関数名は出ない → --verbose オプションつければ出る
  • 標準出力も出ない → --capture=no オプションつければ出る
txt
========================== test session starts ===================
platform darwin -- Python 3.10.17, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/takaaki/workdir/SamplePython
collected 1 item

test_sample.py .

========================= 1 passed in 0.00s ======================

失敗時

txt
========================== test session starts ===================
platform darwin -- Python 3.10.17, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/takaaki/workdir/SamplePython
collected 1 item

test_sample.py F

============================== FAILURES ==========================
_________________________ test_add_two_and_three _________________

def test_add_two_and_three() -> None:
> assert add(2, 4) == 5
E assert 6 == 5
E + where 6 = add(2, 4)

test_sample.py:4: AssertionError
========================== short test summary info ===============
FAILED test_sample.py::test_add_two_and_three - assert 6 == 5
============================= 1 failed in 0.01s ==================

以下広告