如何使用httpx-pytest软件包模拟httpx.connectError?
我想为我的API嘲笑ConnectionError。我正在为一个软件创建一个Python软件包,如果在localhost上运行:8080
,那么它将给出正确的结果。但是,如果软件不运行,那么我想捕获它。我能够使用httpx.connectError
编写功能来获取此异常,但是如何为其编写测试呢?
我的功能就是这样
def get_workspace(self, workspace: str) -> Union[WorkspaceModel, GSResponse]:
try:
Client = self.http_client
responses = Client.get(f"workspaces/{workspace}")
if responses.status_code == 200:
return WorkspaceModel.parse_obj(responses.json())
else :
results = self.response_recognise(responses)
return results
except httpx.TimeoutException as exc:
res = {}
res['code'] = 504
res['response'] = "Timeout Error"
return GSResponse.parse_obj(res)
except httpx.NetworkError as exc:
res = {}
res['code'] = 503
res['response'] = "Geoserver unavailable"
return GSResponse.parse_obj(res)
I want to mock ConnectionError for my API. I'm creating a python package for one software which if running on localhost:8080
then it will give result correctly. But if the software is not running, then I want to catch it. I'm able to write function using httpx.ConnectError
to get this exception, but how can I write test for the same ?
my function is like this
def get_workspace(self, workspace: str) -> Union[WorkspaceModel, GSResponse]:
try:
Client = self.http_client
responses = Client.get(f"workspaces/{workspace}")
if responses.status_code == 200:
return WorkspaceModel.parse_obj(responses.json())
else :
results = self.response_recognise(responses)
return results
except httpx.TimeoutException as exc:
res = {}
res['code'] = 504
res['response'] = "Timeout Error"
return GSResponse.parse_obj(res)
except httpx.NetworkError as exc:
res = {}
res['code'] = 503
res['response'] = "Geoserver unavailable"
return GSResponse.parse_obj(res)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 pytest-httpx ,您可以模拟httpx httpx fiving histhist h.href = httpx_mock.add_exception 。
您的测试案例看起来像这样:
Using pytest-httpx, you can simulate httpx raising any kind of exception thanks to httpx_mock.add_exception.
Your test case would look something like that: