Pytestにおけるテストパラメータ化:複数入力によるテスト実行
メニューを表示するにはスワイプしてください
パラメータ化テストは、入力値や期待される出力のみが異なるシナリオごとに多数のテスト関数を書くことなく、テストカバレッジを向上させるために重要です。このアプローチは、時間の節約だけでなく、テストスイートの明確性と保守性を高めます。
- テストコードの重複やエラーの可能性を減少;
- パラメータを追加するだけで新しいテストケースを簡単に追加可能;
- 幅広い入力値に対する包括的なテストを実現。
2つの数値の平均を計算するシンプルな関数を考えます。括弧を付け忘れると論理的なエラーが発生する場合があります。@pytest.mark.parametrize を使って、この関数を複数の数値ペアでテストします。
# Function to test
def calculate_average(num1, num2):
return (num1 + num2) / 2
# Test function using pytest's parametrize
import pytest
@pytest.mark.parametrize(
"num1, num2, expected",
[
(10, 20, 15),
(20, 30, 25),
(5, 5, 5)
])
def test_calculate_average(num1, num2, expected):
assert (calculate_average(num1, num2) == expected), f"Average of {num1} and {num2} should be equal to {(num1 + num2) / 2}"
この例は、test_calculate_average を3つの異なる数値セットで実行し、関数が正しく平均を計算できるかを確認する方法を示しています。
id付き構文
id パラメータは各入力セットに識別子を割り当て、テスト出力でテストを簡単に識別できるようにします。
@pytest.mark.parametrize("num1, num2, expected", [
pytest.param(10, 20, 15, id="integers"),
pytest.param(20, 30, 25, id="more integers"),
pytest.param(5, 5, 5, id="equal numbers")
])
def test_calculate_average_with_ids(num1, num2, expected):
assert calculate_average(num1, num2) == expected
pytest.param を使うことで、各テストケースに個別のIDを直接設定するなど、より細かな制御が可能です。
ids付き構文
ids を使って各テストケースに一意のIDを付与することもでき、テストレポートの可読性が向上します。
@pytest.mark.parametrize("num1, num2, expected", [
(10, 20, 15),
(20, 30, 25),
(5, 5, 5)
], ids=["integers", "more integers", "equal numbers"])
def test_calculate_average_with_ids(num1, num2, expected):
assert calculate_average(num1, num2) == expected
このコードでは、各パラメータセットにテストケースを説明するIDが関連付けられ、テスト出力に表示されます。
出力例は以下の通りです:
===================== test session starts ======================
collected 3 items
test_example.py::test_calculate_average_with_ids[integers] FAILED
test_example.py::test_calculate_average_with_ids[more integers] PASSED
test_example.py::test_calculate_average_with_ids[equal numbers] PASSED
=========================== FAILURES ===========================
________________ test_calculate_average_with_ids[integers] ________________
num1 = 10, num2 = 20, expected = 15
def test_calculate_average_with_ids(num1, num2, expected):
> assert calculate_average(num1, num2) == expected
E assert 20 == 15
E + where 20 = calculate_average(10, 20)
test_example.py:10: AssertionError
================== 1 failed, 2 passed in 0.23s ==================
1. 2つの数値を掛け算する関数を考えます。テストケースの空欄を埋めて完成させてください。
2. id で ids や @pytest.mark.parametrize を指定する主な利点は何ですか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 4
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 4