はじめてのテストの作成
pytestでは、以下のルールに従ってテストを記述します。
1. テストの基本ルール
pytestでは、以下のルールに従ってテストを記述します。
- テストファイル名は
test_で始める(例:test_calculator.py) - テスト関数名は
test_で始める(例:test_add) assert文で期待する結果を検証する
基本的なテスト関数の構文は以下の通りです。
def test_関数名():
assert 関数(引数) == 期待値
実際に試してみましょう。
2. テストの作成
tests/init.pyの作成
tests/__init__.pyを作成します。Visual Studio Codeのエクスプローラーでtestsフォルダを右クリックし、「新しいファイル」を選択して__init__.pyという名前で作成してください。このファイルは空ファイルとして作成します。
python-testing
├── src/
│ ├── __init__.py
│ ├── calculator.py
│ ├── user_service.py
│ └── weather_client.py
├── tests/
│ └── __init__.py ← このファイルを作成(空ファイル)
└── requirements.txt
| 💡 ポイント |
|---|
testsフォルダにも__init__.pyを作成します。srcフォルダと同様に、Pythonパッケージとして認識させることで、テストコードからsrcモジュールを正しくインポートできるようになります。 |
2.1 tests/test_calculator.pyの作成
tests/test_calculator.pyを作成します。Visual Studio Codeのエクスプローラーでtestsフォルダを右クリックし、「新しいファイル」を選択してtest_calculator.pyという名前で作成してください。
python-testing
├── src/
│ ├── __init__.py
│ ├── calculator.py
│ ├── user_service.py
│ └── weather_client.py
├── tests/
│ ├── __init__.py
│ └── test_calculator.py ← このファイルを作成
└── requirements.txt
作成したファイルに以下の内容を記述して保存します。
from src.calculator import add, subtract, multiply, divide
def test_add():
assert add(1, 2) == 3
def test_subtract():
assert subtract(5, 3) == 2
def test_multiply():
assert multiply(3, 4) == 12
コードを解説します。
from src.calculator import add, subtract, multiply, divide
テスト対象のsrc/calculator.pyから、テストしたい関数をインポートしています。テストファイルからテスト対象のコードを読み込むことで、関数を呼び出してテストできるようになります。
def test_add():
assert add(1, 2) == 3
test_で始まる関数がテスト関数です。assert文は、続く式がTrueであればテスト成功、Falseであればテスト失敗となります。ここではadd(1, 2)の戻り値が3であることを検証しています。
def test_subtract():
assert subtract(5, 3) == 2
def test_multiply():
assert multiply(3, 4) == 12
同様に、subtract関数とmultiply関数のテストを記述しています。それぞれ期待する計算結果と一致するかをassert文で検証しています。
3. テストの実行
以下のコマンドで、Python がインストールされていることを確認します。
Windowsの場合:
python --version
以下のように Python のバージョンが表示されれば、インストールは確認できています。
Python 3.x.x
Macの場合:
python3 --version
以下のように Python のバージョンが表示されれば、インストールは確認できています。
Python 3.x.x
バージョンが表示されない場合は、Pythonのインストール を先に実施してください。
インストールが確認できたら、プロジェクトのルートディレクトリで、以下のコマンドを実行します。
Windowsの場合:
pytest tests/test_calculator.py -v
Macの場合:
python3 -m pytest tests/test_calculator.py -v
-vオプションは詳細な出力を表示します。実行結果は以下のようになります。
========================= test session starts ==========================
collected 3 items
tests/test_calculator.py::test_add PASSED [ 33%]
tests/test_calculator.py::test_subtract PASSED [ 66%]
tests/test_calculator.py::test_multiply PASSED [100%]
========================== 3 passed in 0.01s ===========================
3つのテストがすべてPASSED(成功)となりました。
4. テストが失敗するケースの体験
テストが失敗するとどうなるかを体験してみましょう。tests/test_calculator.pyのtest_add関数を以下のように変更してください。
def test_add():
assert add(1, 2) == 5 # わざと間違った期待値にする
変更を保存したら、再度テストを実行します。
Windowsの場合:
pytest tests/test_calculator.py -v
Macの場合:
python3 -m pytest tests/test_calculator.py -v
以下のように、テストが失敗した結果が表示されます。
========================= test session starts ==========================
collected 3 items
tests/test_calculator.py::test_add FAILED [ 33%]
tests/test_calculator.py::test_subtract PASSED [ 66%]
tests/test_calculator.py::test_multiply PASSED [100%]
================================ FAILURES ================================
__________________________ test_add __________________________
def test_add():
> assert add(1, 2) == 5
E assert 3 == 5
E + where 3 = add(1, 2)
tests/test_calculator.py:5: AssertionError
======================== 1 failed, 2 passed in 0.02s ========================
失敗したテストはFAILEDと表示され、FAILURESセクションに詳細が出力されます。assert 3 == 5という行から、add(1, 2)の実際の戻り値は3であるのに、期待値を5としていたため失敗したことがわかります。このように、pytestは失敗時に「何が期待されていて、実際には何だったか」を明確に表示してくれます。
テスト失敗を確認できたら、test_add関数を元に戻してください。
def test_add():
assert add(1, 2) == 3
変更を保存したら、再度テストを実行して3つすべてがPASSEDに戻ることを確認してください。