在 Python 3.8 中修补异步对象

Patching Async Object in 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"

为了通过 pytest 测试 asyncio 代码,我建议您使用库 pytest-asyncio and asynctest

安装:pip install pytest-asyncio asynctest.

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

import httpx
import asynctest
import pytest


class DebugClass:
    async 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"


@pytest.mark.asyncio
async def test_debug_class_post():
    with asynctest.patch('httpx.AsyncClient.post') as post_mock:
        post_mock.side_effect = TimeoutError
        debug_class = DebugClass()
        res = await debug_class.post()
        assert res == "NOK"