How can I mock requests and the response?

I am trying to use Pythons mock package to mock Pythons requests module. What are the basic calls to get me working in below scenario?

In my views.py, I have a function that makes variety of requests.get() calls with different response each time

    def myview(request):
      res1 = requests.get('aurl')
      res2 = request.get('burl')
      res3 = request.get('curl')

In my test class I want to do something like this but cannot figure out exact method calls

Step 1:

    # Mock the requests module
    # when mockedRequests.get('aurl') is called then return 'a response'
    # when mockedRequests.get('burl') is called then return 'b response'
    # when mockedRequests.get('curl') is called then return 'c response'

Step 2:

Call my view

Step 3:

verify response contains 'a response', 'b response' , 'c response'

How can I complete Step 1 (mocking the requests module)?

Here is what worked for me:

    import mock
    @mock.patch('requests.get', mock.Mock(side_effect = lambda k:{'aurl': 'a response', 'burl' : 'b response'}.get(k, 'unhandled request %s'%k)))

From: stackoverflow.com/q/15753390

Back to homepage or read more recommendations: