[英]Mock streaming API in python for unit test
我有一個異步 function 調用流式 api。 為這個 function 編寫單元測試的最佳方法是什么? 必須模擬 api 響應。
我嘗試使用 aiounittest 並使用來自 unittest 的模擬。 但這會調用實際的 api 而不是得到模擬響應。 還嘗試使用 pytest.mark.asyncio 注釋,但這一直給我錯誤 - 從未等待協程。 我已經驗證 pytest-asyncio 已經安裝。
我正在使用 VS Code 和 Python 3.6.6
這是相關的代碼片段:
async def method1():
response = requests.get(url=url, params=params, stream=True)
for data in response.iter_lines():
# processing logic here
yield data
粘貼一些我嘗試過的測試。
def mocked_get(*args, **kwargs):
#implementation of mock
class TestClass (unittest.TestCase):
@patch("requests.get", side_effect=mocked_get)
async def test_method (self, mock_requests):
resp = []
async for data in method1:
resp.append (data)
#Also tried await method1
assert resp
還嘗試了 class TestClass (aiounittest.AsyncTestCase):
使用asynctest
而不是aiounittest
。
unittest.TestCase
替換為asynctest.TestCase
。from unittest.mock import patch
替換為from asynctest.mock import patch
。async for data in method1:
應該是async for data in method1():
。import asynctest
from asynctest.mock import patch
class TestClass(asynctest.TestCase):
@patch("requests.get", side_effect=mocked_get)
async def test_method(self, mock_requests):
resp = []
async for data in method1():
resp.append(data)
assert resp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.