所以,我刚刚开始在 Django 项目中使用 mock。我正在尝试模拟 View 的一部分,该 View 向远程 API 发出请求以确认订阅请求是真实的(根据我正在努力的规范进行的一种验证形式)。
我所拥有的类似于:
class SubscriptionView(View):
def post(self, request, **kwargs):
remote_url = request.POST.get('remote_url')
if remote_url:
response = requests.get(remote_url, params={'verify': 'hello'})
if response.status_code != 200:
return HttpResponse('Verification of request failed')
我现在想做的是使用 mock 来模拟 requests.get
调用以更改响应,但我不知道如何为补丁装饰器执行此操作。我以为你会做类似的事情:
@patch(requests.get)
def test_response_verify(self):
# make a call to the view using self.app.post (WebTest),
# requests.get makes a suitable fake response from the mock object
我如何实现这一目标?
最佳答案
你快到了。你只是稍微错误地调用它。
from mock import call, patch
@patch('my_app.views.requests')
def test_response_verify(self, mock_requests):
# We setup the mock, this may look like magic but it works, return_value is
# a special attribute on a mock, it is what is returned when it is called
# So this is saying we want the return value of requests.get to have an
# status code attribute of 200
mock_requests.get.return_value.status_code = 200
# Here we make the call to the view
response = SubscriptionView().post(request, {'remote_url': 'some_url'})
self.assertEqual(
mock_requests.get.call_args_list,
[call('some_url', params={'verify': 'hello'})]
)
您还可以测试响应的类型是否正确以及内容是否正确。
关于Python 模拟、django 和请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069541/