简体   繁体   English

用于单元测试的 python 中的模拟流 API

[英]Mock streaming API in python for unit test

I have an async function that calls a streaming api.我有一个异步 function 调用流式 api。 What is the best way to write unit test for this function?为这个 function 编写单元测试的最佳方法是什么? The api response has to be mocked.必须模拟 api 响应。

I tried with aiounittest and used mock from unittest.我尝试使用 aiounittest 并使用来自 unittest 的模拟。 But this calls the actual api instead of getting the mocked response.但这会调用实际的 api 而不是得到模拟响应。 Also tried with pytest.mark.asyncio annotation, but this kept giving me the error - coroutine was never awaited.还尝试使用 pytest.mark.asyncio 注释,但这一直给我错误 - 从未等待协程。 I have verified that pytest-asyncio has been installed.我已经验证 pytest-asyncio 已经安装。

I am using VS Code and Python 3.6.6我正在使用 VS Code 和 Python 3.6.6

Here is the relevant code snippet:这是相关的代码片段:

async def method1():
    response = requests.get(url=url, params=params, stream=True)
    for data in response.iter_lines():
        # processing logic here
        yield data

Pasting some of the tests I tried.粘贴一些我尝试过的测试。

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
    

Also tried with class TestClass (aiounittest.AsyncTestCase):还尝试了 class TestClass (aiounittest.AsyncTestCase):

Use asynctest instead of aiounittest .使用asynctest而不是aiounittest

  1. Replace unittest.TestCase with asynctest.TestCase .unittest.TestCase替换为asynctest.TestCase
  2. Replace from unittest.mock import patch with from asynctest.mock import patch .from unittest.mock import patch替换为from asynctest.mock import patch
  3. async for data in method1: should be async for data in method1(): . 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM