【发布时间】:2018-08-05 09:16:00
【问题描述】:
我正在编写一些测试,我想将 flask.Response 对象转换为相应的 requests.Response 对象。所以我有 2 个 Flask 应用程序(例如 A 和 B),并且 A 对 B 进行内部调用(通过 requests.post(url, json=payload))。我的目标是在不启动任何服务器的情况下正确模拟这些调用,当前的解决方案如下所示:
from unittest import mock
...
def mock_B_request(url, json):
response = app_B.test_client().post(url, json=json) # flask.Response
# Some hacking should be done here,
# since flask.Respone doesn't have `.ok`, `.json()`, etc.,
# so it will break the code inside app_A
return response
...
# Inside the actual test method
with mock.patch('requests.post', side_effect=mock_B_request):
response = app_A.test_client().post(url, json=payload)
result = response.get_json()
...
有人遇到过这样的问题吗?这里最简单的解决方案是什么?
【问题讨论】:
标签: python unit-testing flask mocking python-requests