\

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の基本的な使い方になります。詳細な使い方や応用例については公式ドキュメントを参照してください。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です