Python mock,django和requests

时间:2013-04-17 20:20:18

标签: 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')

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

我如何实现这一目标?

2 个答案:

答案 0 :(得分: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'})]
    )

您还可以测试响应是否正确并且内容正确。

答案 1 :(得分:3)

全部在the documentation

  

patch(target,new = DEFAULT,spec = None,create = False,spec_set = None,autospec = None,new_callable = None,** kwargs)

     

target应该是'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