2013-04-17 50 views
9

所以,我刚开始使用模拟Django项目。我试图模拟出一部分视图,它向远程API发出请求,以确认订阅请求是真实的(根据我正在使用的规范进行的验证形式)。Python模拟,Django和请求

我有什么似的:

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

我现在想要做的就是使用模拟来模拟出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 

我该如何做到这一点?

+0

使用模拟的死亡?还有django.test.client.RequestFactory - https://docs.djangoproject.com/en/1.5/topics/testing/advanced/#module-django.test.client – David

+3

只为未来的观众,提问者想模拟外部API调用。不是对视图本身的调用。在这种情况下,嘲笑似乎非常明智。 – aychedee

+0

按照@aychedee,这确实是我在这个问题上所追求的目标。 – jvc26

回答

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

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

3

这一切都在the documentation

补丁(目标,新= DEFAULT,规格=无,建立=假spec_set =无,autospec =无,new_callable =无,** 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