10

所以,我刚刚开始在 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')

我现在想做的是使用 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

我如何实现这一目标?

4

2 回答 2

12

您快到了。你只是稍微不正确地调用它。

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'})]
    )

您还可以测试响应是正确的类型并且具有正确的内容。

于 2013-04-17T23:30:47.083 回答
3

这一切都在文档中:

补丁(目标,new=DEFAULT,spec=None,create=False,spec_set=None,autospec=None,new_callable=None,**kwargs)

目标应该是格式为“package.module.ClassName”的字符串。

from mock import patch

# or @patch('requests.get')
@patch.object(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
于 2013-04-17T20:35:48.100 回答