2013-04-17 11 views
9

तो, मैंने अभी 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

बस भविष्य के दर्शकों के लिए, प्रश्नकर्ता नकली करना चाहता था एक बाहरी एपीआई कॉल बाहर। खुद को देखने के लिए कॉल नहीं। उस स्थिति में मोजे बहुत समझदार लगते हैं। – 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 में सब है:

पैच (लक्ष्य, नई = डिफ़ॉल्ट, कल्पना = कोई नहीं, बनाने के = झूठी, 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 
संबंधित मुद्दे