簡體   English   中英

用於單元測試的 python 中的模擬流 API

[英]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

  1. unittest.TestCase替換為asynctest.TestCase
  2. from unittest.mock import patch替換為from asynctest.mock import patch
  3. 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