如何解决在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"
解决方法
要通过<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,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-asyncio和asynctest。
要安装:pytest
。
以下是基于您的代码的示例:
pip install pytest-asyncio asynctest
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。