2013-04-17 4 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から)

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 
関連する問題