Pythonのテストフレームワークであるpytest
は、その使い方が簡単で、失敗したテストの原因が分かりやすいという特徴があります。
インストール
pytest
はpipを使用して簡単にインストールすることができます。
pip install pytest
基本的な使い方
基本的にはassert
で望む結果を書きます。以下にtest_assert1.py
というテスト用のファイルを作成する例を示します。
# content of test_assert1.py
def f():
return 3
def test_function():
assert f() == 4
テストの実行はpytest
コマンドを利用します。
期待される例外の処理
例外が発生することが期待される場合にはpytest.raises
を利用します。
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
fixturesの活用
fixtures
はunittestのsetup/teardownのような関数を劇的に改善する関数であり、テスト関数は引数として名前を指定することでfixtureオブジェクトを受け取ることができます。
# content of ./test_smtpsimple.py
import pytest
@pytest.fixture
def smtp_connection():
import smtplib
return smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
def test_ehlo(smtp_connection):
response, msg = smtp_connection.ehlo()
assert response == 250
assert 0 # for demo purposes
以上がpytest
の基本的な使い方になります。詳細な使い方や応用例については公式ドキュメントを参照してください。