ホームページ  >  記事  >  バックエンド開発  >  テスト用に Python のリクエスト モジュールを効果的にモックする方法は?

テスト用に Python のリクエスト モジュールを効果的にモックする方法は?

Mary-Kate Olsen
Mary-Kate Olsenオリジナル
2024-10-20 19:44:30954ブラウズ

How to Effectively Mock Python's Requests Module for Testing?

Python のモック パッケージを使用してリクエストをモックする

Python のリクエスト モジュールを効果的にモックするには、次の手順に従います。

ステップ 1: リクエスト モジュールをモックする

テスト クラスのコンテキストでリクエスト モジュールをモックするには、次の構文を使用します:

<code class="python">import mock
@mock.patch('requests.get')
def test_function(self, mockedRequests):</code>

テスト関数内:

>
  • 各 URL に必要な戻り値を指定して、「aurl」、「burl」、および「curl」呼び出しを mockedRequests オブジェクトに割り当てます。

例:

<code class="python">mockedRequests.get('aurl').return_value = 'a response'
mockedRequests.get('burl').return_value = 'b response'
mockedRequests.get('curl').return_value = 'c response'</code>

ステップ 2: View 関数を呼び出す

テスト ケースで、myview 関数を呼び出して HTTP リクエストを実行します。

ステップ 3: 応答の検証

応答オブジェクトに期待値 ('a 応答'、'b 応答'、'c 応答') が含まれていることをアサートします。

例:

<code class="python">res1 = myview(request)
self.assertIn('a response', res1)
res2 = myview(request)
self.assertIn('b response', res2)
res3 = myview(request)
self.assertIn('c response', res3)</code>

コード例:

<code class="python">import unittest
import mock
from views import myview

# Mock the requests module
@mock.patch('requests.get')
def test_myview(self, mockedRequests):
    # Define return values for URL calls
    mockedRequests.get('aurl').return_value = 'a response'
    mockedRequests.get('burl').return_value = 'b response'
    mockedRequests.get('curl').return_value = 'c response'

    # Call the view function
    res1 = myview(request)
    res2 = myview(request)
    res3 = myview(request)

    # Verify response
    self.assertIn('a response', res1)
    self.assertIn('b response', res2)
    self.assertIn('c response', res3)

if __name__ == '__main__':
    unittest.main()</code>

以上がテスト用に Python のリクエスト モジュールを効果的にモックする方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。