2013-04-17 2 views
9

그래서 방금 장고 프로젝트에서 모의 ​​작업을 시작했습니다. 원격 가입 요청을 확인하기 위해 원격 API에 대한 요청을 만드는 뷰의 일부를 조롱하려고합니다 (내가 작업중인 사양에 따라 확인하는 형식).파이썬 모의, django 및 요청

I과 유사한이 무엇 :

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/ko/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로 만들 수 없음)

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