テストフレームワーク
実際にテストコードを書くためには、一般的にはテストフレームワークを利用します。テストフレームワークは用いるプログラミング言語により異なります。pythonであれば、pytestやunittestがあります。これらのフレームワークは、テスト実行や作成を行う開発者を支援するのが主な役割です。これ以降は、pytestを用いて開発を行います。(pytest未インストールの場合はインストールしましょう)
pytest入門
論より証拠ということで、pytestを用いた簡単なテストの例を見てみましょう。
sample.py:
def add(x: int, y: int):
return x + y
test_sample.py:
import pytest
from first_day.sample import add
#成功例
def test_simple_case():
assert add(1, 2) == 3
#失敗例
def test_wrong_case():
assert add(1, 2) == 5
test_sample.pyには、sample.pyで実装されたadd関数のテストが二つ書かれています。assert f(x) == y
と記述することで、f(x)の出力がyと一致することを確認することができます。ここで、テストを実行してみましょう。テストの実行は次のコマンドで行います:
pytest ./test_sample.py
。次の結果が返ってきます:
test_sample.py .F [100%]
================================================= FAILURES ==================================================
______________________________________________ test_wrong_case ______________________________________________
def test_wrong_case():
> assert add(1, 2) == 5
E assert 3 == 5
E + where 3 = add(1, 2)
test_sample.py:10: AssertionError
========================================== short test summary info ==========================================
FAILED test_sample.py::test_wrong_case - assert 3 == 5
======================================== 1 failed, 1 passed in 0.06s ========================================
結果を見ると、test_wrong_caseに書いたassert add(1, 2) == 5
でエラーが出ているとわかります。関数の返り値3が、5と不一致であることがエラーの原因であるとわかります。sample.pyを次のように修正します。
import pytest
from first_day.sample import add
#成功例
def test_simple_case():
assert add(1, 2) == 3
再度テストを実行すると、次のメッセージが表示され、テストが通ったことがわかります:
platform darwin -- Python 3.8.5, pytest-6.1.1, py-1.9.0, pluggy-0.13.1
rootdir: /Users/okumotosho/tdd_py_sample/first_day
collected 1 item
test_sample.py . [100%]
============================================= 1 passed in 0.01s =============================================
まとめ
- pytestの簡単な使い方について説明しました
- 次回以降は、pytestと簡単な例を用いてTDDを実践してみましょう