Python テストのリクエストとレスポンスのモック化
Python テストでは、実行フローを制御するためにモジュールとその機能をモック化することが必要になります。そして特定のシナリオを検証します。このうち、requests モジュールのモック化は、HTTP リクエストに依存する関数やメソッドをテストするためによく使用されます。
次のコードを含む views.py ファイルを考えてみましょう:
<code class="python">def myview(request): res1 = requests.get('aurl') res2 = request.get('burl') res3 = request.get('curl')</code>
これをモックするには動作を確認するには、Python モック パッケージを使用できます。これを段階的に実現する方法は次のとおりです。
ステップ 1: モック動作を定義する
requests モジュールをモックするには、requests.get を置き換える関数を定義します。 ()。この関数では、URL ごとに必要な応答を指定できます。
<code class="python">def mocked_requests_get(*args, **kwargs): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return self.json_data if args[0] == 'aurl': return MockResponse({'a': 'a'}, 200) elif args[0] == 'burl': return MockResponse({'b': 'b'}, 200) elif args[0] == 'curl': return MockResponse({'c': 'c'}, 200) return MockResponse(None, 404)</code>
ステップ 2: リクエスト モジュールにパッチを適用する
テスト ケースでは、モックを使用します。 .patch() デコレータを使用して、実際のリクエスト モジュールをモック関数で置き換えます。
<code class="python">@mock.patch('requests.get', side_effect=mocked_requests_get) def test_myview(self, mock_get): # Call the function you want to test myview(None) # Assertions for expected responses ...</code>
ステップ 3: アサーションを確認する
テスト関数内で、次のコマンドを使用できます。
<code class="python">self.assertEqual(mock_get.call_args_list[0][0][0], 'aurl') self.assertEqual(mock_get.call_args_list[1][0][0], 'burl') self.assertEqual(mock_get.call_args_list[2][0][0], 'curl')</code>
これらの手順に従うことで、HTTP リクエストを効果的にモックし、Python テスト シナリオでのレスポンスを制御できます。これにより、外部の依存関係が結果に干渉しないようにしながら、特定の機能を分離してテストできます。
以上がPython テスト シナリオで HTTP リクエストとレスポンスをモックする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

forhandlinglaredataSetsinpython、usenumpyArrays forbetterperformance.1)numpyarraysarememory-effictientandfasterfornumericaloperations.2)nusinnnnedarytypeconversions.3)レバレッジベクトル化は、測定済みのマネージメーシェイメージーウェイズデイタイです

inpython、listsusedynamicmemoryallocation with allocation、whilenumpyArraysalocatefixedmemory.1)listsallocatemorememorythanneededededinitivative.2)numpyArrayasallocateexactmemoryforements、rededicablebutlessflexibilityを提供します。

inpython、youcanspecthedatatypeyfelemeremodelernspant.1)usenpynernrump.1)usenpynerp.dloatp.ploatm64、フォーマーpreciscontrolatatypes。

numpyisessentialfornumericalcomputinginpythonduetoitsspeed、memory efficiency、andcomprehensivematicalfunctions.1)それは、performsoperations.2)numpyArraysaremoremory-efficientthanpythonlists.3)Itofderangeofmathematicaloperty

contiguousMemoryAllocationisucial forArraysは、ForeffienceAndfastelementAccess.1)iteenablesConstantTimeAccess、O(1)、DuetodirectAddresscalculation.2)itemprovesefficiencyByAllowingMultiblementFechesperCacheLine.3)itimplifieMememm

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

ホットトピック









