Python mock,django和requests

jvc*_*c26 10 python django unit-testing mocking django-testing

所以,我刚刚开始在Django项目中使用mock.我正在尝试模拟一个视图的一部分,该视图向远程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')
Run Code Online (Sandbox Code Playgroud)

我现在想要做的是使用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
Run Code Online (Sandbox Code Playgroud)

我该如何实现这一目标?

ayc*_*dee 11

你快到了.你只是稍微错误地调用它.

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'})]
    )
Run Code Online (Sandbox Code Playgroud)

您还可以测试响应是否正确,并且具有正确的内容.