在Python 3.8中修补异步对象

时间:2020-10-26 10:27:03

标签: python async-await pytest python-3.8

我有一个关于使用Python 3.8模拟修补异步对象的新手问题。我只想模拟post()以便测试错误处理逻辑,但到目前为止我还没有运气。你能告诉我我做错了什么吗?非常感谢。

main.py

import httpx


test_data = {"id": "123"}

class DebugClass:
    def post(self):
        try:
            async with httpx.AsyncClient() as client:
                res = await client.post(url='http://localhost:8080', data=test_data)
            return "OK"
        except Exception as e:
            return "NOK"

test_main.py

from unittest import mock
from unittest.mock import patch, AsyncMock


from main import DebugClass

class TestClass:
    @mock.patch('httpx.AsyncClient.post', new_callable=AsyncMock)
    def test_post(self, mock_client_post):
        mock_client_post = AsyncMock(side_effect=TimeoutError)
        debug_class = DebugClass()
        res = debug_class.post()
        assert res == "NOK"

1 个答案:

答案 0 :(得分:1)

要通过<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="Q_1_ck1" value="R" data-id="Environmental Science , Physical Education , Agriculture , Yoga " checked> <input type="checkbox" id="Q_1_ck2" value="E" data-id="Entrepreneurship, Political Science, Agriculture , Business Administration, Salesmanship "> <input type="checkbox" id="Q_1_ck3" value="S" data-id="History, Legal Studies, Mass Media Studies, Home Science, Food Nutrition and Dietetics, Foreign Languages, National Cadet Corps, Yoga" checked>测试asyncio代码,我建议您使用库pytest-asyncioasynctest

要安装:pytest

以下是基于您的代码的示例:

pip install pytest-asyncio asynctest