gpt4 book ai didi

python - python中的模拟流API进行单元测试

转载 作者:行者123 更新时间:2023-12-03 16:47:15 24 4
gpt4 key购买 nike

我有一个调用流 API 的异步函数。为这个函数编写单元测试的最佳方法是什么?必须模拟 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

还尝试使用类 TestClass (aiounittest.AsyncTestCase):

最佳答案

使用 asynctest 而不是 aiounittest .

  • 替换 unittest.TestCaseasynctest.TestCase .
  • 替换 from unittest.mock import patchfrom 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

    关于python - python中的模拟流API进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65133937/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com