モック

プロジェクトのsrc/weather_client.pyには、外部APIを呼び出して天気情報を取得する関数があります。しかし、このコードをそのままテストしようとすると、テストを実行するたびに実際のHTTPリクエストが送信されます。これにはいくつかの問題があります。

  • 天気情報は時間とともに変わるため、テスト結果が毎回異なり、期待値を固定できない
  • テストの実行にネットワーク接続が必要になる
  • 外部APIが停止しているとテストが失敗する(コードに問題がなくても)
  • HTTPリクエストの分だけテストの実行が遅くなる

このように、テスト対象のコードが外部のサービスやリソースに依存している場合、依存先を本物の代わりに「偽物」に置き換えてテストする手法をモックと呼びます。モックを使うことで、外部APIの状態に関係なく、コードのロジックだけを安定してテストできます。Pythonではunittest.mockモジュールのpatchを使います。

基本的な構文は以下の通りです。

from unittest.mock import patch

@patch("モジュール名.関数名")
def test_関数名(mock_オブジェクト):
    mock_オブジェクト.return_value = モック戻り値
    結果 = テスト対象関数()
    assert 結果 == 期待値

実際に試してみましょう。tests/test_weather_client.pyを作成します。Visual Studio Codeのエクスプローラーでtestsフォルダを右クリックし、「新しいファイル」を選択してtest_weather_client.pyという名前で作成してください。

python-testing
├── src/
│   ├── __init__.py
│   ├── calculator.py
│   ├── user_service.py
│   └── weather_client.py
├── tests/
│   ├── __init__.py
│   ├── test_calculator.py
│   ├── test_user_service.py
│   └── test_weather_client.py  ← このファイルを作成
└── requirements.txt

作成したファイルに以下の内容を記述して保存します。

from unittest.mock import patch, MagicMock
from src.weather_client import fetch_weather, get_weather_summary

@patch("src.weather_client.urllib.request.urlopen")
def test_fetch_weather_success(mock_urlopen):
    # Arrange
    mock_response = MagicMock()
    mock_response.read.return_value = b'{"temperature": 22.5}'
    mock_response.__enter__ = MagicMock(return_value=mock_response)
    mock_response.__exit__ = MagicMock(return_value=False)
    mock_urlopen.return_value = mock_response

    # Act
    result = fetch_weather("Tokyo")

    # Assert
    assert result["status"] == "success"
    assert result["temperature"] == 22.5

@patch("src.weather_client.urllib.request.urlopen")
def test_fetch_weather_error(mock_urlopen):
    # Arrange
    mock_urlopen.side_effect = Exception("Connection refused")

    # Act
    result = fetch_weather("Tokyo")

    # Assert
    assert result["status"] == "error"
    assert "Connection refused" in result["message"]

@patch("src.weather_client.fetch_weather")
def test_get_weather_summary(mock_fetch):
    # Arrange
    mock_fetch.side_effect = [
        {"city": "Tokyo", "status": "success", "temperature": 22.5},
        {"city": "Osaka", "status": "error", "message": "timeout"},
        {"city": "Nagoya", "status": "success", "temperature": 20.0},
    ]

    cities = ["Tokyo", "Osaka", "Nagoya"]

    # Act
    summary = get_weather_summary(cities)

    # Assert
    assert summary["total"] == 3
    assert summary["success"] == 2
    assert summary["error"] == 1

コードを解説します。

@patch("src.weather_client.urllib.request.urlopen")
def test_fetch_weather_success(mock_urlopen):

@patchデコレータでurllib.request.urlopenをモックに置き換えています。テスト関数の引数mock_urlopenにモックオブジェクトが渡されます。これにより、実際のHTTPリクエストを送ることなく、関数のロジックのみを検証できます。

    mock_response = MagicMock()
    mock_response.read.return_value = b'{"temperature": 22.5}'

MagicMock(あらゆるメソッド呼び出しを模擬できるオブジェクト)を使って、APIのレスポンスを模擬しています。read()メソッドが呼ばれたときにJSON形式のバイト列を返すように設定しています。

@patch("src.weather_client.fetch_weather")
def test_get_weather_summary(mock_fetch):
    mock_fetch.side_effect = [...]

side_effectにリストを渡すと、関数が呼ばれるたびにリストの要素を順番に返します。ここでは3都市分のレスポンスを設定し、成功2件・エラー1件のケースをテストしています。

📝 モックを使う場面
モックは、外部API、データベース、ファイルシステムなど、テスト環境で利用しにくい外部依存がある場合に使います。モックを使うことで、テストの実行速度が向上し、外部サービスの障害に影響されない安定したテストが実現できます。

実際に試してみましょう。テストを実行します。

Windowsの場合:

pytest tests/test_weather_client.py -v

Macの場合:

python3 -m pytest tests/test_weather_client.py -v

以下のような実行結果が表示されます。

========================= test session starts ==========================
collected 3 items

tests/test_weather_client.py::test_fetch_weather_success PASSED         [ 33%]
tests/test_weather_client.py::test_fetch_weather_error PASSED           [ 66%]
tests/test_weather_client.py::test_get_weather_summary PASSED           [100%]

========================== 3 passed in 0.01s ===========================

モックにより実際のHTTPリクエストを送ることなく、天気取得ロジックの成功ケース、エラーケース、サマリ集計の3つのテストがすべて成功しています。